From edc97a0df2fbff05dd03483938425d1590440c82 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Fri, 17 May 2024 08:22:29 +0000 Subject: [PATCH 001/366] Fix verbatim paths used with include! When using `concat!` to join paths, the Unix path separator (`/`) is often used. This breaks on Windows if the base path is a verbatim path (i.e. starts with `\\?\`). --- compiler/rustc_expand/src/base.rs | 8 +++++++- .../import-macro-verbatim/include/include.txt | 1 + tests/run-make/import-macro-verbatim/rmake.rs | 8 ++++++++ tests/run-make/import-macro-verbatim/verbatim.rs | 12 ++++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/run-make/import-macro-verbatim/include/include.txt create mode 100644 tests/run-make/import-macro-verbatim/rmake.rs create mode 100644 tests/run-make/import-macro-verbatim/verbatim.rs diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index c195d6925889..23ff735aac8c 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1,5 +1,6 @@ use std::default::Default; use std::iter; +use std::path::Component::Prefix; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -1293,7 +1294,12 @@ pub fn resolve_path(sess: &Session, path: impl Into, span: Span) -> PRe base_path.push(path); Ok(base_path) } else { - Ok(path) + // This ensures that Windows verbatim paths are fixed if mixed path separators are used, + // which can happen when `concat!` is used to join paths. + match path.components().next() { + Some(Prefix(prefix)) if prefix.kind().is_verbatim() => Ok(path.components().collect()), + _ => Ok(path), + } } } diff --git a/tests/run-make/import-macro-verbatim/include/include.txt b/tests/run-make/import-macro-verbatim/include/include.txt new file mode 100644 index 000000000000..63d71b14c1df --- /dev/null +++ b/tests/run-make/import-macro-verbatim/include/include.txt @@ -0,0 +1 @@ +static TEST: &str = "Hello World!"; diff --git a/tests/run-make/import-macro-verbatim/rmake.rs b/tests/run-make/import-macro-verbatim/rmake.rs new file mode 100644 index 000000000000..d2bf626e0aaa --- /dev/null +++ b/tests/run-make/import-macro-verbatim/rmake.rs @@ -0,0 +1,8 @@ +//@ only-windows other platforms do not have Windows verbatim paths +use run_make_support::rustc; +fn main() { + // Canonicalizing the path ensures that it's verbatim (i.e. starts with `\\?\`) + let mut path = std::fs::canonicalize(file!()).unwrap(); + path.pop(); + rustc().input("verbatim.rs").env("VERBATIM_DIR", path).run(); +} diff --git a/tests/run-make/import-macro-verbatim/verbatim.rs b/tests/run-make/import-macro-verbatim/verbatim.rs new file mode 100644 index 000000000000..56a83673c1f5 --- /dev/null +++ b/tests/run-make/import-macro-verbatim/verbatim.rs @@ -0,0 +1,12 @@ +//! Include a file by concating the verbatim path using `/` instead of `\` + +include!(concat!(env!("VERBATIM_DIR"), "/include/include.txt")); +fn main() { + assert_eq!(TEST, "Hello World!"); + + let s = include_str!(concat!(env!("VERBATIM_DIR"), "/include/include.txt")); + assert_eq!(s, "static TEST: &str = \"Hello World!\";\n"); + + let b = include_bytes!(concat!(env!("VERBATIM_DIR"), "/include/include.txt")); + assert_eq!(b, b"static TEST: &str = \"Hello World!\";\n"); +} From 0d300ac678cfc69724861c7c94c3daa3eb15fac1 Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Fri, 13 Sep 2024 14:01:02 -0700 Subject: [PATCH 002/366] Update StableMIR doc to reflect current status We no longer use git subtree, and we have 2 different crates. --- compiler/stable_mir/README.md | 102 +++++----------------------------- 1 file changed, 14 insertions(+), 88 deletions(-) diff --git a/compiler/stable_mir/README.md b/compiler/stable_mir/README.md index 31dee955f491..89f610e110e7 100644 --- a/compiler/stable_mir/README.md +++ b/compiler/stable_mir/README.md @@ -1,93 +1,25 @@ -This crate is regularly synced with its mirror in the rustc repo at `compiler/rustc_smir`. +This crate is currently developed in-tree together with the compiler. -We use `git subtree` for this to preserve commits and allow the rustc repo to -edit these crates without having to touch this repo. This keeps the crates compiling -while allowing us to independently work on them here. The effort of keeping them in -sync is pushed entirely onto us, without affecting rustc workflows negatively. -This may change in the future, but changes to policy should only be done via a -compiler team MCP. - -## Instructions for working on this crate locally - -Since the crate is the same in the rustc repo and here, the dependencies on rustc_* crates -will only either work here or there, but never in both places at the same time. Thus we use -optional dependencies on the rustc_* crates, requiring local development to use - -``` -cargo build --no-default-features -Zavoid-dev-deps -``` - -in order to compile successfully. - -## Instructions for syncing - -### Updating this repository - -In the rustc repo, execute - -``` -git subtree push --prefix=compiler/rustc_smir url_to_your_fork_of_project_stable_mir some_feature_branch -``` - -and then open a PR of your `some_feature_branch` against https://github.com/rust-lang/project-stable-mir - -### Updating the rustc library - -First we need to bump our stack limit, as the rustc repo otherwise quickly hits that: - -``` -ulimit -s 60000 -``` - -#### Maximum function recursion depth (1000) reached - -Then we need to disable `dash` as the default shell for sh scripts, as otherwise we run into a -hard limit of a recursion depth of 1000: - -``` -sudo dpkg-reconfigure dash -``` - -and then select `No` to disable dash. - - -#### Patching your `git worktree` - -The regular git worktree does not scale to repos of the size of the rustc repo. -So download the `git-subtree.sh` from https://github.com/gitgitgadget/git/pull/493/files and run - -``` -sudo cp --backup /path/to/patched/git-subtree.sh /usr/lib/git-core/git-subtree -sudo chmod --reference=/usr/lib/git-core/git-subtree~ /usr/lib/git-core/git-subtree -sudo chown --reference=/usr/lib/git-core/git-subtree~ /usr/lib/git-core/git-subtree -``` - -#### Actually doing a sync - -In the rustc repo, execute - -``` -git subtree pull --prefix=compiler/rustc_smir https://github.com/rust-lang/project-stable-mir smir -``` - -Note: only ever sync to rustc from the project-stable-mir's `smir` branch. Do not sync with your own forks. - -Then open a PR against rustc just like a regular PR. +Our goal is to start publishing `stable_mir` into crates.io. +Until then, users will use this as any other rustc crate, via extern crate. ## Stable MIR Design The stable-mir will follow a similar approach to proc-macro2. It’s -implementation will eventually be broken down into two main crates: +implementation is done using two main crates: - `stable_mir`: Public crate, to be published on crates.io, which will contain -the stable data structure as well as proxy APIs to make calls to the -compiler. -- `rustc_smir`: The compiler crate that will translate from internal MIR to -SMIR. This crate will also implement APIs that will be invoked by -stable-mir to query the compiler for more information. +the stable data structure as well as calls to `rustc_smir` APIs and +translation between stable and internal constructs. +- `rustc_smir`: This crate implements the public APIs to the compiler. +It is responsible for gathering all the information requested, and providing +the data in its unstable form. -This will help tools to communicate with the rust compiler via stable APIs. Tools will depend on -`stable_mir` crate, which will invoke the compiler using APIs defined in `rustc_smir`. I.e.: +I.e., +tools will depend on `stable_mir` crate, +which will invoke the compiler using APIs defined in `rustc_smir`. + +I.e.: ``` ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ @@ -104,9 +36,3 @@ This will help tools to communicate with the rust compiler via stable APIs. Tool More details can be found here: https://hackmd.io/XhnYHKKuR6-LChhobvlT-g?view - -For now, the code for these two crates are in separate modules of this crate. -The modules have the same name for simplicity. We also have a third module, -`rustc_internal` which will expose APIs and definitions that allow users to -gather information from internal MIR constructs that haven't been exposed in -the `stable_mir` module. From 9368b9f57e7e3a82b5becdfd17a1eeb606e6fd5f Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 30 Sep 2024 00:34:58 -0400 Subject: [PATCH 003/366] Debug assert that unevaluated consts have the right substs --- compiler/rustc_middle/src/ty/consts.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 73d0acf95f4f..ebc6cac3c429 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -109,6 +109,7 @@ impl<'tcx> Const<'tcx> { #[inline] pub fn new_unevaluated(tcx: TyCtxt<'tcx>, uv: ty::UnevaluatedConst<'tcx>) -> Const<'tcx> { + tcx.debug_assert_args_compatible(uv.def, uv.args); Const::new(tcx, ty::ConstKind::Unevaluated(uv)) } From 2239f1c5cd6da232b5d92765deace77519bdd209 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 30 Sep 2024 01:00:38 -0400 Subject: [PATCH 004/366] Validate ExistentialPredicate args --- .../src/hir_ty_lowering/dyn_compatibility.rs | 3 +- compiler/rustc_middle/src/ty/context.rs | 20 +++++++++ compiler/rustc_passes/src/reachable.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 8 ++-- .../cfi/typeid/itanium_cxx_abi/transform.rs | 21 +++++---- .../rustc_smir/src/rustc_internal/internal.rs | 20 +++++---- .../rustc_smir/src/rustc_smir/convert/ty.rs | 4 +- compiler/rustc_type_ir/src/interner.rs | 8 ++-- compiler/rustc_type_ir/src/predicate.rs | 45 ++++++++++++++++++- compiler/rustc_type_ir/src/relate.rs | 4 +- 10 files changed, 103 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index e7b8e6e69b0c..ff90f89f6668 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -250,7 +250,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } }) .collect(); - let args = tcx.mk_args(&args); let span = i.bottom().1; let empty_generic_args = hir_trait_bounds.iter().any(|(hir_bound, _)| { @@ -283,7 +282,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .emit(); } - ty::ExistentialTraitRef { def_id: trait_ref.def_id, args } + ty::ExistentialTraitRef::new(tcx, trait_ref.def_id, args) }) }); diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 2ffb273cb6fc..711dc80e933e 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -279,6 +279,26 @@ impl<'tcx> Interner for TyCtxt<'tcx> { self.debug_assert_args_compatible(def_id, args); } + /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection` + /// are compatible with the `DefId`. Since we're missing a `Self` type, stick on + /// a dummy self type and forward to `debug_assert_args_compatible`. + fn debug_assert_existential_args_compatible( + self, + def_id: Self::DefId, + args: Self::GenericArgs, + ) { + // FIXME: We could perhaps add a `skip: usize` to `debug_assert_args_compatible` + // to avoid needing to reintern the set of args... + if cfg!(debug_assertions) { + self.debug_assert_args_compatible( + def_id, + self.mk_args_from_iter( + [self.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()), + ), + ); + } + } + fn mk_type_list_from_iter(self, args: I) -> T::Output where I: Iterator, diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index 925ee2620228..0cb0e961c0e4 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -322,7 +322,7 @@ impl<'tcx> ReachableContext<'tcx> { self.visit(ty); // Manually visit to actually see the trait's `DefId`. Type visitors won't see it if let Some(trait_ref) = dyn_ty.principal() { - let ExistentialTraitRef { def_id, args } = trait_ref.skip_binder(); + let ExistentialTraitRef { def_id, args, .. } = trait_ref.skip_binder(); self.visit_def_id(def_id, "", &""); self.visit(args); } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 9094b00fbfb4..0f820654ec81 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -32,8 +32,8 @@ use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, use rustc_middle::query::Providers; use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{ - self, Const, GenericArgs, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable, - TypeVisitable, TypeVisitor, + self, Const, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, + TypeVisitor, }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; @@ -246,10 +246,10 @@ where ty::ExistentialPredicate::Trait(trait_ref) => trait_ref, ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx), ty::ExistentialPredicate::AutoTrait(def_id) => { - ty::ExistentialTraitRef { def_id, args: GenericArgs::empty() } + ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty()) } }; - let ty::ExistentialTraitRef { def_id, args: _ } = trait_ref; + let ty::ExistentialTraitRef { def_id, .. } = trait_ref; try_visit!(self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)); } } diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index 5f7184a42407..a97a00f6ac08 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -245,11 +245,15 @@ fn trait_object_ty<'tcx>(tcx: TyCtxt<'tcx>, poly_trait_ref: ty::PolyTraitRef<'tc alias_ty.to_ty(tcx), ); debug!("Resolved {:?} -> {resolved}", alias_ty.to_ty(tcx)); - ty::ExistentialPredicate::Projection(ty::ExistentialProjection { - def_id: assoc_ty.def_id, - args: ty::ExistentialTraitRef::erase_self_ty(tcx, super_trait_ref).args, - term: resolved.into(), - }) + ty::ExistentialPredicate::Projection( + ty::ExistentialProjection::erase_self_ty( + tcx, + ty::ProjectionPredicate { + projection_term: alias_ty.into(), + term: resolved.into(), + }, + ), + ) }) }) }) @@ -318,10 +322,11 @@ pub fn transform_instance<'tcx>( .lang_items() .drop_trait() .unwrap_or_else(|| bug!("typeid_for_instance: couldn't get drop_trait lang item")); - let predicate = ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef { + let predicate = ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::new_from_args( + tcx, def_id, - args: List::empty(), - }); + ty::List::empty(), + )); let predicates = tcx.mk_poly_existential_predicates(&[ty::Binder::dummy(predicate)]); let self_ty = Ty::new_dynamic(tcx, predicates, tcx.lifetimes.re_erased, ty::Dyn); instance.args = tcx.mk_args_trait(self_ty, List::empty()); diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index e9c3b3ffc1dd..7be7db1fd3d3 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -380,11 +380,12 @@ impl RustcInternal for ExistentialProjection { type T<'tcx> = rustc_ty::ExistentialProjection<'tcx>; fn internal<'tcx>(&self, tables: &mut Tables<'_>, tcx: TyCtxt<'tcx>) -> Self::T<'tcx> { - rustc_ty::ExistentialProjection { - def_id: self.def_id.0.internal(tables, tcx), - args: self.generic_args.internal(tables, tcx), - term: self.term.internal(tables, tcx), - } + rustc_ty::ExistentialProjection::new_from_args( + tcx, + self.def_id.0.internal(tables, tcx), + self.generic_args.internal(tables, tcx), + self.term.internal(tables, tcx), + ) } } @@ -403,10 +404,11 @@ impl RustcInternal for ExistentialTraitRef { type T<'tcx> = rustc_ty::ExistentialTraitRef<'tcx>; fn internal<'tcx>(&self, tables: &mut Tables<'_>, tcx: TyCtxt<'tcx>) -> Self::T<'tcx> { - rustc_ty::ExistentialTraitRef { - def_id: self.def_id.0.internal(tables, tcx), - args: self.generic_args.internal(tables, tcx), - } + rustc_ty::ExistentialTraitRef::new_from_args( + tcx, + self.def_id.0.internal(tables, tcx), + self.generic_args.internal(tables, tcx), + ) } } diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index b9372283febf..ef2ee9a166af 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -68,7 +68,7 @@ impl<'tcx> Stable<'tcx> for ty::ExistentialTraitRef<'tcx> { type T = stable_mir::ty::ExistentialTraitRef; fn stable(&self, tables: &mut Tables<'_>) -> Self::T { - let ty::ExistentialTraitRef { def_id, args } = self; + let ty::ExistentialTraitRef { def_id, args, .. } = self; stable_mir::ty::ExistentialTraitRef { def_id: tables.trait_def(*def_id), generic_args: args.stable(tables), @@ -95,7 +95,7 @@ impl<'tcx> Stable<'tcx> for ty::ExistentialProjection<'tcx> { type T = stable_mir::ty::ExistentialProjection; fn stable(&self, tables: &mut Tables<'_>) -> Self::T { - let ty::ExistentialProjection { def_id, args, term } = self; + let ty::ExistentialProjection { def_id, args, term, .. } = self; stable_mir::ty::ExistentialProjection { def_id: tables.trait_def(*def_id), generic_args: args.stable(tables), diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index b2ac67efef61..3f5d19108f22 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -15,9 +15,7 @@ use crate::solve::{ CanonicalInput, ExternalConstraintsData, PredefinedOpaquesData, QueryResult, SolverMode, }; use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable}; -use crate::{ - search_graph, {self as ty}, -}; +use crate::{self as ty, search_graph}; pub trait Interner: Sized @@ -173,6 +171,10 @@ pub trait Interner: fn debug_assert_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs); + /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection` + /// are compatible with the `DefId`. + fn debug_assert_existential_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs); + fn mk_type_list_from_iter(self, args: I) -> T::Output where I: Iterator, diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index 76065c10d190..fed689652a59 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -289,9 +289,26 @@ impl ty::Binder> { pub struct ExistentialTraitRef { pub def_id: I::DefId, pub args: I::GenericArgs, + /// This field exists to prevent the creation of `ExistentialTraitRef` without + /// calling [`ExistentialTraitRef::new_from_args`]. + _use_existential_trait_ref_new_instead: (), } impl ExistentialTraitRef { + pub fn new_from_args(interner: I, trait_def_id: I::DefId, args: I::GenericArgs) -> Self { + interner.debug_assert_existential_args_compatible(trait_def_id, args); + Self { def_id: trait_def_id, args, _use_existential_trait_ref_new_instead: () } + } + + pub fn new( + interner: I, + trait_def_id: I::DefId, + args: impl IntoIterator>, + ) -> Self { + let args = interner.mk_args_from_iter(args.into_iter().map(Into::into)); + Self::new_from_args(interner, trait_def_id, args) + } + pub fn erase_self_ty(interner: I, trait_ref: TraitRef) -> ExistentialTraitRef { // Assert there is a Self. trait_ref.args.type_at(0); @@ -299,6 +316,7 @@ impl ExistentialTraitRef { ExistentialTraitRef { def_id: trait_ref.def_id, args: interner.mk_args(&trait_ref.args.as_slice()[1..]), + _use_existential_trait_ref_new_instead: (), } } @@ -336,9 +354,33 @@ pub struct ExistentialProjection { pub def_id: I::DefId, pub args: I::GenericArgs, pub term: I::Term, + + /// This field exists to prevent the creation of `ExistentialProjection` + /// without using [`ExistentialProjection::new_from_args`]. + use_existential_projection_new_instead: (), } impl ExistentialProjection { + pub fn new_from_args( + interner: I, + def_id: I::DefId, + args: I::GenericArgs, + term: I::Term, + ) -> ExistentialProjection { + interner.debug_assert_existential_args_compatible(def_id, args); + Self { def_id, args, term, use_existential_projection_new_instead: () } + } + + pub fn new( + interner: I, + def_id: I::DefId, + args: impl IntoIterator>, + term: I::Term, + ) -> ExistentialProjection { + let args = interner.mk_args_from_iter(args.into_iter().map(Into::into)); + Self::new_from_args(interner, def_id, args, term) + } + /// Extracts the underlying existential trait reference from this projection. /// For example, if this is a projection of `exists T. ::Item == X`, /// then this function would return an `exists T. T: Iterator` existential trait @@ -347,7 +389,7 @@ impl ExistentialProjection { let def_id = interner.parent(self.def_id); let args_count = interner.generics_of(def_id).count() - 1; let args = interner.mk_args(&self.args.as_slice()[..args_count]); - ExistentialTraitRef { def_id, args } + ExistentialTraitRef { def_id, args, _use_existential_trait_ref_new_instead: () } } pub fn with_self_ty(&self, interner: I, self_ty: I::Ty) -> ProjectionPredicate { @@ -372,6 +414,7 @@ impl ExistentialProjection { def_id: projection_predicate.projection_term.def_id, args: interner.mk_args(&projection_predicate.projection_term.args.as_slice()[1..]), term: projection_predicate.term, + use_existential_projection_new_instead: (), } } } diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index 9c725f34d8e5..61dd2390c803 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -308,7 +308,7 @@ impl Relate for ty::ExistentialProjection { a.args, b.args, )?; - Ok(ty::ExistentialProjection { def_id: a.def_id, args, term }) + Ok(ty::ExistentialProjection::new_from_args(relation.cx(), a.def_id, args, term)) } } } @@ -348,7 +348,7 @@ impl Relate for ty::ExistentialTraitRef { })) } else { let args = relate_args_invariantly(relation, a.args, b.args)?; - Ok(ty::ExistentialTraitRef { def_id: a.def_id, args }) + Ok(ty::ExistentialTraitRef::new_from_args(relation.cx(), a.def_id, args)) } } } From 7a3a98d8949dcfd98c9509b0869b6bca00bf5017 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Wed, 2 Oct 2024 19:57:59 +0200 Subject: [PATCH 005/366] Fix target_vendor in QNX Neutrino targets The `x86_64-pc-nto-qnx710` and `i586-pc-nto-qnx700` targets have `pc` in their target triple names, but the vendor was set to the default `"unknown"`. --- compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs | 1 + compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs b/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs index 2519b935c03a..7648f81fd4d9 100644 --- a/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs +++ b/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs @@ -21,6 +21,7 @@ pub(crate) fn target() -> Target { "-Vgcc_ntox86_cxx", ]), env: "nto70".into(), + vendor: "pc".into(), stack_probes: StackProbeType::Inline, ..base::nto_qnx::opts() }, diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs index 1aa82494a499..245a5f067654 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs @@ -21,6 +21,7 @@ pub(crate) fn target() -> Target { "-Vgcc_ntox86_64_cxx", ]), env: "nto71".into(), + vendor: "pc".into(), ..base::nto_qnx::opts() }, } From f2a80a0f891a09301d43c269b8704bcb2817a419 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 17 Aug 2024 13:03:27 -0400 Subject: [PATCH 006/366] A raw ref of a deref is always safe --- compiler/rustc_mir_build/src/check_unsafety.rs | 12 +++--------- tests/ui/static/raw-ref-deref-without-unsafe.rs | 1 - .../ui/static/raw-ref-deref-without-unsafe.stderr | 2 +- tests/ui/unsafe/place-expr-safe.rs | 14 ++++++++++++++ 4 files changed, 18 insertions(+), 11 deletions(-) create mode 100644 tests/ui/unsafe/place-expr-safe.rs diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 8512763a595d..0f0286fab291 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -512,17 +512,11 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { // THIR desugars UNSAFE_STATIC into *UNSAFE_STATIC_REF, where // UNSAFE_STATIC_REF holds the addr of the UNSAFE_STATIC, so: take two steps && let ExprKind::Deref { arg } = self.thir[arg].kind - // FIXME(workingjubiee): we lack a clear reason to reject ThreadLocalRef here, - // but we also have no conclusive reason to allow it either! - && let ExprKind::StaticRef { .. } = self.thir[arg].kind { - // A raw ref to a place expr, even an "unsafe static", is okay! - // We short-circuit to not recursively traverse this expression. + // Taking a raw ref to a deref place expr is always safe. + // Make sure the expression we're deref'ing is safe, though. + visit::walk_expr(self, &self.thir[arg]); return; - // note: const_mut_refs enables this code, and it currently remains unsafe: - // static mut BYTE: u8 = 0; - // static mut BYTE_PTR: *mut u8 = unsafe { addr_of_mut!(BYTE) }; - // static mut DEREF_BYTE_PTR: *mut u8 = unsafe { addr_of_mut!(*BYTE_PTR) }; } } ExprKind::Deref { arg } => { diff --git a/tests/ui/static/raw-ref-deref-without-unsafe.rs b/tests/ui/static/raw-ref-deref-without-unsafe.rs index 289e55b76382..7146c564e91d 100644 --- a/tests/ui/static/raw-ref-deref-without-unsafe.rs +++ b/tests/ui/static/raw-ref-deref-without-unsafe.rs @@ -9,7 +9,6 @@ static mut BYTE_PTR: *mut u8 = ptr::addr_of_mut!(BYTE); // (it's fine to create raw refs to places!) the following derefs the ptr before creating its ref! static mut DEREF_BYTE_PTR: *mut u8 = ptr::addr_of_mut!(*BYTE_PTR); //~^ ERROR: use of mutable static -//~| ERROR: dereference of raw pointer fn main() { let _ = unsafe { DEREF_BYTE_PTR }; diff --git a/tests/ui/static/raw-ref-deref-without-unsafe.stderr b/tests/ui/static/raw-ref-deref-without-unsafe.stderr index f034499bbb5f..d654d4b6e6b7 100644 --- a/tests/ui/static/raw-ref-deref-without-unsafe.stderr +++ b/tests/ui/static/raw-ref-deref-without-unsafe.stderr @@ -14,6 +14,6 @@ LL | static mut DEREF_BYTE_PTR: *mut u8 = ptr::addr_of_mut!(*BYTE_PTR); | = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0133`. diff --git a/tests/ui/unsafe/place-expr-safe.rs b/tests/ui/unsafe/place-expr-safe.rs new file mode 100644 index 000000000000..2590ea740465 --- /dev/null +++ b/tests/ui/unsafe/place-expr-safe.rs @@ -0,0 +1,14 @@ +//@ check-pass + +fn main() { + let ptr = std::ptr::null_mut::(); + let addr = &raw const *ptr; + + let local = 1; + let ptr = &local as *const i32; + let addr = &raw const *ptr; + + let boxed = Box::new(1); + let ptr = &*boxed as *const i32; + let addr = &raw const *ptr; +} From 367183bc0c64d2835dbfe498d995072c3d426ffe Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 18 Aug 2024 12:33:21 -0400 Subject: [PATCH 007/366] Don't emit null pointer lint for raw ref of null deref --- compiler/rustc_lint/src/builtin.rs | 26 ++++++++++++------- .../rustc_mir_build/src/check_unsafety.rs | 2 -- tests/ui/lint/lint-deref-nullptr.rs | 4 +-- tests/ui/lint/lint-deref-nullptr.stderr | 14 +--------- tests/ui/static/raw-ref-deref-with-unsafe.rs | 9 ++++--- .../ui/static/raw-ref-deref-without-unsafe.rs | 6 ++--- .../raw-ref-deref-without-unsafe.stderr | 8 ------ 7 files changed, 28 insertions(+), 41 deletions(-) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 8bd9c899a628..0d66ea54bd97 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2657,8 +2657,8 @@ declare_lint! { /// /// ### Explanation /// - /// Dereferencing a null pointer causes [undefined behavior] even as a place expression, - /// like `&*(0 as *const i32)` or `addr_of!(*(0 as *const i32))`. + /// Dereferencing a null pointer causes [undefined behavior] if it is accessed + /// (loaded from or stored to). /// /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html pub DEREF_NULLPTR, @@ -2673,14 +2673,14 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { /// test if expression is a null ptr fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { match &expr.kind { - rustc_hir::ExprKind::Cast(expr, ty) => { - if let rustc_hir::TyKind::Ptr(_) = ty.kind { + hir::ExprKind::Cast(expr, ty) => { + if let hir::TyKind::Ptr(_) = ty.kind { return is_zero(expr) || is_null_ptr(cx, expr); } } // check for call to `core::ptr::null` or `core::ptr::null_mut` - rustc_hir::ExprKind::Call(path, _) => { - if let rustc_hir::ExprKind::Path(ref qpath) = path.kind { + hir::ExprKind::Call(path, _) => { + if let hir::ExprKind::Path(ref qpath) = path.kind { if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() { return matches!( cx.tcx.get_diagnostic_name(def_id), @@ -2697,7 +2697,7 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { /// test if expression is the literal `0` fn is_zero(expr: &hir::Expr<'_>) -> bool { match &expr.kind { - rustc_hir::ExprKind::Lit(lit) => { + hir::ExprKind::Lit(lit) => { if let LitKind::Int(a, _) = lit.node { return a == 0; } @@ -2707,8 +2707,16 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { false } - if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind { - if is_null_ptr(cx, expr_deref) { + if let hir::ExprKind::Unary(hir::UnOp::Deref, expr_deref) = expr.kind + && is_null_ptr(cx, expr_deref) + { + if let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::AddrOf(hir::BorrowKind::Raw, ..), + .. + }) = cx.tcx.parent_hir_node(expr.hir_id) + { + // `&raw *NULL` is ok. + } else { cx.emit_span_lint(DEREF_NULLPTR, expr.span, BuiltinDerefNullptr { label: expr.span, }); diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 0f0286fab291..f3e6301d9d16 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -509,8 +509,6 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } ExprKind::RawBorrow { arg, .. } => { if let ExprKind::Scope { value: arg, .. } = self.thir[arg].kind - // THIR desugars UNSAFE_STATIC into *UNSAFE_STATIC_REF, where - // UNSAFE_STATIC_REF holds the addr of the UNSAFE_STATIC, so: take two steps && let ExprKind::Deref { arg } = self.thir[arg].kind { // Taking a raw ref to a deref place expr is always safe. diff --git a/tests/ui/lint/lint-deref-nullptr.rs b/tests/ui/lint/lint-deref-nullptr.rs index d052dbd9b647..f83d88309b9a 100644 --- a/tests/ui/lint/lint-deref-nullptr.rs +++ b/tests/ui/lint/lint-deref-nullptr.rs @@ -27,9 +27,9 @@ fn f() { let ub = &*ptr::null_mut::(); //~^ ERROR dereferencing a null pointer ptr::addr_of!(*ptr::null::()); - //~^ ERROR dereferencing a null pointer + // ^^ OKAY ptr::addr_of_mut!(*ptr::null_mut::()); - //~^ ERROR dereferencing a null pointer + // ^^ OKAY let offset = ptr::addr_of!((*ptr::null::()).field); //~^ ERROR dereferencing a null pointer } diff --git a/tests/ui/lint/lint-deref-nullptr.stderr b/tests/ui/lint/lint-deref-nullptr.stderr index c6f432e4e420..175431b2994b 100644 --- a/tests/ui/lint/lint-deref-nullptr.stderr +++ b/tests/ui/lint/lint-deref-nullptr.stderr @@ -46,23 +46,11 @@ error: dereferencing a null pointer LL | let ub = &*ptr::null_mut::(); | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed -error: dereferencing a null pointer - --> $DIR/lint-deref-nullptr.rs:29:23 - | -LL | ptr::addr_of!(*ptr::null::()); - | ^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed - -error: dereferencing a null pointer - --> $DIR/lint-deref-nullptr.rs:31:27 - | -LL | ptr::addr_of_mut!(*ptr::null_mut::()); - | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed - error: dereferencing a null pointer --> $DIR/lint-deref-nullptr.rs:33:36 | LL | let offset = ptr::addr_of!((*ptr::null::()).field); | ^^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed -error: aborting due to 10 previous errors +error: aborting due to 8 previous errors diff --git a/tests/ui/static/raw-ref-deref-with-unsafe.rs b/tests/ui/static/raw-ref-deref-with-unsafe.rs index 0974948b3a06..5beed6971792 100644 --- a/tests/ui/static/raw-ref-deref-with-unsafe.rs +++ b/tests/ui/static/raw-ref-deref-with-unsafe.rs @@ -1,13 +1,14 @@ //@ check-pass use std::ptr; -// This code should remain unsafe because of the two unsafe operations here, -// even if in a hypothetical future we deem all &raw (const|mut) *ptr exprs safe. - static mut BYTE: u8 = 0; static mut BYTE_PTR: *mut u8 = ptr::addr_of_mut!(BYTE); + +// This code should remain unsafe because reading from a static mut is *always* unsafe. + // An unsafe static's ident is a place expression in its own right, so despite the above being safe -// (it's fine to create raw refs to places!) the following derefs the ptr before creating its ref +// (it's fine to create raw refs to places!) the following *reads* from the static mut place before +// derefing it explicitly with the `*` below. static mut DEREF_BYTE_PTR: *mut u8 = unsafe { ptr::addr_of_mut!(*BYTE_PTR) }; fn main() { diff --git a/tests/ui/static/raw-ref-deref-without-unsafe.rs b/tests/ui/static/raw-ref-deref-without-unsafe.rs index 7146c564e91d..97d08c815bf9 100644 --- a/tests/ui/static/raw-ref-deref-without-unsafe.rs +++ b/tests/ui/static/raw-ref-deref-without-unsafe.rs @@ -1,10 +1,10 @@ use std::ptr; -// This code should remain unsafe because of the two unsafe operations here, -// even if in a hypothetical future we deem all &raw (const|mut) *ptr exprs safe. - static mut BYTE: u8 = 0; static mut BYTE_PTR: *mut u8 = ptr::addr_of_mut!(BYTE); + +// This code should remain unsafe because reading from a static mut is *always* unsafe. + // An unsafe static's ident is a place expression in its own right, so despite the above being safe // (it's fine to create raw refs to places!) the following derefs the ptr before creating its ref! static mut DEREF_BYTE_PTR: *mut u8 = ptr::addr_of_mut!(*BYTE_PTR); diff --git a/tests/ui/static/raw-ref-deref-without-unsafe.stderr b/tests/ui/static/raw-ref-deref-without-unsafe.stderr index d654d4b6e6b7..b9c294e5c1f5 100644 --- a/tests/ui/static/raw-ref-deref-without-unsafe.stderr +++ b/tests/ui/static/raw-ref-deref-without-unsafe.stderr @@ -1,11 +1,3 @@ -error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block - --> $DIR/raw-ref-deref-without-unsafe.rs:10:56 - | -LL | static mut DEREF_BYTE_PTR: *mut u8 = ptr::addr_of_mut!(*BYTE_PTR); - | ^^^^^^^^^ dereference of raw pointer - | - = note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior - error[E0133]: use of mutable static is unsafe and requires unsafe function or block --> $DIR/raw-ref-deref-without-unsafe.rs:10:57 | From f954bab4f12292e6125180492a948a62988e3143 Mon Sep 17 00:00:00 2001 From: "Chai T. Rex" Date: Tue, 8 Oct 2024 00:13:59 -0400 Subject: [PATCH 008/366] Stabilize `isqrt` feature --- library/core/benches/lib.rs | 1 - library/core/src/lib.rs | 1 - library/core/src/num/int_macros.rs | 10 +- library/core/src/num/nonzero.rs | 5 +- library/core/src/num/uint_macros.rs | 5 +- library/core/tests/lib.rs | 1 - src/tools/clippy/tests/ui/cast.rs | 1 - src/tools/clippy/tests/ui/cast.stderr | 184 +++++++++++++------------- 8 files changed, 100 insertions(+), 108 deletions(-) diff --git a/library/core/benches/lib.rs b/library/core/benches/lib.rs index 3f1c58bbd720..32d15c386cb1 100644 --- a/library/core/benches/lib.rs +++ b/library/core/benches/lib.rs @@ -8,7 +8,6 @@ #![feature(iter_array_chunks)] #![feature(iter_next_chunk)] #![feature(iter_advance_by)] -#![feature(isqrt)] extern crate test; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index e323e88f2614..a64319aa8473 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -161,7 +161,6 @@ #![feature(ip)] #![feature(is_ascii_octdigit)] #![feature(is_val_statically_known)] -#![feature(isqrt)] #![feature(lazy_get)] #![feature(link_cfg)] #![feature(offset_of_enum)] diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 7241b3ff6a3b..18c7aebc4f97 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -1629,11 +1629,10 @@ macro_rules! int_impl { /// /// Basic usage: /// ``` - /// #![feature(isqrt)] #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_isqrt(), Some(3));")] /// ``` - #[unstable(feature = "isqrt", issue = "116226")] - #[rustc_const_unstable(feature = "isqrt", issue = "116226")] + #[stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -2880,11 +2879,10 @@ macro_rules! int_impl { /// /// Basic usage: /// ``` - /// #![feature(isqrt)] #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")] /// ``` - #[unstable(feature = "isqrt", issue = "116226")] - #[rustc_const_unstable(feature = "isqrt", issue = "116226")] + #[stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index e5c9a7e086ac..f8043d2202cb 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1527,7 +1527,6 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// /// Basic usage: /// ``` - /// #![feature(isqrt)] /// # use std::num::NonZero; /// # /// # fn main() { test().unwrap(); } @@ -1539,8 +1538,8 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// # Some(()) /// # } /// ``` - #[unstable(feature = "isqrt", issue = "116226")] - #[rustc_const_unstable(feature = "isqrt", issue = "116226")] + #[stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index d9036abecc59..4b632e1fb388 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -2753,11 +2753,10 @@ macro_rules! uint_impl { /// /// Basic usage: /// ``` - /// #![feature(isqrt)] #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")] /// ``` - #[unstable(feature = "isqrt", issue = "116226")] - #[rustc_const_unstable(feature = "isqrt", issue = "116226")] + #[stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "isqrt", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 196e91ee3e92..18d57221453f 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -58,7 +58,6 @@ #![feature(int_roundings)] #![feature(ip)] #![feature(is_ascii_octdigit)] -#![feature(isqrt)] #![feature(iter_advance_by)] #![feature(iter_array_chunks)] #![feature(iter_chain)] diff --git a/src/tools/clippy/tests/ui/cast.rs b/src/tools/clippy/tests/ui/cast.rs index 146b04ab8131..0de53a75c623 100644 --- a/src/tools/clippy/tests/ui/cast.rs +++ b/src/tools/clippy/tests/ui/cast.rs @@ -1,7 +1,6 @@ //@no-rustfix #![feature(repr128)] -#![feature(isqrt)] #![allow(incomplete_features)] #![warn( clippy::cast_precision_loss, diff --git a/src/tools/clippy/tests/ui/cast.stderr b/src/tools/clippy/tests/ui/cast.stderr index 7824bdfac25e..452482fc88e2 100644 --- a/src/tools/clippy/tests/ui/cast.stderr +++ b/src/tools/clippy/tests/ui/cast.stderr @@ -1,5 +1,5 @@ error: casting `i32` to `f32` causes a loss of precision (`i32` is 32 bits wide, but `f32`'s mantissa is only 23 bits wide) - --> tests/ui/cast.rs:26:5 + --> tests/ui/cast.rs:25:5 | LL | x0 as f32; | ^^^^^^^^^ @@ -8,37 +8,37 @@ LL | x0 as f32; = help: to override `-D warnings` add `#[allow(clippy::cast_precision_loss)]` error: casting `i64` to `f32` causes a loss of precision (`i64` is 64 bits wide, but `f32`'s mantissa is only 23 bits wide) - --> tests/ui/cast.rs:30:5 + --> tests/ui/cast.rs:29:5 | LL | x1 as f32; | ^^^^^^^^^ error: casting `i64` to `f64` causes a loss of precision (`i64` is 64 bits wide, but `f64`'s mantissa is only 52 bits wide) - --> tests/ui/cast.rs:32:5 + --> tests/ui/cast.rs:31:5 | LL | x1 as f64; | ^^^^^^^^^ error: casting `u32` to `f32` causes a loss of precision (`u32` is 32 bits wide, but `f32`'s mantissa is only 23 bits wide) - --> tests/ui/cast.rs:35:5 + --> tests/ui/cast.rs:34:5 | LL | x2 as f32; | ^^^^^^^^^ error: casting `u64` to `f32` causes a loss of precision (`u64` is 64 bits wide, but `f32`'s mantissa is only 23 bits wide) - --> tests/ui/cast.rs:38:5 + --> tests/ui/cast.rs:37:5 | LL | x3 as f32; | ^^^^^^^^^ error: casting `u64` to `f64` causes a loss of precision (`u64` is 64 bits wide, but `f64`'s mantissa is only 52 bits wide) - --> tests/ui/cast.rs:40:5 + --> tests/ui/cast.rs:39:5 | LL | x3 as f64; | ^^^^^^^^^ error: casting `f32` to `i32` may truncate the value - --> tests/ui/cast.rs:43:5 + --> tests/ui/cast.rs:42:5 | LL | 1f32 as i32; | ^^^^^^^^^^^ @@ -48,7 +48,7 @@ LL | 1f32 as i32; = help: to override `-D warnings` add `#[allow(clippy::cast_possible_truncation)]` error: casting `f32` to `u32` may truncate the value - --> tests/ui/cast.rs:45:5 + --> tests/ui/cast.rs:44:5 | LL | 1f32 as u32; | ^^^^^^^^^^^ @@ -56,7 +56,7 @@ LL | 1f32 as u32; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:45:5 + --> tests/ui/cast.rs:44:5 | LL | 1f32 as u32; | ^^^^^^^^^^^ @@ -65,7 +65,7 @@ LL | 1f32 as u32; = help: to override `-D warnings` add `#[allow(clippy::cast_sign_loss)]` error: casting `f64` to `f32` may truncate the value - --> tests/ui/cast.rs:49:5 + --> tests/ui/cast.rs:48:5 | LL | 1f64 as f32; | ^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL | 1f64 as f32; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `i32` to `i8` may truncate the value - --> tests/ui/cast.rs:51:5 + --> tests/ui/cast.rs:50:5 | LL | 1i32 as i8; | ^^^^^^^^^^ @@ -85,7 +85,7 @@ LL | i8::try_from(1i32); | ~~~~~~~~~~~~~~~~~~ error: casting `i32` to `u8` may truncate the value - --> tests/ui/cast.rs:53:5 + --> tests/ui/cast.rs:52:5 | LL | 1i32 as u8; | ^^^^^^^^^^ @@ -97,7 +97,7 @@ LL | u8::try_from(1i32); | ~~~~~~~~~~~~~~~~~~ error: casting `f64` to `isize` may truncate the value - --> tests/ui/cast.rs:55:5 + --> tests/ui/cast.rs:54:5 | LL | 1f64 as isize; | ^^^^^^^^^^^^^ @@ -105,7 +105,7 @@ LL | 1f64 as isize; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f64` to `usize` may truncate the value - --> tests/ui/cast.rs:57:5 + --> tests/ui/cast.rs:56:5 | LL | 1f64 as usize; | ^^^^^^^^^^^^^ @@ -113,13 +113,13 @@ LL | 1f64 as usize; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f64` to `usize` may lose the sign of the value - --> tests/ui/cast.rs:57:5 + --> tests/ui/cast.rs:56:5 | LL | 1f64 as usize; | ^^^^^^^^^^^^^ error: casting `u32` to `u16` may truncate the value - --> tests/ui/cast.rs:60:5 + --> tests/ui/cast.rs:59:5 | LL | 1f32 as u32 as u16; | ^^^^^^^^^^^^^^^^^^ @@ -131,7 +131,7 @@ LL | u16::try_from(1f32 as u32); | ~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `f32` to `u32` may truncate the value - --> tests/ui/cast.rs:60:5 + --> tests/ui/cast.rs:59:5 | LL | 1f32 as u32 as u16; | ^^^^^^^^^^^ @@ -139,13 +139,13 @@ LL | 1f32 as u32 as u16; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:60:5 + --> tests/ui/cast.rs:59:5 | LL | 1f32 as u32 as u16; | ^^^^^^^^^^^ error: casting `i32` to `i8` may truncate the value - --> tests/ui/cast.rs:65:22 + --> tests/ui/cast.rs:64:22 | LL | let _x: i8 = 1i32 as _; | ^^^^^^^^^ @@ -157,7 +157,7 @@ LL | let _x: i8 = 1i32.try_into(); | ~~~~~~~~~~~~~~~ error: casting `f32` to `i32` may truncate the value - --> tests/ui/cast.rs:67:9 + --> tests/ui/cast.rs:66:9 | LL | 1f32 as i32; | ^^^^^^^^^^^ @@ -165,7 +165,7 @@ LL | 1f32 as i32; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f64` to `i32` may truncate the value - --> tests/ui/cast.rs:69:9 + --> tests/ui/cast.rs:68:9 | LL | 1f64 as i32; | ^^^^^^^^^^^ @@ -173,7 +173,7 @@ LL | 1f64 as i32; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f32` to `u8` may truncate the value - --> tests/ui/cast.rs:71:9 + --> tests/ui/cast.rs:70:9 | LL | 1f32 as u8; | ^^^^^^^^^^ @@ -181,13 +181,13 @@ LL | 1f32 as u8; = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... error: casting `f32` to `u8` may lose the sign of the value - --> tests/ui/cast.rs:71:9 + --> tests/ui/cast.rs:70:9 | LL | 1f32 as u8; | ^^^^^^^^^^ error: casting `u8` to `i8` may wrap around the value - --> tests/ui/cast.rs:76:5 + --> tests/ui/cast.rs:75:5 | LL | 1u8 as i8; | ^^^^^^^^^ @@ -196,31 +196,31 @@ LL | 1u8 as i8; = help: to override `-D warnings` add `#[allow(clippy::cast_possible_wrap)]` error: casting `u16` to `i16` may wrap around the value - --> tests/ui/cast.rs:79:5 + --> tests/ui/cast.rs:78:5 | LL | 1u16 as i16; | ^^^^^^^^^^^ error: casting `u32` to `i32` may wrap around the value - --> tests/ui/cast.rs:81:5 + --> tests/ui/cast.rs:80:5 | LL | 1u32 as i32; | ^^^^^^^^^^^ error: casting `u64` to `i64` may wrap around the value - --> tests/ui/cast.rs:83:5 + --> tests/ui/cast.rs:82:5 | LL | 1u64 as i64; | ^^^^^^^^^^^ error: casting `usize` to `isize` may wrap around the value - --> tests/ui/cast.rs:85:5 + --> tests/ui/cast.rs:84:5 | LL | 1usize as isize; | ^^^^^^^^^^^^^^^ error: casting `usize` to `i8` may truncate the value - --> tests/ui/cast.rs:88:5 + --> tests/ui/cast.rs:87:5 | LL | 1usize as i8; | ^^^^^^^^^^^^ @@ -232,7 +232,7 @@ LL | i8::try_from(1usize); | ~~~~~~~~~~~~~~~~~~~~ error: casting `usize` to `i16` may truncate the value - --> tests/ui/cast.rs:91:5 + --> tests/ui/cast.rs:90:5 | LL | 1usize as i16; | ^^^^^^^^^^^^^ @@ -244,7 +244,7 @@ LL | i16::try_from(1usize); | ~~~~~~~~~~~~~~~~~~~~~ error: casting `usize` to `i16` may wrap around the value on targets with 16-bit wide pointers - --> tests/ui/cast.rs:91:5 + --> tests/ui/cast.rs:90:5 | LL | 1usize as i16; | ^^^^^^^^^^^^^ @@ -253,7 +253,7 @@ LL | 1usize as i16; = note: for more information see https://doc.rust-lang.org/reference/types/numeric.html#machine-dependent-integer-types error: casting `usize` to `i32` may truncate the value on targets with 64-bit wide pointers - --> tests/ui/cast.rs:96:5 + --> tests/ui/cast.rs:95:5 | LL | 1usize as i32; | ^^^^^^^^^^^^^ @@ -265,19 +265,19 @@ LL | i32::try_from(1usize); | ~~~~~~~~~~~~~~~~~~~~~ error: casting `usize` to `i32` may wrap around the value on targets with 32-bit wide pointers - --> tests/ui/cast.rs:96:5 + --> tests/ui/cast.rs:95:5 | LL | 1usize as i32; | ^^^^^^^^^^^^^ error: casting `usize` to `i64` may wrap around the value on targets with 64-bit wide pointers - --> tests/ui/cast.rs:100:5 + --> tests/ui/cast.rs:99:5 | LL | 1usize as i64; | ^^^^^^^^^^^^^ error: casting `u16` to `isize` may wrap around the value on targets with 16-bit wide pointers - --> tests/ui/cast.rs:105:5 + --> tests/ui/cast.rs:104:5 | LL | 1u16 as isize; | ^^^^^^^^^^^^^ @@ -286,13 +286,13 @@ LL | 1u16 as isize; = note: for more information see https://doc.rust-lang.org/reference/types/numeric.html#machine-dependent-integer-types error: casting `u32` to `isize` may wrap around the value on targets with 32-bit wide pointers - --> tests/ui/cast.rs:109:5 + --> tests/ui/cast.rs:108:5 | LL | 1u32 as isize; | ^^^^^^^^^^^^^ error: casting `u64` to `isize` may truncate the value on targets with 32-bit wide pointers - --> tests/ui/cast.rs:112:5 + --> tests/ui/cast.rs:111:5 | LL | 1u64 as isize; | ^^^^^^^^^^^^^ @@ -304,55 +304,55 @@ LL | isize::try_from(1u64); | ~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `isize` may wrap around the value on targets with 64-bit wide pointers - --> tests/ui/cast.rs:112:5 + --> tests/ui/cast.rs:111:5 | LL | 1u64 as isize; | ^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:117:5 + --> tests/ui/cast.rs:116:5 | LL | -1i32 as u32; | ^^^^^^^^^^^^ error: casting `isize` to `usize` may lose the sign of the value - --> tests/ui/cast.rs:120:5 + --> tests/ui/cast.rs:119:5 | LL | -1isize as usize; | ^^^^^^^^^^^^^^^^ error: casting `i8` to `u8` may lose the sign of the value - --> tests/ui/cast.rs:131:5 + --> tests/ui/cast.rs:130:5 | LL | (i8::MIN).abs() as u8; | ^^^^^^^^^^^^^^^^^^^^^ error: casting `i64` to `u64` may lose the sign of the value - --> tests/ui/cast.rs:135:5 + --> tests/ui/cast.rs:134:5 | LL | (-1i64).abs() as u64; | ^^^^^^^^^^^^^^^^^^^^ error: casting `isize` to `usize` may lose the sign of the value - --> tests/ui/cast.rs:136:5 + --> tests/ui/cast.rs:135:5 | LL | (-1isize).abs() as usize; | ^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i64` to `u64` may lose the sign of the value - --> tests/ui/cast.rs:143:5 + --> tests/ui/cast.rs:142:5 | LL | (unsafe { (-1i64).checked_abs().unwrap_unchecked() }) as u64; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i64` to `u64` may lose the sign of the value - --> tests/ui/cast.rs:158:5 + --> tests/ui/cast.rs:157:5 | LL | (unsafe { (-1i64).checked_isqrt().unwrap_unchecked() }) as u64; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i64` to `i8` may truncate the value - --> tests/ui/cast.rs:209:5 + --> tests/ui/cast.rs:208:5 | LL | (-99999999999i64).min(1) as i8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -364,7 +364,7 @@ LL | i8::try_from((-99999999999i64).min(1)); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `u8` may truncate the value - --> tests/ui/cast.rs:223:5 + --> tests/ui/cast.rs:222:5 | LL | 999999u64.clamp(0, 256) as u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -376,7 +376,7 @@ LL | u8::try_from(999999u64.clamp(0, 256)); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `main::E2` to `u8` may truncate the value - --> tests/ui/cast.rs:246:21 + --> tests/ui/cast.rs:245:21 | LL | let _ = self as u8; | ^^^^^^^^^^ @@ -388,7 +388,7 @@ LL | let _ = u8::try_from(self); | ~~~~~~~~~~~~~~~~~~ error: casting `main::E2::B` to `u8` will truncate the value - --> tests/ui/cast.rs:248:21 + --> tests/ui/cast.rs:247:21 | LL | let _ = Self::B as u8; | ^^^^^^^^^^^^^ @@ -397,7 +397,7 @@ LL | let _ = Self::B as u8; = help: to override `-D warnings` add `#[allow(clippy::cast_enum_truncation)]` error: casting `main::E5` to `i8` may truncate the value - --> tests/ui/cast.rs:290:21 + --> tests/ui/cast.rs:289:21 | LL | let _ = self as i8; | ^^^^^^^^^^ @@ -409,13 +409,13 @@ LL | let _ = i8::try_from(self); | ~~~~~~~~~~~~~~~~~~ error: casting `main::E5::A` to `i8` will truncate the value - --> tests/ui/cast.rs:292:21 + --> tests/ui/cast.rs:291:21 | LL | let _ = Self::A as i8; | ^^^^^^^^^^^^^ error: casting `main::E6` to `i16` may truncate the value - --> tests/ui/cast.rs:309:21 + --> tests/ui/cast.rs:308:21 | LL | let _ = self as i16; | ^^^^^^^^^^^ @@ -427,7 +427,7 @@ LL | let _ = i16::try_from(self); | ~~~~~~~~~~~~~~~~~~~ error: casting `main::E7` to `usize` may truncate the value on targets with 32-bit wide pointers - --> tests/ui/cast.rs:328:21 + --> tests/ui/cast.rs:327:21 | LL | let _ = self as usize; | ^^^^^^^^^^^^^ @@ -439,7 +439,7 @@ LL | let _ = usize::try_from(self); | ~~~~~~~~~~~~~~~~~~~~~ error: casting `main::E10` to `u16` may truncate the value - --> tests/ui/cast.rs:375:21 + --> tests/ui/cast.rs:374:21 | LL | let _ = self as u16; | ^^^^^^^^^^^ @@ -451,7 +451,7 @@ LL | let _ = u16::try_from(self); | ~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `u8` may truncate the value - --> tests/ui/cast.rs:386:13 + --> tests/ui/cast.rs:385:13 | LL | let c = (q >> 16) as u8; | ^^^^^^^^^^^^^^^ @@ -463,7 +463,7 @@ LL | let c = u8::try_from(q >> 16); | ~~~~~~~~~~~~~~~~~~~~~ error: casting `u32` to `u8` may truncate the value - --> tests/ui/cast.rs:390:13 + --> tests/ui/cast.rs:389:13 | LL | let c = (q / 1000) as u8; | ^^^^^^^^^^^^^^^^ @@ -475,85 +475,85 @@ LL | let c = u8::try_from(q / 1000); | ~~~~~~~~~~~~~~~~~~~~~~ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:402:9 + --> tests/ui/cast.rs:401:9 | LL | (x * x) as u32; | ^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:407:32 + --> tests/ui/cast.rs:406:32 | LL | let _a = |x: i32| -> u32 { (x * x * x * x) as u32 }; | ^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:409:5 + --> tests/ui/cast.rs:408:5 | LL | (2_i32).checked_pow(3).unwrap() as u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:410:5 + --> tests/ui/cast.rs:409:5 | LL | (-2_i32).pow(3) as u32; | ^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:415:5 + --> tests/ui/cast.rs:414:5 | LL | (-5_i32 % 2) as u32; | ^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:417:5 + --> tests/ui/cast.rs:416:5 | LL | (-5_i32 % -2) as u32; | ^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:420:5 + --> tests/ui/cast.rs:419:5 | LL | (-2_i32 >> 1) as u32; | ^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:424:5 + --> tests/ui/cast.rs:423:5 | LL | (x * x) as u32; | ^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:425:5 + --> tests/ui/cast.rs:424:5 | LL | (x * x * x) as u32; | ^^^^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:429:5 + --> tests/ui/cast.rs:428:5 | LL | (y * y * y * y * -2) as u16; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:431:5 + --> tests/ui/cast.rs:430:5 | LL | (y * y * y / y * 2) as u16; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:432:5 + --> tests/ui/cast.rs:431:5 | LL | (y * y / y * 2) as u16; | ^^^^^^^^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:434:5 + --> tests/ui/cast.rs:433:5 | LL | (y / y * y * -2) as u16; | ^^^^^^^^^^^^^^^^^^^^^^^ error: equal expressions as operands to `/` - --> tests/ui/cast.rs:434:6 + --> tests/ui/cast.rs:433:6 | LL | (y / y * y * -2) as u16; | ^^^^^ @@ -561,97 +561,97 @@ LL | (y / y * y * -2) as u16; = note: `#[deny(clippy::eq_op)]` on by default error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:437:5 + --> tests/ui/cast.rs:436:5 | LL | (y + y + y + -2) as u16; | ^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:439:5 + --> tests/ui/cast.rs:438:5 | LL | (y + y + y + 2) as u16; | ^^^^^^^^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:443:5 + --> tests/ui/cast.rs:442:5 | LL | (z + -2) as u16; | ^^^^^^^^^^^^^^^ error: casting `i16` to `u16` may lose the sign of the value - --> tests/ui/cast.rs:445:5 + --> tests/ui/cast.rs:444:5 | LL | (z + z + 2) as u16; | ^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:448:9 + --> tests/ui/cast.rs:447:9 | LL | (a * a * b * b * c * c) as u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:449:9 + --> tests/ui/cast.rs:448:9 | LL | (a * b * c) as u32; | ^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:451:9 + --> tests/ui/cast.rs:450:9 | LL | (a * -b * c) as u32; | ^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:453:9 + --> tests/ui/cast.rs:452:9 | LL | (a * b * c * c) as u32; | ^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:454:9 + --> tests/ui/cast.rs:453:9 | LL | (a * -2) as u32; | ^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:456:9 + --> tests/ui/cast.rs:455:9 | LL | (a * b * c * -2) as u32; | ^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:458:9 + --> tests/ui/cast.rs:457:9 | LL | (a / b) as u32; | ^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:459:9 + --> tests/ui/cast.rs:458:9 | LL | (a / b * c) as u32; | ^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:461:9 + --> tests/ui/cast.rs:460:9 | LL | (a / b + b * c) as u32; | ^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:463:9 + --> tests/ui/cast.rs:462:9 | LL | a.saturating_pow(3) as u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:465:9 + --> tests/ui/cast.rs:464:9 | LL | (a.abs() * b.pow(2) / c.abs()) as u32 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `i32` to `u32` may lose the sign of the value - --> tests/ui/cast.rs:473:21 + --> tests/ui/cast.rs:472:21 | LL | let _ = i32::MIN as u32; // cast_sign_loss | ^^^^^^^^^^^^^^^ @@ -662,7 +662,7 @@ LL | m!(); = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) error: casting `u32` to `u8` may truncate the value - --> tests/ui/cast.rs:474:21 + --> tests/ui/cast.rs:473:21 | LL | let _ = u32::MAX as u8; // cast_possible_truncation | ^^^^^^^^^^^^^^ @@ -678,7 +678,7 @@ LL | let _ = u8::try_from(u32::MAX); // cast_possible_truncation | ~~~~~~~~~~~~~~~~~~~~~~ error: casting `f64` to `f32` may truncate the value - --> tests/ui/cast.rs:475:21 + --> tests/ui/cast.rs:474:21 | LL | let _ = std::f64::consts::PI as f32; // cast_possible_truncation | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -690,7 +690,7 @@ LL | m!(); = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) error: casting `i64` to `usize` may truncate the value on targets with 32-bit wide pointers - --> tests/ui/cast.rs:484:5 + --> tests/ui/cast.rs:483:5 | LL | bar.unwrap().unwrap() as usize | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -702,13 +702,13 @@ LL | usize::try_from(bar.unwrap().unwrap()) | error: casting `i64` to `usize` may lose the sign of the value - --> tests/ui/cast.rs:484:5 + --> tests/ui/cast.rs:483:5 | LL | bar.unwrap().unwrap() as usize | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `u64` to `u8` may truncate the value - --> tests/ui/cast.rs:499:5 + --> tests/ui/cast.rs:498:5 | LL | (256 & 999999u64) as u8; | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -720,7 +720,7 @@ LL | u8::try_from(256 & 999999u64); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: casting `u64` to `u8` may truncate the value - --> tests/ui/cast.rs:501:5 + --> tests/ui/cast.rs:500:5 | LL | (255 % 999999u64) as u8; | ^^^^^^^^^^^^^^^^^^^^^^^ From 57eacbba4017142aefddbe6aac246942fc195891 Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Wed, 9 Oct 2024 10:19:34 -0700 Subject: [PATCH 009/366] Expand `ptr::fn_addr_eq()` documentation. * Describe more clearly what is (not) guaranteed, and de-emphasize the implementation details. * Explain what you *can* reliably use it for. --- library/core/src/ptr/mod.rs | 38 +++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 67f1b0cd16de..a207f7e5b9aa 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -2164,13 +2164,36 @@ pub fn addr_eq(p: *const T, q: *const U) -> bool { /// Compares the *addresses* of the two function pointers for equality. /// -/// Function pointers comparisons can have surprising results since -/// they are never guaranteed to be unique and could vary between different -/// code generation units. Furthermore, different functions could have the -/// same address after being merged together. +/// This is the same as `f == g`, but using this function makes clear that the potentially +/// surprising semantics of function pointer comparison are involved. +/// There are very few guarantees about how functions are compiled and they have no intrinsic +/// “identity”; in particular, this comparison: +/// +/// * May return `true` unexpectedly, in cases where functions are equivalent. +/// For example, the following program is likely (but not guaranteed) to print `(true, true)` +/// when compiled with optimization: +/// +/// ``` +/// # #![feature(ptr_fn_addr_eq)] +/// let f: fn(i32) -> i32 = |x| x; +/// let g: fn(i32) -> i32 = |x| x + 0; // different closure, different body +/// let h: fn(u32) -> u32 = |x| x + 0; // different signature too +/// dbg!(std::ptr::fn_addr_eq(f, g), std::ptr::fn_addr_eq(f, h)); +/// ``` +/// +/// * May return `false` in any case. +/// This is particularly likely with generic functions but may happen with any function. +/// (From an implementation perspective, this is possible because functions may sometimes be +/// processed more than once by the compiler, resulting in duplicate machine code.) +/// +/// Despite these false positives and false negatives, this comparison can still be useful. +/// Specifically, if +/// +/// * `T` is the same type as `U`, `T` is a [subtype] of `U`, or `U` is a [subtype] of `T`, and +/// * `ptr::fn_addr_eq(f, g)` returns true, +/// +/// then calling `f` and calling `g` will be equivalent. /// -/// This is the same as `f == g` but using this function makes clear -/// that you are aware of these potentially surprising semantics. /// /// # Examples /// @@ -2182,6 +2205,9 @@ pub fn addr_eq(p: *const T, q: *const U) -> bool { /// fn b() { println!("b"); } /// assert!(!ptr::fn_addr_eq(a as fn(), b as fn())); /// ``` +/// +/// [subtype]: https://doc.rust-lang.org/reference/subtyping.html + #[unstable(feature = "ptr_fn_addr_eq", issue = "129322")] #[inline(always)] #[must_use = "function pointer comparison produces a value"] From 8e2ac498f4e8240c21f1e4ed9ed8c2370a5913f7 Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Wed, 9 Oct 2024 12:42:01 -0700 Subject: [PATCH 010/366] Apply suggestions from code review Co-authored-by: Urgau <3616612+Urgau@users.noreply.github.com> --- library/core/src/ptr/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index a207f7e5b9aa..5ee2419591dc 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -2166,10 +2166,12 @@ pub fn addr_eq(p: *const T, q: *const U) -> bool { /// /// This is the same as `f == g`, but using this function makes clear that the potentially /// surprising semantics of function pointer comparison are involved. -/// There are very few guarantees about how functions are compiled and they have no intrinsic +/// +/// There are **very few guarantees** about how functions are compiled and they have no intrinsic /// “identity”; in particular, this comparison: /// /// * May return `true` unexpectedly, in cases where functions are equivalent. +/// /// For example, the following program is likely (but not guaranteed) to print `(true, true)` /// when compiled with optimization: /// @@ -2182,6 +2184,7 @@ pub fn addr_eq(p: *const T, q: *const U) -> bool { /// ``` /// /// * May return `false` in any case. +/// /// This is particularly likely with generic functions but may happen with any function. /// (From an implementation perspective, this is possible because functions may sometimes be /// processed more than once by the compiler, resulting in duplicate machine code.) @@ -2207,7 +2210,6 @@ pub fn addr_eq(p: *const T, q: *const U) -> bool { /// ``` /// /// [subtype]: https://doc.rust-lang.org/reference/subtyping.html - #[unstable(feature = "ptr_fn_addr_eq", issue = "129322")] #[inline(always)] #[must_use = "function pointer comparison produces a value"] From 5280f152b0dad9faf33478a06c6a1cdf97b71ae4 Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Wed, 9 Oct 2024 12:53:03 -0700 Subject: [PATCH 011/366] Add "not guaranteed to be equal" Co-authored-by: Urgau <3616612+Urgau@users.noreply.github.com> --- library/core/src/ptr/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 5ee2419591dc..dfe28aa7756e 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -2180,7 +2180,7 @@ pub fn addr_eq(p: *const T, q: *const U) -> bool { /// let f: fn(i32) -> i32 = |x| x; /// let g: fn(i32) -> i32 = |x| x + 0; // different closure, different body /// let h: fn(u32) -> u32 = |x| x + 0; // different signature too -/// dbg!(std::ptr::fn_addr_eq(f, g), std::ptr::fn_addr_eq(f, h)); +/// dbg!(std::ptr::fn_addr_eq(f, g), std::ptr::fn_addr_eq(f, h)); // not guaranteed to be equal /// ``` /// /// * May return `false` in any case. From 5e8820caaa91f3d7740303e9e7047fbfb82281ce Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 11 Oct 2024 10:59:09 -0400 Subject: [PATCH 012/366] Add a note for ? on future in sync function --- .../src/error_reporting/traits/suggestions.rs | 102 ++++++++++-------- tests/ui/async-await/try-in-sync.rs | 9 ++ tests/ui/async-await/try-in-sync.stderr | 18 ++++ 3 files changed, 84 insertions(+), 45 deletions(-) create mode 100644 tests/ui/async-await/try-in-sync.rs create mode 100644 tests/ui/async-await/try-in-sync.stderr diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 87834c329e19..8dcdee736ff3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -3594,52 +3594,64 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, span: Span, ) { - if let Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) = - self.tcx.coroutine_kind(obligation.cause.body_id) + let future_trait = self.tcx.require_lang_item(LangItem::Future, None); + + let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); + let impls_future = self.type_implements_trait( + future_trait, + [self.tcx.instantiate_bound_regions_with_erased(self_ty)], + obligation.param_env, + ); + if !impls_future.must_apply_modulo_regions() { + return; + } + + let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0]; + // `::Output` + let projection_ty = trait_pred.map_bound(|trait_pred| { + Ty::new_projection( + self.tcx, + item_def_id, + // Future::Output has no args + [trait_pred.self_ty()], + ) + }); + let InferOk { value: projection_ty, .. } = + self.at(&obligation.cause, obligation.param_env).normalize(projection_ty); + + debug!( + normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty) + ); + let try_obligation = self.mk_trait_obligation_with_new_self_ty( + obligation.param_env, + trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())), + ); + debug!(try_trait_obligation = ?try_obligation); + if self.predicate_may_hold(&try_obligation) + && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) + && snippet.ends_with('?') { - let future_trait = self.tcx.require_lang_item(LangItem::Future, None); - - let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); - let impls_future = self.type_implements_trait( - future_trait, - [self.tcx.instantiate_bound_regions_with_erased(self_ty)], - obligation.param_env, - ); - if !impls_future.must_apply_modulo_regions() { - return; - } - - let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0]; - // `::Output` - let projection_ty = trait_pred.map_bound(|trait_pred| { - Ty::new_projection( - self.tcx, - item_def_id, - // Future::Output has no args - [trait_pred.self_ty()], - ) - }); - let InferOk { value: projection_ty, .. } = - self.at(&obligation.cause, obligation.param_env).normalize(projection_ty); - - debug!( - normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty) - ); - let try_obligation = self.mk_trait_obligation_with_new_self_ty( - obligation.param_env, - trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())), - ); - debug!(try_trait_obligation = ?try_obligation); - if self.predicate_may_hold(&try_obligation) - && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) - && snippet.ends_with('?') - { - err.span_suggestion_verbose( - span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(), - "consider `await`ing on the `Future`", - ".await", - Applicability::MaybeIncorrect, - ); + match self.tcx.coroutine_kind(obligation.cause.body_id) { + Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => { + err.span_suggestion_verbose( + span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(), + "consider `await`ing on the `Future`", + ".await", + Applicability::MaybeIncorrect, + ); + } + _ => { + let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into(); + span.push_span_label( + self.tcx.def_span(obligation.cause.body_id), + "this is not `async`", + ); + err.span_note( + span, + "this implements `Future` and its output type supports \ + `?`, but the future cannot be awaited in a synchronous function", + ); + } } } } diff --git a/tests/ui/async-await/try-in-sync.rs b/tests/ui/async-await/try-in-sync.rs new file mode 100644 index 000000000000..81d72c3fb9a2 --- /dev/null +++ b/tests/ui/async-await/try-in-sync.rs @@ -0,0 +1,9 @@ +//@ edition: 2021 + +async fn foo() -> Result<(), ()> { todo!() } + +fn main() -> Result<(), ()> { + foo()?; + //~^ ERROR the `?` operator can only be applied to values that implement `Try` + Ok(()) +} diff --git a/tests/ui/async-await/try-in-sync.stderr b/tests/ui/async-await/try-in-sync.stderr new file mode 100644 index 000000000000..bc7a6bd01512 --- /dev/null +++ b/tests/ui/async-await/try-in-sync.stderr @@ -0,0 +1,18 @@ +error[E0277]: the `?` operator can only be applied to values that implement `Try` + --> $DIR/try-in-sync.rs:6:5 + | +LL | foo()?; + | ^^^^^^ the `?` operator cannot be applied to type `impl Future>` + | + = help: the trait `Try` is not implemented for `impl Future>` +note: this implements `Future` and its output type supports `?`, but the future cannot be awaited in a synchronous function + --> $DIR/try-in-sync.rs:6:10 + | +LL | fn main() -> Result<(), ()> { + | --------------------------- this is not `async` +LL | foo()?; + | ^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. From c8b71ef3dd83f1d6b99d128ff2fc3b99c9ce28ab Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 12 Oct 2024 06:11:11 -0400 Subject: [PATCH 013/366] Also note for fields --- compiler/rustc_hir_typeck/src/expr.rs | 28 +++++++++++++++++------ tests/ui/async-await/field-in-sync.rs | 13 +++++++++++ tests/ui/async-await/field-in-sync.stderr | 17 ++++++++++++++ tests/ui/async-await/issue-61076.stderr | 4 ++-- 4 files changed, 53 insertions(+), 9 deletions(-) create mode 100644 tests/ui/async-await/field-in-sync.rs create mode 100644 tests/ui/async-await/field-in-sync.stderr diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index b310398a0f1b..bd35a3a8e889 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -10,7 +10,8 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::unord::UnordMap; use rustc_errors::codes::*; use rustc_errors::{ - Applicability, Diag, ErrorGuaranteed, StashKey, Subdiagnostic, pluralize, struct_span_code_err, + Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, pluralize, + struct_span_code_err, }; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; @@ -2757,12 +2758,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { field_ident.span, "field not available in `impl Future`, but it is available in its `Output`", ); - err.span_suggestion_verbose( - base.span.shrink_to_hi(), - "consider `await`ing on the `Future` and access the field of its `Output`", - ".await", - Applicability::MaybeIncorrect, - ); + match self.tcx.coroutine_kind(self.body_id) { + Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => { + err.span_suggestion_verbose( + base.span.shrink_to_hi(), + "consider `await`ing on the `Future` to access the field", + ".await", + Applicability::MaybeIncorrect, + ); + } + _ => { + let mut span: MultiSpan = base.span.into(); + span.push_span_label(self.tcx.def_span(self.body_id), "this is not `async`"); + err.span_note( + span, + "this implements `Future` and its output type has the field, \ + but the future cannot be awaited in a synchronous function", + ); + } + } } fn ban_nonexisting_field( diff --git a/tests/ui/async-await/field-in-sync.rs b/tests/ui/async-await/field-in-sync.rs new file mode 100644 index 000000000000..586980c6e2be --- /dev/null +++ b/tests/ui/async-await/field-in-sync.rs @@ -0,0 +1,13 @@ +//@ edition: 2021 + +struct S { + field: (), +} + +async fn foo() -> S { todo!() } + +fn main() -> Result<(), ()> { + foo().field; + //~^ ERROR no field `field` on type `impl Future` + Ok(()) +} diff --git a/tests/ui/async-await/field-in-sync.stderr b/tests/ui/async-await/field-in-sync.stderr new file mode 100644 index 000000000000..7be30339c275 --- /dev/null +++ b/tests/ui/async-await/field-in-sync.stderr @@ -0,0 +1,17 @@ +error[E0609]: no field `field` on type `impl Future` + --> $DIR/field-in-sync.rs:10:11 + | +LL | foo().field; + | ^^^^^ field not available in `impl Future`, but it is available in its `Output` + | +note: this implements `Future` and its output type has the field, but the future cannot be awaited in a synchronous function + --> $DIR/field-in-sync.rs:10:5 + | +LL | fn main() -> Result<(), ()> { + | --------------------------- this is not `async` +LL | foo().field; + | ^^^^^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0609`. diff --git a/tests/ui/async-await/issue-61076.stderr b/tests/ui/async-await/issue-61076.stderr index 44de282988ba..b8478c8d1388 100644 --- a/tests/ui/async-await/issue-61076.stderr +++ b/tests/ui/async-await/issue-61076.stderr @@ -28,7 +28,7 @@ error[E0609]: no field `0` on type `impl Future` LL | let _: i32 = tuple().0; | ^ field not available in `impl Future`, but it is available in its `Output` | -help: consider `await`ing on the `Future` and access the field of its `Output` +help: consider `await`ing on the `Future` to access the field | LL | let _: i32 = tuple().await.0; | ++++++ @@ -39,7 +39,7 @@ error[E0609]: no field `a` on type `impl Future` LL | let _: i32 = struct_().a; | ^ field not available in `impl Future`, but it is available in its `Output` | -help: consider `await`ing on the `Future` and access the field of its `Output` +help: consider `await`ing on the `Future` to access the field | LL | let _: i32 = struct_().await.a; | ++++++ From 90b181c8e137d10991733064fd5cefef98658ffa Mon Sep 17 00:00:00 2001 From: Giga Bowser <45986823+Giga-Bowser@users.noreply.github.com> Date: Sun, 13 Oct 2024 10:53:38 -0400 Subject: [PATCH 014/366] Add wrap/unwrap return type in Option --- .../src/handlers/unwrap_option_return_type.rs | 1143 ++++++++++++++++ .../handlers/wrap_return_type_in_option.rs | 1173 +++++++++++++++++ .../crates/ide-assists/src/lib.rs | 4 + .../crates/ide-assists/src/tests/generated.rs | 28 + 4 files changed, 2348 insertions(+) create mode 100644 src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs create mode 100644 src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs new file mode 100644 index 000000000000..8dc40842406b --- /dev/null +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs @@ -0,0 +1,1143 @@ +use ide_db::{ + famous_defs::FamousDefs, + syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, +}; +use itertools::Itertools; +use syntax::{ + ast::{self, Expr, HasGenericArgs}, + match_ast, AstNode, NodeOrToken, SyntaxKind, TextRange, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: unwrap_option_return_type +// +// Unwrap the function's return type. +// +// ``` +// # //- minicore: option +// fn foo() -> Option$0 { Some(42i32) } +// ``` +// -> +// ``` +// fn foo() -> i32 { 42i32 } +// ``` +pub(crate) fn unwrap_option_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + let ret_type = ctx.find_node_at_offset::()?; + let parent = ret_type.syntax().parent()?; + let body = match_ast! { + match parent { + ast::Fn(func) => func.body()?, + ast::ClosureExpr(closure) => match closure.body()? { + Expr::BlockExpr(block) => block, + // closures require a block when a return type is specified + _ => return None, + }, + _ => return None, + } + }; + + let type_ref = &ret_type.ty()?; + let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else { + return None; + }; + let option_enum = + FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_option_Option()?; + if ret_enum != option_enum { + return None; + } + + let ok_type = unwrap_option_type(type_ref)?; + + acc.add( + AssistId("unwrap_option_return_type", AssistKind::RefactorRewrite), + "Unwrap Option return type", + type_ref.syntax().text_range(), + |builder| { + let body = ast::Expr::BlockExpr(body); + + let mut exprs_to_unwrap = Vec::new(); + let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); + walk_expr(&body, &mut |expr| { + if let Expr::ReturnExpr(ret_expr) = expr { + if let Some(ret_expr_arg) = &ret_expr.expr() { + for_each_tail_expr(ret_expr_arg, tail_cb); + } + } + }); + for_each_tail_expr(&body, tail_cb); + + let is_unit_type = is_unit_type(&ok_type); + if is_unit_type { + let mut text_range = ret_type.syntax().text_range(); + + if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() { + if token.kind() == SyntaxKind::WHITESPACE { + text_range = TextRange::new(text_range.start(), token.text_range().end()); + } + } + + builder.delete(text_range); + } else { + builder.replace(type_ref.syntax().text_range(), ok_type.syntax().text()); + } + + for ret_expr_arg in exprs_to_unwrap { + let ret_expr_str = ret_expr_arg.to_string(); + if ret_expr_str.starts_with("Some(") { + let arg_list = ret_expr_arg.syntax().children().find_map(ast::ArgList::cast); + if let Some(arg_list) = arg_list { + if is_unit_type { + match ret_expr_arg.syntax().prev_sibling_or_token() { + // Useful to delete the entire line without leaving trailing whitespaces + Some(whitespace) => { + let new_range = TextRange::new( + whitespace.text_range().start(), + ret_expr_arg.syntax().text_range().end(), + ); + builder.delete(new_range); + } + None => { + builder.delete(ret_expr_arg.syntax().text_range()); + } + } + } else { + builder.replace( + ret_expr_arg.syntax().text_range(), + arg_list.args().join(", "), + ); + } + } + } else if ret_expr_str == "None" { + builder.replace(ret_expr_arg.syntax().text_range(), "()"); + } + } + }, + ) +} + +fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { + match e { + Expr::BreakExpr(break_expr) => { + if let Some(break_expr_arg) = break_expr.expr() { + for_each_tail_expr(&break_expr_arg, &mut |e| tail_cb_impl(acc, e)) + } + } + Expr::ReturnExpr(_) => { + // all return expressions have already been handled by the walk loop + } + e => acc.push(e.clone()), + } +} + +// Tries to extract `T` from `Option`. +fn unwrap_option_type(ty: &ast::Type) -> Option { + let ast::Type::PathType(path_ty) = ty else { + return None; + }; + let path = path_ty.path()?; + let segment = path.first_segment()?; + let generic_arg_list = segment.generic_arg_list()?; + let generic_args: Vec<_> = generic_arg_list.generic_args().collect(); + let ast::GenericArg::TypeArg(some_type) = generic_args.first()? else { + return None; + }; + some_type.ty() +} + +fn is_unit_type(ty: &ast::Type) -> bool { + let ast::Type::TupleType(tuple) = ty else { return false }; + tuple.fields().next().is_none() +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn unwrap_option_return_type_simple() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + return Some(42i32); +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_unit_type() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option<()$0> { + Some(()) +} +"#, + r#" +fn foo() { +} +"#, + ); + + // Unformatted return type + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option<()$0>{ + Some(()) +} +"#, + r#" +fn foo() { +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_none() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + if true { + Some(42) + } else { + None + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42 + } else { + () + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_ending_with_parent() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + if true { + Some(42) + } else { + foo() + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42 + } else { + foo() + } +} +"#, + ); + } + + #[test] + fn unwrap_return_type_break_split_tail() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + loop { + break if true { + Some(1) + } else { + Some(0) + }; + } +} +"#, + r#" +fn foo() -> i32 { + loop { + break if true { + 1 + } else { + 0 + }; + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> Option { + let test = "test"; + return Some(42i32); + }; +} +"#, + r#" +fn foo() { + || -> i32 { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_bad_cursor() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> i32 { + let test = "test";$0 + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_bad_cursor_closure() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> i32 { + let test = "test";$0 + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_closure_non_block() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { || -> i$032 3; } +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_already_not_option_std() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> i32$0 { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_already_not_option_closure() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> i32$0 { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() ->$0 Option { + let test = "test"; + Some(42i32) +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + 42i32 +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || ->$0 Option { + let test = "test"; + Some(42i32) + }; +} +"#, + r#" +fn foo() { + || -> i32 { + let test = "test"; + 42i32 + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_only() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { Some(42i32) } +"#, + r#" +fn foo() -> i32 { 42i32 } +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option$0 { + if true { + Some(42i32) + } else { + Some(24i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42i32 + } else { + 24i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_without_block_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> Option$0 { + if true { + Some(42i32) + } else { + Some(24i32) + } + }; +} +"#, + r#" +fn foo() { + || -> i32 { + if true { + 42i32 + } else { + 24i32 + } + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_nested_if() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option$0 { + if true { + if false { + Some(1) + } else { + Some(2) + } + } else { + Some(24i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + if false { + 1 + } else { + 2 + } + } else { + 24i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_await() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +async fn foo() -> Option { + if true { + if false { + Some(1.await) + } else { + Some(2.await) + } + } else { + Some(24i32.await) + } +} +"#, + r#" +async fn foo() -> i32 { + if true { + if false { + 1.await + } else { + 2.await + } + } else { + 24i32.await + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_array() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option<[i32; 3]$0> { Some([1, 2, 3]) } +"#, + r#" +fn foo() -> [i32; 3] { [1, 2, 3] } +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_cast() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -$0> Option { + if true { + if false { + Some(1 as i32) + } else { + Some(2 as i32) + } + } else { + Some(24 as i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + if false { + 1 as i32 + } else { + 2 as i32 + } + } else { + 24 as i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_match() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => Some(42i32), + _ => Some(24i32), + } +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + match my_var { + 5 => 42i32, + _ => 24i32, + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_loop_with_tail() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + loop { + println!("test"); + 5 + } + Some(my_var) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + loop { + println!("test"); + 5 + } + my_var +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_loop_in_let_stmt() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = let x = loop { + break 1; + }; + Some(my_var) +} +"#, + r#" +fn foo() -> i32 { + let my_var = let x = loop { + break 1; + }; + my_var +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_match_return_expr() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option$0 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return Some(24i32), + }; + Some(res) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return 24i32, + }; + res +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return Some(24i32); + }; + Some(res) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return 24i32; + }; + res +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_match_deeper() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => { + if true { + Some(42i32) + } else { + Some(25i32) + } + }, + _ => { + let test = "test"; + if test == "test" { + return Some(bar()); + } + Some(53i32) + }, + } +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + match my_var { + 5 => { + if true { + 42i32 + } else { + 25i32 + } + }, + _ => { + let test = "test"; + if test == "test" { + return bar(); + } + 53i32 + }, + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_early_return() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + Some(53i32) +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + if test == "test" { + return 24i32; + } + 53i32 +} +"#, + ); + } + + #[test] + fn wrap_return_in_tail_position() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(num: i32) -> $0Option { + return Some(num) +} +"#, + r#" +fn foo(num: i32) -> i32 { + return num +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + let t = None; + + Some(t.unwrap_or_else(|| the_field)) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return 99; + } else { + return 0; + } + } + let t = None; + + t.unwrap_or_else(|| the_field) +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_weird_forms() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + let mut i = 0; + loop { + if i == 1 { + break Some(55); + } + i += 1; + } +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + if i == 1 { + break 55; + } + i += 1; + } +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return Some(55u32); + } + i += 3; + } + match i { + 5 => return Some(99), + _ => return Some(0), + }; + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return 55u32; + } + i += 3; + } + match i { + 5 => return 99, + _ => return 0, + }; + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return Some(99), + _ => return Some(0), + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return 99, + _ => return 0, + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99) + } else { + return Some(0) + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99 + } else { + return 0 + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_nested_type() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option, result +fn foo() -> Option> { + Some(Ok(42)) +} +"#, + r#" +fn foo() -> Result { + Ok(42) +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option, result +fn foo() -> Option, ()>> { + Some(Err()) +} +"#, + r#" +fn foo() -> Result, ()> { + Err() +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option, result, iterators +fn foo() -> Option$0> { + Some(Some(42).into_iter()) +} +"#, + r#" +fn foo() -> impl Iterator { + Some(42).into_iter() +} +"#, + ); + } +} diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs new file mode 100644 index 000000000000..90cfc2ef17c7 --- /dev/null +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs @@ -0,0 +1,1173 @@ +use std::iter; + +use hir::HasSource; +use ide_db::{ + famous_defs::FamousDefs, + syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, +}; +use itertools::Itertools; +use syntax::{ + ast::{self, make, Expr, HasGenericParams}, + match_ast, ted, AstNode, ToSmolStr, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: wrap_return_type_in_option +// +// Wrap the function's return type into Option. +// +// ``` +// # //- minicore: option +// fn foo() -> i32$0 { 42i32 } +// ``` +// -> +// ``` +// fn foo() -> Option { Some(42i32) } +// ``` +pub(crate) fn wrap_return_type_in_option(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + let ret_type = ctx.find_node_at_offset::()?; + let parent = ret_type.syntax().parent()?; + let body = match_ast! { + match parent { + ast::Fn(func) => func.body()?, + ast::ClosureExpr(closure) => match closure.body()? { + Expr::BlockExpr(block) => block, + // closures require a block when a return type is specified + _ => return None, + }, + _ => return None, + } + }; + + let type_ref = &ret_type.ty()?; + let core_option = + FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_option_Option()?; + + let ty = ctx.sema.resolve_type(type_ref)?.as_adt(); + if matches!(ty, Some(hir::Adt::Enum(ret_type)) if ret_type == core_option) { + // The return type is already wrapped in an Option + cov_mark::hit!(wrap_return_type_in_option_simple_return_type_already_option); + return None; + } + + acc.add( + AssistId("wrap_return_type_in_option", AssistKind::RefactorRewrite), + "Wrap return type in Option", + type_ref.syntax().text_range(), + |edit| { + let new_option_ty = option_type(ctx, &core_option, type_ref).clone_for_update(); + let body = edit.make_mut(ast::Expr::BlockExpr(body)); + + let mut exprs_to_wrap = Vec::new(); + let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); + walk_expr(&body, &mut |expr| { + if let Expr::ReturnExpr(ret_expr) = expr { + if let Some(ret_expr_arg) = &ret_expr.expr() { + for_each_tail_expr(ret_expr_arg, tail_cb); + } + } + }); + for_each_tail_expr(&body, tail_cb); + + for ret_expr_arg in exprs_to_wrap { + let some_wrapped = make::expr_call( + make::expr_path(make::ext::ident_path("Some")), + make::arg_list(iter::once(ret_expr_arg.clone())), + ) + .clone_for_update(); + ted::replace(ret_expr_arg.syntax(), some_wrapped.syntax()); + } + + let old_option_ty = edit.make_mut(type_ref.clone()); + ted::replace(old_option_ty.syntax(), new_option_ty.syntax()); + }, + ) +} + +fn option_type( + ctx: &AssistContext<'_>, + core_option: &hir::Enum, + ret_type: &ast::Type, +) -> ast::Type { + // Try to find an Option type alias in the current scope (shadowing the default). + let option_path = hir::ModPath::from_segments( + hir::PathKind::Plain, + iter::once(hir::Name::new_symbol_root(hir::sym::Option.clone())), + ); + let alias = ctx.sema.resolve_mod_path(ret_type.syntax(), &option_path).and_then(|def| { + def.filter_map(|def| match def.as_module_def()? { + hir::ModuleDef::TypeAlias(alias) => { + let enum_ty = alias.ty(ctx.db()).as_adt()?.as_enum()?; + (&enum_ty == core_option).then_some(alias) + } + _ => None, + }) + .find_map(|alias| { + let mut inserted_ret_type = false; + let generic_params = alias + .source(ctx.db())? + .value + .generic_param_list()? + .generic_params() + .map(|param| match param { + // Replace the very first type parameter with the functions return type. + ast::GenericParam::TypeParam(_) if !inserted_ret_type => { + inserted_ret_type = true; + ret_type.to_smolstr() + } + ast::GenericParam::LifetimeParam(_) => make::lifetime("'_").to_smolstr(), + _ => make::ty_placeholder().to_smolstr(), + }) + .join(", "); + + let name = alias.name(ctx.db()); + let name = name.as_str(); + Some(make::ty(&format!("{name}<{generic_params}>"))) + }) + }); + // If there is no applicable alias in scope use the default Option type. + alias.unwrap_or_else(|| make::ext::ty_option(ret_type.clone())) +} + +fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { + match e { + Expr::BreakExpr(break_expr) => { + if let Some(break_expr_arg) = break_expr.expr() { + for_each_tail_expr(&break_expr_arg, &mut |e| tail_cb_impl(acc, e)) + } + } + Expr::ReturnExpr(_) => { + // all return expressions have already been handled by the walk loop + } + e => acc.push(e.clone()), + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn wrap_return_type_in_option_simple() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i3$02 { + let test = "test"; + return 42i32; +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_break_split_tail() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i3$02 { + loop { + break if true { + 1 + } else { + 0 + }; + } +} +"#, + r#" +fn foo() -> Option { + loop { + break if true { + Some(1) + } else { + Some(0) + }; + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> i32$0 { + let test = "test"; + return 42i32; + }; +} +"#, + r#" +fn foo() { + || -> Option { + let test = "test"; + return Some(42i32); + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_bad_cursor() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32 { + let test = "test";$0 + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_bad_cursor_closure() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> i32 { + let test = "test";$0 + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_closure_non_block() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { || -> i$032 3; } +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_already_option_std() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> core::option::Option { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_already_option() { + cov_mark::check!(wrap_return_type_in_option_simple_return_type_already_option); + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_already_option_closure() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> Option { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_cursor() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> $0i32 { + let test = "test"; + return 42i32; +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() ->$0 i32 { + let test = "test"; + 42i32 +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + Some(42i32) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || ->$0 i32 { + let test = "test"; + 42i32 + }; +} +"#, + r#" +fn foo() { + || -> Option { + let test = "test"; + Some(42i32) + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_only() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { 42i32 } +"#, + r#" +fn foo() -> Option { Some(42i32) } +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + if true { + 42i32 + } else { + 24i32 + } +} +"#, + r#" +fn foo() -> Option { + if true { + Some(42i32) + } else { + Some(24i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_without_block_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> i32$0 { + if true { + 42i32 + } else { + 24i32 + } + }; +} +"#, + r#" +fn foo() { + || -> Option { + if true { + Some(42i32) + } else { + Some(24i32) + } + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_nested_if() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + if true { + if false { + 1 + } else { + 2 + } + } else { + 24i32 + } +} +"#, + r#" +fn foo() -> Option { + if true { + if false { + Some(1) + } else { + Some(2) + } + } else { + Some(24i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_await() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +async fn foo() -> i$032 { + if true { + if false { + 1.await + } else { + 2.await + } + } else { + 24i32.await + } +} +"#, + r#" +async fn foo() -> Option { + if true { + if false { + Some(1.await) + } else { + Some(2.await) + } + } else { + Some(24i32.await) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_array() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> [i32;$0 3] { [1, 2, 3] } +"#, + r#" +fn foo() -> Option<[i32; 3]> { Some([1, 2, 3]) } +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_cast() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -$0> i32 { + if true { + if false { + 1 as i32 + } else { + 2 as i32 + } + } else { + 24 as i32 + } +} +"#, + r#" +fn foo() -> Option { + if true { + if false { + Some(1 as i32) + } else { + Some(2 as i32) + } + } else { + Some(24 as i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_match() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + match my_var { + 5 => 42i32, + _ => 24i32, + } +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => Some(42i32), + _ => Some(24i32), + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_loop_with_tail() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + loop { + println!("test"); + 5 + } + my_var +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + loop { + println!("test"); + 5 + } + Some(my_var) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_loop_in_let_stmt() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = let x = loop { + break 1; + }; + my_var +} +"#, + r#" +fn foo() -> Option { + let my_var = let x = loop { + break 1; + }; + Some(my_var) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_match_return_expr() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return 24i32, + }; + res +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return Some(24i32), + }; + Some(res) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return 24i32; + }; + res +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return Some(24i32); + }; + Some(res) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_match_deeper() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + match my_var { + 5 => { + if true { + 42i32 + } else { + 25i32 + } + }, + _ => { + let test = "test"; + if test == "test" { + return bar(); + } + 53i32 + }, + } +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => { + if true { + Some(42i32) + } else { + Some(25i32) + } + }, + _ => { + let test = "test"; + if test == "test" { + return Some(bar()); + } + Some(53i32) + }, + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_early_return() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i$032 { + let test = "test"; + if test == "test" { + return 24i32; + } + 53i32 +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + Some(53i32) +} +"#, + ); + } + + #[test] + fn wrap_return_in_tail_position() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(num: i32) -> $0i32 { + return num +} +"#, + r#" +fn foo(num: i32) -> Option { + return Some(num) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) ->$0 u32 { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u32$0 { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return 99; + } else { + return 0; + } + } + let t = None; + + t.unwrap_or_else(|| the_field) +} +"#, + r#" +fn foo(the_field: u32) -> Option { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + let t = None; + + Some(t.unwrap_or_else(|| the_field)) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_weird_forms() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + if i == 1 { + break 55; + } + i += 1; + } +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + let mut i = 0; + loop { + if i == 1 { + break Some(55); + } + i += 1; + } +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u32$0 { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return 55u32; + } + i += 3; + } + match i { + 5 => return 99, + _ => return 0, + }; + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return Some(55u32); + } + i += 3; + } + match i { + 5 => return Some(99), + _ => return Some(0), + }; + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u3$02 { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return 99, + _ => return 0, + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return Some(99), + _ => return Some(0), + } + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u32$0 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99 + } else { + return 0 + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99) + } else { + return Some(0) + } + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> $0u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_local_option_type() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +type Option = core::option::Option; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +type Option = core::option::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +type Option2 = core::option::Option; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +type Option2 = core::option::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_imported_local_option_type() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::Option; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::*; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::*; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_local_option_type_from_function_body() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i3$02 { + type Option = core::option::Option; + 0 +} +"#, + r#" +fn foo() -> Option { + type Option = core::option::Option; + Some(0) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_local_option_type_already_using_alias() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +pub type Option = core::option::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + } +} diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs index c98655b42302..63a3fec3f41d 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs @@ -223,8 +223,10 @@ mod handlers { mod unnecessary_async; mod unqualify_method_call; mod unwrap_block; + mod unwrap_option_return_type; mod unwrap_result_return_type; mod unwrap_tuple; + mod wrap_return_type_in_option; mod wrap_return_type_in_result; mod wrap_unwrap_cfg_attr; @@ -355,9 +357,11 @@ mod handlers { unmerge_use::unmerge_use, unnecessary_async::unnecessary_async, unwrap_block::unwrap_block, + unwrap_option_return_type::unwrap_option_return_type, unwrap_result_return_type::unwrap_result_return_type, unwrap_tuple::unwrap_tuple, unqualify_method_call::unqualify_method_call, + wrap_return_type_in_option::wrap_return_type_in_option, wrap_return_type_in_result::wrap_return_type_in_result, wrap_unwrap_cfg_attr::wrap_unwrap_cfg_attr, diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/tests/generated.rs b/src/tools/rust-analyzer/crates/ide-assists/src/tests/generated.rs index 48e12a810735..933d45d75083 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/tests/generated.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/tests/generated.rs @@ -3264,6 +3264,20 @@ fn foo() { ) } +#[test] +fn doctest_unwrap_option_return_type() { + check_doc_test( + "unwrap_option_return_type", + r#####" +//- minicore: option +fn foo() -> Option$0 { Some(42i32) } +"#####, + r#####" +fn foo() -> i32 { 42i32 } +"#####, + ) +} + #[test] fn doctest_unwrap_result_return_type() { check_doc_test( @@ -3297,6 +3311,20 @@ fn main() { ) } +#[test] +fn doctest_wrap_return_type_in_option() { + check_doc_test( + "wrap_return_type_in_option", + r#####" +//- minicore: option +fn foo() -> i32$0 { 42i32 } +"#####, + r#####" +fn foo() -> Option { Some(42i32) } +"#####, + ) +} + #[test] fn doctest_wrap_return_type_in_result() { check_doc_test( From 136463158460cac8c7dbb6dcbce669fa941e33b4 Mon Sep 17 00:00:00 2001 From: Lieselotte <52315535+she3py@users.noreply.github.com> Date: Mon, 14 Oct 2024 20:24:30 +0200 Subject: [PATCH 015/366] `rt::Argument`: elide lifetimes --- library/core/src/fmt/rt.rs | 26 +++++++++---------- tests/ui/closures/issue-111932.stderr | 2 +- .../const-generics/infer/issue-77092.stderr | 2 +- tests/ui/fmt/ifmt-unimpl.stderr | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/library/core/src/fmt/rt.rs b/library/core/src/fmt/rt.rs index eee4a9e4c6c8..af6f0da88de6 100644 --- a/library/core/src/fmt/rt.rs +++ b/library/core/src/fmt/rt.rs @@ -94,11 +94,11 @@ pub struct Argument<'a> { } #[rustc_diagnostic_item = "ArgumentMethods"] -impl<'a> Argument<'a> { +impl Argument<'_> { #[inline(always)] - fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> Argument<'b> { + fn new<'a, T>(x: &'a T, f: fn(&T, &mut Formatter<'_>) -> Result) -> Argument<'a> { Argument { - // INVARIANT: this creates an `ArgumentType<'b>` from a `&'b T` and + // INVARIANT: this creates an `ArgumentType<'a>` from a `&'a T` and // a `fn(&T, ...)`, so the invariant is maintained. ty: ArgumentType::Placeholder { value: NonNull::from(x).cast(), @@ -110,43 +110,43 @@ impl<'a> Argument<'a> { } #[inline(always)] - pub fn new_display<'b, T: Display>(x: &'b T) -> Argument<'b> { + pub fn new_display(x: &T) -> Argument<'_> { Self::new(x, Display::fmt) } #[inline(always)] - pub fn new_debug<'b, T: Debug>(x: &'b T) -> Argument<'b> { + pub fn new_debug(x: &T) -> Argument<'_> { Self::new(x, Debug::fmt) } #[inline(always)] - pub fn new_debug_noop<'b, T: Debug>(x: &'b T) -> Argument<'b> { + pub fn new_debug_noop(x: &T) -> Argument<'_> { Self::new(x, |_, _| Ok(())) } #[inline(always)] - pub fn new_octal<'b, T: Octal>(x: &'b T) -> Argument<'b> { + pub fn new_octal(x: &T) -> Argument<'_> { Self::new(x, Octal::fmt) } #[inline(always)] - pub fn new_lower_hex<'b, T: LowerHex>(x: &'b T) -> Argument<'b> { + pub fn new_lower_hex(x: &T) -> Argument<'_> { Self::new(x, LowerHex::fmt) } #[inline(always)] - pub fn new_upper_hex<'b, T: UpperHex>(x: &'b T) -> Argument<'b> { + pub fn new_upper_hex(x: &T) -> Argument<'_> { Self::new(x, UpperHex::fmt) } #[inline(always)] - pub fn new_pointer<'b, T: Pointer>(x: &'b T) -> Argument<'b> { + pub fn new_pointer(x: &T) -> Argument<'_> { Self::new(x, Pointer::fmt) } #[inline(always)] - pub fn new_binary<'b, T: Binary>(x: &'b T) -> Argument<'b> { + pub fn new_binary(x: &T) -> Argument<'_> { Self::new(x, Binary::fmt) } #[inline(always)] - pub fn new_lower_exp<'b, T: LowerExp>(x: &'b T) -> Argument<'b> { + pub fn new_lower_exp(x: &T) -> Argument<'_> { Self::new(x, LowerExp::fmt) } #[inline(always)] - pub fn new_upper_exp<'b, T: UpperExp>(x: &'b T) -> Argument<'b> { + pub fn new_upper_exp(x: &T) -> Argument<'_> { Self::new(x, UpperExp::fmt) } #[inline(always)] diff --git a/tests/ui/closures/issue-111932.stderr b/tests/ui/closures/issue-111932.stderr index ff46b10d005d..93488ad2011e 100644 --- a/tests/ui/closures/issue-111932.stderr +++ b/tests/ui/closures/issue-111932.stderr @@ -17,7 +17,7 @@ LL | println!("{:?}", foo); | required by a bound introduced by this call | = help: the trait `Sized` is not implemented for `dyn Foo` -note: required by an implicit `Sized` bound in `core::fmt::rt::Argument::<'a>::new_debug` +note: required by an implicit `Sized` bound in `core::fmt::rt::Argument::<'_>::new_debug` --> $SRC_DIR/core/src/fmt/rt.rs:LL:COL = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/const-generics/infer/issue-77092.stderr b/tests/ui/const-generics/infer/issue-77092.stderr index 9a6374a2adcb..4ab80cec58d8 100644 --- a/tests/ui/const-generics/infer/issue-77092.stderr +++ b/tests/ui/const-generics/infer/issue-77092.stderr @@ -25,7 +25,7 @@ LL | println!("{:?}", take_array_from_mut(&mut arr, i)); = note: required for `[i32; _]` to implement `Debug` = note: 1 redundant requirement hidden = note: required for `&mut [i32; _]` to implement `Debug` -note: required by a bound in `core::fmt::rt::Argument::<'a>::new_debug` +note: required by a bound in `core::fmt::rt::Argument::<'_>::new_debug` --> $SRC_DIR/core/src/fmt/rt.rs:LL:COL help: consider specifying the generic arguments | diff --git a/tests/ui/fmt/ifmt-unimpl.stderr b/tests/ui/fmt/ifmt-unimpl.stderr index a22bba07c027..f83e7c877288 100644 --- a/tests/ui/fmt/ifmt-unimpl.stderr +++ b/tests/ui/fmt/ifmt-unimpl.stderr @@ -17,7 +17,7 @@ LL | format!("{:X}", "3"); i32 and 9 others = note: required for `&str` to implement `UpperHex` -note: required by a bound in `core::fmt::rt::Argument::<'a>::new_upper_hex` +note: required by a bound in `core::fmt::rt::Argument::<'_>::new_upper_hex` --> $SRC_DIR/core/src/fmt/rt.rs:LL:COL = note: this error originates in the macro `$crate::__export::format_args` which comes from the expansion of the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) From 362879d8c13f3912510c5a299dbf6fa2c2067afa Mon Sep 17 00:00:00 2001 From: ltdk Date: Mon, 14 Oct 2024 16:05:01 -0400 Subject: [PATCH 016/366] Run most core::num tests in const context too --- library/core/tests/lib.rs | 35 ++ library/core/tests/num/int_macros.rs | 586 +++++++++++++------------- library/core/tests/num/uint_macros.rs | 435 ++++++++++--------- 3 files changed, 535 insertions(+), 521 deletions(-) diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 37e7db1157c8..76ab0d157b61 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -16,11 +16,14 @@ #![feature(clone_to_uninit)] #![feature(const_align_of_val_raw)] #![feature(const_align_offset)] +#![feature(const_bigint_helper_methods)] #![feature(const_black_box)] +#![feature(const_eval_select)] #![feature(const_hash)] #![feature(const_heap)] #![feature(const_likely)] #![feature(const_nonnull_new)] +#![feature(const_num_midpoint)] #![feature(const_option_ext)] #![feature(const_pin)] #![feature(const_pointer_is_aligned)] @@ -45,6 +48,7 @@ #![feature(get_many_mut)] #![feature(hasher_prefixfree_extras)] #![feature(hashmap_internals)] +#![feature(inline_const_pat)] #![feature(int_roundings)] #![feature(ip)] #![feature(ip_from)] @@ -104,6 +108,37 @@ #![deny(fuzzy_provenance_casts)] #![deny(unsafe_op_in_unsafe_fn)] +/// Version of `assert_matches` that ignores fancy runtime printing in const context and uses structural equality. +macro_rules! assert_eq_const_safe { + ($left:expr, $right:expr$(, $($arg:tt)+)?) => { + { + fn runtime() { + assert_eq!($left, $right, $($arg)*); + } + const fn compiletime() { + assert!(matches!($left, const { $right })); + } + core::intrinsics::const_eval_select((), compiletime, runtime) + } + }; +} + +/// Creates a test for runtime and a test for constant-time. +macro_rules! test_runtime_and_compiletime { + ($( + $(#[$attr:meta])* + fn $test:ident() $block:block + )*) => { + $( + $(#[$attr])* + #[test] + fn $test() $block + $(#[$attr])* + const _: () = $block; + )* + } +} + mod alloc; mod any; mod array; diff --git a/library/core/tests/num/int_macros.rs b/library/core/tests/num/int_macros.rs index 6a26bd15a663..7d3381ee5044 100644 --- a/library/core/tests/num/int_macros.rs +++ b/library/core/tests/num/int_macros.rs @@ -17,42 +17,6 @@ macro_rules! int_module { num::test_num(10 as $T, 2 as $T); } - #[test] - fn test_rem_euclid() { - assert_eq!((-1 as $T).rem_euclid(MIN), MAX); - } - - #[test] - pub fn test_abs() { - assert_eq!((1 as $T).abs(), 1 as $T); - assert_eq!((0 as $T).abs(), 0 as $T); - assert_eq!((-1 as $T).abs(), 1 as $T); - } - - #[test] - fn test_signum() { - assert_eq!((1 as $T).signum(), 1 as $T); - assert_eq!((0 as $T).signum(), 0 as $T); - assert_eq!((-0 as $T).signum(), 0 as $T); - assert_eq!((-1 as $T).signum(), -1 as $T); - } - - #[test] - fn test_is_positive() { - assert!((1 as $T).is_positive()); - assert!(!(0 as $T).is_positive()); - assert!(!(-0 as $T).is_positive()); - assert!(!(-1 as $T).is_positive()); - } - - #[test] - fn test_is_negative() { - assert!(!(1 as $T).is_negative()); - assert!(!(0 as $T).is_negative()); - assert!(!(-0 as $T).is_negative()); - assert!((-1 as $T).is_negative()); - } - #[test] fn test_bitwise_operators() { assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(0b1010 as $T)); @@ -63,6 +27,40 @@ macro_rules! int_module { assert_eq!(-(0b11 as $T) - (1 as $T), (0b11 as $T).not()); } + test_runtime_and_compiletime! { + + fn test_rem_euclid() { + assert_eq_const_safe!((-1 as $T).rem_euclid(MIN), MAX); + } + + fn test_abs() { + assert_eq_const_safe!((1 as $T).abs(), 1 as $T); + assert_eq_const_safe!((0 as $T).abs(), 0 as $T); + assert_eq_const_safe!((-1 as $T).abs(), 1 as $T); + } + + fn test_signum() { + assert_eq_const_safe!((1 as $T).signum(), 1 as $T); + assert_eq_const_safe!((0 as $T).signum(), 0 as $T); + assert_eq_const_safe!((-0 as $T).signum(), 0 as $T); + assert_eq_const_safe!((-1 as $T).signum(), -1 as $T); + } + + fn test_is_positive() { + assert!((1 as $T).is_positive()); + assert!(!(0 as $T).is_positive()); + assert!(!(-0 as $T).is_positive()); + assert!(!(-1 as $T).is_positive()); + } + + fn test_is_negative() { + assert!(!(1 as $T).is_negative()); + assert!(!(0 as $T).is_negative()); + assert!(!(-0 as $T).is_negative()); + assert!((-1 as $T).is_negative()); + } + } + const A: $T = 0b0101100; const B: $T = 0b0100001; const C: $T = 0b1111001; @@ -70,134 +68,126 @@ macro_rules! int_module { const _0: $T = 0; const _1: $T = !0; - #[test] - fn test_count_ones() { - assert_eq!(A.count_ones(), 3); - assert_eq!(B.count_ones(), 2); - assert_eq!(C.count_ones(), 5); - } + test_runtime_and_compiletime! { + fn test_count_ones() { + assert_eq_const_safe!(A.count_ones(), 3); + assert_eq_const_safe!(B.count_ones(), 2); + assert_eq_const_safe!(C.count_ones(), 5); + } - #[test] - fn test_count_zeros() { - assert_eq!(A.count_zeros(), $T::BITS - 3); - assert_eq!(B.count_zeros(), $T::BITS - 2); - assert_eq!(C.count_zeros(), $T::BITS - 5); - } + fn test_count_zeros() { + assert_eq_const_safe!(A.count_zeros(), $T::BITS - 3); + assert_eq_const_safe!(B.count_zeros(), $T::BITS - 2); + assert_eq_const_safe!(C.count_zeros(), $T::BITS - 5); + } - #[test] - fn test_leading_trailing_ones() { - let a: $T = 0b0101_1111; - assert_eq!(a.trailing_ones(), 5); - assert_eq!((!a).leading_ones(), $T::BITS - 7); + fn test_leading_trailing_ones() { + const A: $T = 0b0101_1111; + assert_eq_const_safe!(A.trailing_ones(), 5); + assert_eq_const_safe!((!A).leading_ones(), $T::BITS - 7); - assert_eq!(a.reverse_bits().leading_ones(), 5); + assert_eq_const_safe!(A.reverse_bits().leading_ones(), 5); - assert_eq!(_1.leading_ones(), $T::BITS); - assert_eq!(_1.trailing_ones(), $T::BITS); + assert_eq_const_safe!(_1.leading_ones(), $T::BITS); + assert_eq_const_safe!(_1.trailing_ones(), $T::BITS); - assert_eq!((_1 << 1).trailing_ones(), 0); - assert_eq!(MAX.leading_ones(), 0); + assert_eq_const_safe!((_1 << 1).trailing_ones(), 0); + assert_eq_const_safe!(MAX.leading_ones(), 0); - assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1); - assert_eq!(MAX.trailing_ones(), $T::BITS - 1); + assert_eq_const_safe!((_1 << 1).leading_ones(), $T::BITS - 1); + assert_eq_const_safe!(MAX.trailing_ones(), $T::BITS - 1); - assert_eq!(_0.leading_ones(), 0); - assert_eq!(_0.trailing_ones(), 0); + assert_eq_const_safe!(_0.leading_ones(), 0); + assert_eq_const_safe!(_0.trailing_ones(), 0); - let x: $T = 0b0010_1100; - assert_eq!(x.leading_ones(), 0); - assert_eq!(x.trailing_ones(), 0); - } + const X: $T = 0b0010_1100; + assert_eq_const_safe!(X.leading_ones(), 0); + assert_eq_const_safe!(X.trailing_ones(), 0); + } - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + fn test_rotate() { + assert_eq_const_safe!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq_const_safe!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq_const_safe!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq_const_safe!(_0.rotate_left(124), _0); + assert_eq_const_safe!(_1.rotate_left(124), _1); + assert_eq_const_safe!(_0.rotate_right(124), _0); + assert_eq_const_safe!(_1.rotate_right(124), _1); - // Rotating by 0 should have no effect - assert_eq!(A.rotate_left(0), A); - assert_eq!(B.rotate_left(0), B); - assert_eq!(C.rotate_left(0), C); - // Rotating by a multiple of word size should also have no effect - assert_eq!(A.rotate_left(128), A); - assert_eq!(B.rotate_left(128), B); - assert_eq!(C.rotate_left(128), C); - } + // Rotating by 0 should have no effect + assert_eq_const_safe!(A.rotate_left(0), A); + assert_eq_const_safe!(B.rotate_left(0), B); + assert_eq_const_safe!(C.rotate_left(0), C); + // Rotating by a multiple of word size should also have no effect + assert_eq_const_safe!(A.rotate_left(128), A); + assert_eq_const_safe!(B.rotate_left(128), B); + assert_eq_const_safe!(C.rotate_left(128), C); + } - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); + fn test_swap_bytes() { + assert_eq_const_safe!(A.swap_bytes().swap_bytes(), A); + assert_eq_const_safe!(B.swap_bytes().swap_bytes(), B); + assert_eq_const_safe!(C.swap_bytes().swap_bytes(), C); - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } + // Swapping these should make no difference + assert_eq_const_safe!(_0.swap_bytes(), _0); + assert_eq_const_safe!(_1.swap_bytes(), _1); + } - #[test] - fn test_le() { - assert_eq!($T::from_le(A.to_le()), A); - assert_eq!($T::from_le(B.to_le()), B); - assert_eq!($T::from_le(C.to_le()), C); - assert_eq!($T::from_le(_0), _0); - assert_eq!($T::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } + fn test_le() { + assert_eq_const_safe!($T::from_le(A.to_le()), A); + assert_eq_const_safe!($T::from_le(B.to_le()), B); + assert_eq_const_safe!($T::from_le(C.to_le()), C); + assert_eq_const_safe!($T::from_le(_0), _0); + assert_eq_const_safe!($T::from_le(_1), _1); + assert_eq_const_safe!(_0.to_le(), _0); + assert_eq_const_safe!(_1.to_le(), _1); + } - #[test] - fn test_be() { - assert_eq!($T::from_be(A.to_be()), A); - assert_eq!($T::from_be(B.to_be()), B); - assert_eq!($T::from_be(C.to_be()), C); - assert_eq!($T::from_be(_0), _0); - assert_eq!($T::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } + fn test_be() { + assert_eq_const_safe!($T::from_be(A.to_be()), A); + assert_eq_const_safe!($T::from_be(B.to_be()), B); + assert_eq_const_safe!($T::from_be(C.to_be()), C); + assert_eq_const_safe!($T::from_be(_0), _0); + assert_eq_const_safe!($T::from_be(_1), _1); + assert_eq_const_safe!(_0.to_be(), _0); + assert_eq_const_safe!(_1.to_be(), _1); + } - #[test] - fn test_signed_checked_div() { - assert_eq!((10 as $T).checked_div(2), Some(5)); - assert_eq!((5 as $T).checked_div(0), None); - assert_eq!(isize::MIN.checked_div(-1), None); - } + fn test_signed_checked_div() { + assert_eq_const_safe!((10 as $T).checked_div(2), Some(5)); + assert_eq_const_safe!((5 as $T).checked_div(0), None); + assert_eq_const_safe!(isize::MIN.checked_div(-1), None); + } - #[test] - fn test_saturating_abs() { - assert_eq!((0 as $T).saturating_abs(), 0); - assert_eq!((123 as $T).saturating_abs(), 123); - assert_eq!((-123 as $T).saturating_abs(), 123); - assert_eq!((MAX - 2).saturating_abs(), MAX - 2); - assert_eq!((MAX - 1).saturating_abs(), MAX - 1); - assert_eq!(MAX.saturating_abs(), MAX); - assert_eq!((MIN + 2).saturating_abs(), MAX - 1); - assert_eq!((MIN + 1).saturating_abs(), MAX); - assert_eq!(MIN.saturating_abs(), MAX); - } + fn test_saturating_abs() { + assert_eq_const_safe!((0 as $T).saturating_abs(), 0); + assert_eq_const_safe!((123 as $T).saturating_abs(), 123); + assert_eq_const_safe!((-123 as $T).saturating_abs(), 123); + assert_eq_const_safe!((MAX - 2).saturating_abs(), MAX - 2); + assert_eq_const_safe!((MAX - 1).saturating_abs(), MAX - 1); + assert_eq_const_safe!(MAX.saturating_abs(), MAX); + assert_eq_const_safe!((MIN + 2).saturating_abs(), MAX - 1); + assert_eq_const_safe!((MIN + 1).saturating_abs(), MAX); + assert_eq_const_safe!(MIN.saturating_abs(), MAX); + } - #[test] - fn test_saturating_neg() { - assert_eq!((0 as $T).saturating_neg(), 0); - assert_eq!((123 as $T).saturating_neg(), -123); - assert_eq!((-123 as $T).saturating_neg(), 123); - assert_eq!((MAX - 2).saturating_neg(), MIN + 3); - assert_eq!((MAX - 1).saturating_neg(), MIN + 2); - assert_eq!(MAX.saturating_neg(), MIN + 1); - assert_eq!((MIN + 2).saturating_neg(), MAX - 1); - assert_eq!((MIN + 1).saturating_neg(), MAX); - assert_eq!(MIN.saturating_neg(), MAX); + fn test_saturating_neg() { + assert_eq_const_safe!((0 as $T).saturating_neg(), 0); + assert_eq_const_safe!((123 as $T).saturating_neg(), -123); + assert_eq_const_safe!((-123 as $T).saturating_neg(), 123); + assert_eq_const_safe!((MAX - 2).saturating_neg(), MIN + 3); + assert_eq_const_safe!((MAX - 1).saturating_neg(), MIN + 2); + assert_eq_const_safe!(MAX.saturating_neg(), MIN + 1); + assert_eq_const_safe!((MIN + 2).saturating_neg(), MAX - 1); + assert_eq_const_safe!((MIN + 1).saturating_neg(), MAX); + assert_eq_const_safe!(MIN.saturating_neg(), MAX); + } } #[test] @@ -222,173 +212,173 @@ macro_rules! int_module { assert_eq!(from_str::<$T>("x"), None); } - #[test] - fn test_from_str_radix() { - assert_eq!($T::from_str_radix("123", 10), Ok(123 as $T)); - assert_eq!($T::from_str_radix("1001", 2), Ok(9 as $T)); - assert_eq!($T::from_str_radix("123", 8), Ok(83 as $T)); - assert_eq!(i32::from_str_radix("123", 16), Ok(291 as i32)); - assert_eq!(i32::from_str_radix("ffff", 16), Ok(65535 as i32)); - assert_eq!(i32::from_str_radix("FFFF", 16), Ok(65535 as i32)); - assert_eq!($T::from_str_radix("z", 36), Ok(35 as $T)); - assert_eq!($T::from_str_radix("Z", 36), Ok(35 as $T)); + test_runtime_and_compiletime! { + fn test_from_str_radix() { + assert_eq_const_safe!($T::from_str_radix("123", 10), Ok(123 as $T)); + assert_eq_const_safe!($T::from_str_radix("1001", 2), Ok(9 as $T)); + assert_eq_const_safe!($T::from_str_radix("123", 8), Ok(83 as $T)); + assert_eq_const_safe!(i32::from_str_radix("123", 16), Ok(291 as i32)); + assert_eq_const_safe!(i32::from_str_radix("ffff", 16), Ok(65535 as i32)); + assert_eq_const_safe!(i32::from_str_radix("FFFF", 16), Ok(65535 as i32)); + assert_eq_const_safe!($T::from_str_radix("z", 36), Ok(35 as $T)); + assert_eq_const_safe!($T::from_str_radix("Z", 36), Ok(35 as $T)); - assert_eq!($T::from_str_radix("-123", 10), Ok(-123 as $T)); - assert_eq!($T::from_str_radix("-1001", 2), Ok(-9 as $T)); - assert_eq!($T::from_str_radix("-123", 8), Ok(-83 as $T)); - assert_eq!(i32::from_str_radix("-123", 16), Ok(-291 as i32)); - assert_eq!(i32::from_str_radix("-ffff", 16), Ok(-65535 as i32)); - assert_eq!(i32::from_str_radix("-FFFF", 16), Ok(-65535 as i32)); - assert_eq!($T::from_str_radix("-z", 36), Ok(-35 as $T)); - assert_eq!($T::from_str_radix("-Z", 36), Ok(-35 as $T)); + assert_eq_const_safe!($T::from_str_radix("-123", 10), Ok(-123 as $T)); + assert_eq_const_safe!($T::from_str_radix("-1001", 2), Ok(-9 as $T)); + assert_eq_const_safe!($T::from_str_radix("-123", 8), Ok(-83 as $T)); + assert_eq_const_safe!(i32::from_str_radix("-123", 16), Ok(-291 as i32)); + assert_eq_const_safe!(i32::from_str_radix("-ffff", 16), Ok(-65535 as i32)); + assert_eq_const_safe!(i32::from_str_radix("-FFFF", 16), Ok(-65535 as i32)); + assert_eq_const_safe!($T::from_str_radix("-z", 36), Ok(-35 as $T)); + assert_eq_const_safe!($T::from_str_radix("-Z", 36), Ok(-35 as $T)); - assert_eq!($T::from_str_radix("Z", 35).ok(), None::<$T>); - assert_eq!($T::from_str_radix("-9", 2).ok(), None::<$T>); - assert_eq!($T::from_str_radix("10_0", 10).ok(), None::<$T>); - assert_eq!(u32::from_str_radix("-9", 10).ok(), None::); - } + assert!($T::from_str_radix("Z", 35).is_err()); + assert!($T::from_str_radix("-9", 2).is_err()); + assert!($T::from_str_radix("10_0", 10).is_err()); + assert!(u32::from_str_radix("-9", 10).is_err()); + } - #[test] - fn test_pow() { - let mut r = 2 as $T; - assert_eq!(r.pow(2), 4 as $T); - assert_eq!(r.pow(0), 1 as $T); - assert_eq!(r.wrapping_pow(2), 4 as $T); - assert_eq!(r.wrapping_pow(0), 1 as $T); - assert_eq!(r.checked_pow(2), Some(4 as $T)); - assert_eq!(r.checked_pow(0), Some(1 as $T)); - assert_eq!(r.overflowing_pow(2), (4 as $T, false)); - assert_eq!(r.overflowing_pow(0), (1 as $T, false)); - assert_eq!(r.saturating_pow(2), 4 as $T); - assert_eq!(r.saturating_pow(0), 1 as $T); + fn test_pow() { + { + const R: $T = 2; + assert_eq_const_safe!(R.pow(2), 4 as $T); + assert_eq_const_safe!(R.pow(0), 1 as $T); + assert_eq_const_safe!(R.wrapping_pow(2), 4 as $T); + assert_eq_const_safe!(R.wrapping_pow(0), 1 as $T); + assert_eq_const_safe!(R.checked_pow(2), Some(4 as $T)); + assert_eq_const_safe!(R.checked_pow(0), Some(1 as $T)); + assert_eq_const_safe!(R.overflowing_pow(2), (4 as $T, false)); + assert_eq_const_safe!(R.overflowing_pow(0), (1 as $T, false)); + assert_eq_const_safe!(R.saturating_pow(2), 4 as $T); + assert_eq_const_safe!(R.saturating_pow(0), 1 as $T); + } - r = MAX; - // use `^` to represent .pow() with no overflow. - // if itest::MAX == 2^j-1, then itest is a `j` bit int, - // so that `itest::MAX*itest::MAX == 2^(2*j)-2^(j+1)+1`, - // thussaturating_pow the overflowing result is exactly 1. - assert_eq!(r.wrapping_pow(2), 1 as $T); - assert_eq!(r.checked_pow(2), None); - assert_eq!(r.overflowing_pow(2), (1 as $T, true)); - assert_eq!(r.saturating_pow(2), MAX); - //test for negative exponent. - r = -2 as $T; - assert_eq!(r.pow(2), 4 as $T); - assert_eq!(r.pow(3), -8 as $T); - assert_eq!(r.pow(0), 1 as $T); - assert_eq!(r.wrapping_pow(2), 4 as $T); - assert_eq!(r.wrapping_pow(3), -8 as $T); - assert_eq!(r.wrapping_pow(0), 1 as $T); - assert_eq!(r.checked_pow(2), Some(4 as $T)); - assert_eq!(r.checked_pow(3), Some(-8 as $T)); - assert_eq!(r.checked_pow(0), Some(1 as $T)); - assert_eq!(r.overflowing_pow(2), (4 as $T, false)); - assert_eq!(r.overflowing_pow(3), (-8 as $T, false)); - assert_eq!(r.overflowing_pow(0), (1 as $T, false)); - assert_eq!(r.saturating_pow(2), 4 as $T); - assert_eq!(r.saturating_pow(3), -8 as $T); - assert_eq!(r.saturating_pow(0), 1 as $T); - } + { + const R: $T = MAX; + // use `^` to represent .pow() with no overflow. + // if itest::MAX == 2^j-1, then itest is a `j` bit int, + // so that `itest::MAX*itest::MAX == 2^(2*j)-2^(j+1)+1`, + // thussaturating_pow the overflowing result is exactly 1. + assert_eq_const_safe!(R.wrapping_pow(2), 1 as $T); + assert_eq_const_safe!(R.checked_pow(2), None); + assert_eq_const_safe!(R.overflowing_pow(2), (1 as $T, true)); + assert_eq_const_safe!(R.saturating_pow(2), MAX); + } - #[test] - fn test_div_floor() { - let a: $T = 8; - let b = 3; - assert_eq!(a.div_floor(b), 2); - assert_eq!(a.div_floor(-b), -3); - assert_eq!((-a).div_floor(b), -3); - assert_eq!((-a).div_floor(-b), 2); - } + { + // test for negative exponent. + const R: $T = -2; + assert_eq_const_safe!(R.pow(2), 4 as $T); + assert_eq_const_safe!(R.pow(3), -8 as $T); + assert_eq_const_safe!(R.pow(0), 1 as $T); + assert_eq_const_safe!(R.wrapping_pow(2), 4 as $T); + assert_eq_const_safe!(R.wrapping_pow(3), -8 as $T); + assert_eq_const_safe!(R.wrapping_pow(0), 1 as $T); + assert_eq_const_safe!(R.checked_pow(2), Some(4 as $T)); + assert_eq_const_safe!(R.checked_pow(3), Some(-8 as $T)); + assert_eq_const_safe!(R.checked_pow(0), Some(1 as $T)); + assert_eq_const_safe!(R.overflowing_pow(2), (4 as $T, false)); + assert_eq_const_safe!(R.overflowing_pow(3), (-8 as $T, false)); + assert_eq_const_safe!(R.overflowing_pow(0), (1 as $T, false)); + assert_eq_const_safe!(R.saturating_pow(2), 4 as $T); + assert_eq_const_safe!(R.saturating_pow(3), -8 as $T); + assert_eq_const_safe!(R.saturating_pow(0), 1 as $T); + } + } - #[test] - fn test_div_ceil() { - let a: $T = 8; - let b = 3; - assert_eq!(a.div_ceil(b), 3); - assert_eq!(a.div_ceil(-b), -2); - assert_eq!((-a).div_ceil(b), -2); - assert_eq!((-a).div_ceil(-b), 3); - } + fn test_div_floor() { + const A: $T = 8; + const B: $T = 3; + assert_eq_const_safe!(A.div_floor(B), 2); + assert_eq_const_safe!(A.div_floor(-B), -3); + assert_eq_const_safe!((-A).div_floor(B), -3); + assert_eq_const_safe!((-A).div_floor(-B), 2); + } - #[test] - fn test_next_multiple_of() { - assert_eq!((16 as $T).next_multiple_of(8), 16); - assert_eq!((23 as $T).next_multiple_of(8), 24); - assert_eq!((16 as $T).next_multiple_of(-8), 16); - assert_eq!((23 as $T).next_multiple_of(-8), 16); - assert_eq!((-16 as $T).next_multiple_of(8), -16); - assert_eq!((-23 as $T).next_multiple_of(8), -16); - assert_eq!((-16 as $T).next_multiple_of(-8), -16); - assert_eq!((-23 as $T).next_multiple_of(-8), -24); - assert_eq!(MIN.next_multiple_of(-1), MIN); - } + fn test_div_ceil() { + const A: $T = 8; + const B: $T = 3; + assert_eq_const_safe!(A.div_ceil(B), 3); + assert_eq_const_safe!(A.div_ceil(-B), -2); + assert_eq_const_safe!((-A).div_ceil(B), -2); + assert_eq_const_safe!((-A).div_ceil(-B), 3); + } - #[test] - fn test_checked_next_multiple_of() { - assert_eq!((16 as $T).checked_next_multiple_of(8), Some(16)); - assert_eq!((23 as $T).checked_next_multiple_of(8), Some(24)); - assert_eq!((16 as $T).checked_next_multiple_of(-8), Some(16)); - assert_eq!((23 as $T).checked_next_multiple_of(-8), Some(16)); - assert_eq!((-16 as $T).checked_next_multiple_of(8), Some(-16)); - assert_eq!((-23 as $T).checked_next_multiple_of(8), Some(-16)); - assert_eq!((-16 as $T).checked_next_multiple_of(-8), Some(-16)); - assert_eq!((-23 as $T).checked_next_multiple_of(-8), Some(-24)); - assert_eq!((1 as $T).checked_next_multiple_of(0), None); - assert_eq!(MAX.checked_next_multiple_of(2), None); - assert_eq!(MIN.checked_next_multiple_of(-3), None); - assert_eq!(MIN.checked_next_multiple_of(-1), Some(MIN)); - } + fn test_next_multiple_of() { + assert_eq_const_safe!((16 as $T).next_multiple_of(8), 16); + assert_eq_const_safe!((23 as $T).next_multiple_of(8), 24); + assert_eq_const_safe!((16 as $T).next_multiple_of(-8), 16); + assert_eq_const_safe!((23 as $T).next_multiple_of(-8), 16); + assert_eq_const_safe!((-16 as $T).next_multiple_of(8), -16); + assert_eq_const_safe!((-23 as $T).next_multiple_of(8), -16); + assert_eq_const_safe!((-16 as $T).next_multiple_of(-8), -16); + assert_eq_const_safe!((-23 as $T).next_multiple_of(-8), -24); + assert_eq_const_safe!(MIN.next_multiple_of(-1), MIN); + } - #[test] - fn test_carrying_add() { - assert_eq!($T::MAX.carrying_add(1, false), ($T::MIN, true)); - assert_eq!($T::MAX.carrying_add(0, true), ($T::MIN, true)); - assert_eq!($T::MAX.carrying_add(1, true), ($T::MIN + 1, true)); - assert_eq!($T::MAX.carrying_add(-1, false), ($T::MAX - 1, false)); - assert_eq!($T::MAX.carrying_add(-1, true), ($T::MAX, false)); // no intermediate overflow - assert_eq!($T::MIN.carrying_add(-1, false), ($T::MAX, true)); - assert_eq!($T::MIN.carrying_add(-1, true), ($T::MIN, false)); // no intermediate overflow - assert_eq!((0 as $T).carrying_add($T::MAX, true), ($T::MIN, true)); - assert_eq!((0 as $T).carrying_add($T::MIN, true), ($T::MIN + 1, false)); - } + fn test_checked_next_multiple_of() { + assert_eq_const_safe!((16 as $T).checked_next_multiple_of(8), Some(16)); + assert_eq_const_safe!((23 as $T).checked_next_multiple_of(8), Some(24)); + assert_eq_const_safe!((16 as $T).checked_next_multiple_of(-8), Some(16)); + assert_eq_const_safe!((23 as $T).checked_next_multiple_of(-8), Some(16)); + assert_eq_const_safe!((-16 as $T).checked_next_multiple_of(8), Some(-16)); + assert_eq_const_safe!((-23 as $T).checked_next_multiple_of(8), Some(-16)); + assert_eq_const_safe!((-16 as $T).checked_next_multiple_of(-8), Some(-16)); + assert_eq_const_safe!((-23 as $T).checked_next_multiple_of(-8), Some(-24)); + assert_eq_const_safe!((1 as $T).checked_next_multiple_of(0), None); + assert_eq_const_safe!(MAX.checked_next_multiple_of(2), None); + assert_eq_const_safe!(MIN.checked_next_multiple_of(-3), None); + assert_eq_const_safe!(MIN.checked_next_multiple_of(-1), Some(MIN)); + } - #[test] - fn test_borrowing_sub() { - assert_eq!($T::MIN.borrowing_sub(1, false), ($T::MAX, true)); - assert_eq!($T::MIN.borrowing_sub(0, true), ($T::MAX, true)); - assert_eq!($T::MIN.borrowing_sub(1, true), ($T::MAX - 1, true)); - assert_eq!($T::MIN.borrowing_sub(-1, false), ($T::MIN + 1, false)); - assert_eq!($T::MIN.borrowing_sub(-1, true), ($T::MIN, false)); // no intermediate overflow - assert_eq!($T::MAX.borrowing_sub(-1, false), ($T::MIN, true)); - assert_eq!($T::MAX.borrowing_sub(-1, true), ($T::MAX, false)); // no intermediate overflow - assert_eq!((0 as $T).borrowing_sub($T::MIN, false), ($T::MIN, true)); - assert_eq!((0 as $T).borrowing_sub($T::MIN, true), ($T::MAX, false)); - } + fn test_carrying_add() { + assert_eq_const_safe!(MAX.carrying_add(1, false), (MIN, true)); + assert_eq_const_safe!(MAX.carrying_add(0, true), (MIN, true)); + assert_eq_const_safe!(MAX.carrying_add(1, true), (MIN + 1, true)); + assert_eq_const_safe!(MAX.carrying_add(-1, false), (MAX - 1, false)); + assert_eq_const_safe!(MAX.carrying_add(-1, true), (MAX, false)); // no intermediate overflow + assert_eq_const_safe!(MIN.carrying_add(-1, false), (MAX, true)); + assert_eq_const_safe!(MIN.carrying_add(-1, true), (MIN, false)); // no intermediate overflow + assert_eq_const_safe!((0 as $T).carrying_add(MAX, true), (MIN, true)); + assert_eq_const_safe!((0 as $T).carrying_add(MIN, true), (MIN + 1, false)); + } - #[test] - fn test_midpoint() { - assert_eq!(<$T>::midpoint(1, 3), 2); - assert_eq!(<$T>::midpoint(3, 1), 2); + fn test_borrowing_sub() { + assert_eq_const_safe!(MIN.borrowing_sub(1, false), (MAX, true)); + assert_eq_const_safe!(MIN.borrowing_sub(0, true), (MAX, true)); + assert_eq_const_safe!(MIN.borrowing_sub(1, true), (MAX - 1, true)); + assert_eq_const_safe!(MIN.borrowing_sub(-1, false), (MIN + 1, false)); + assert_eq_const_safe!(MIN.borrowing_sub(-1, true), (MIN, false)); // no intermediate overflow + assert_eq_const_safe!(MAX.borrowing_sub(-1, false), (MIN, true)); + assert_eq_const_safe!(MAX.borrowing_sub(-1, true), (MAX, false)); // no intermediate overflow + assert_eq_const_safe!((0 as $T).borrowing_sub(MIN, false), (MIN, true)); + assert_eq_const_safe!((0 as $T).borrowing_sub(MIN, true), (MAX, false)); + } - assert_eq!(<$T>::midpoint(0, 0), 0); - assert_eq!(<$T>::midpoint(0, 2), 1); - assert_eq!(<$T>::midpoint(2, 0), 1); - assert_eq!(<$T>::midpoint(2, 2), 2); + fn test_midpoint() { + assert_eq_const_safe!(<$T>::midpoint(1, 3), 2); + assert_eq_const_safe!(<$T>::midpoint(3, 1), 2); - assert_eq!(<$T>::midpoint(1, 4), 2); - assert_eq!(<$T>::midpoint(4, 1), 2); - assert_eq!(<$T>::midpoint(3, 4), 3); - assert_eq!(<$T>::midpoint(4, 3), 3); + assert_eq_const_safe!(<$T>::midpoint(0, 0), 0); + assert_eq_const_safe!(<$T>::midpoint(0, 2), 1); + assert_eq_const_safe!(<$T>::midpoint(2, 0), 1); + assert_eq_const_safe!(<$T>::midpoint(2, 2), 2); - assert_eq!(<$T>::midpoint(<$T>::MIN, <$T>::MAX), -1); - assert_eq!(<$T>::midpoint(<$T>::MAX, <$T>::MIN), -1); - assert_eq!(<$T>::midpoint(<$T>::MIN, <$T>::MIN), <$T>::MIN); - assert_eq!(<$T>::midpoint(<$T>::MAX, <$T>::MAX), <$T>::MAX); + assert_eq_const_safe!(<$T>::midpoint(1, 4), 2); + assert_eq_const_safe!(<$T>::midpoint(4, 1), 2); + assert_eq_const_safe!(<$T>::midpoint(3, 4), 3); + assert_eq_const_safe!(<$T>::midpoint(4, 3), 3); - assert_eq!(<$T>::midpoint(<$T>::MIN, 6), <$T>::MIN / 2 + 3); - assert_eq!(<$T>::midpoint(6, <$T>::MIN), <$T>::MIN / 2 + 3); - assert_eq!(<$T>::midpoint(<$T>::MAX, 6), <$T>::MAX / 2 + 3); - assert_eq!(<$T>::midpoint(6, <$T>::MAX), <$T>::MAX / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MAX), -1); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MIN), -1); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MIN), <$T>::MIN); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MAX), <$T>::MAX); + + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, 6), <$T>::MIN / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(6, <$T>::MIN), <$T>::MIN / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, 6), <$T>::MAX / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(6, <$T>::MAX), <$T>::MAX / 2 + 3); + } } }; } diff --git a/library/core/tests/num/uint_macros.rs b/library/core/tests/num/uint_macros.rs index f4fa789461eb..105aad4522d7 100644 --- a/library/core/tests/num/uint_macros.rs +++ b/library/core/tests/num/uint_macros.rs @@ -2,7 +2,6 @@ macro_rules! uint_module { ($T:ident) => { use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr}; use core::$T::*; - use std::str::FromStr; use crate::num; @@ -35,122 +34,115 @@ macro_rules! uint_module { const _0: $T = 0; const _1: $T = !0; - #[test] - fn test_count_ones() { - assert!(A.count_ones() == 3); - assert!(B.count_ones() == 2); - assert!(C.count_ones() == 5); + test_runtime_and_compiletime! { + fn test_count_ones() { + assert!(A.count_ones() == 3); + assert!(B.count_ones() == 2); + assert!(C.count_ones() == 5); + } + + fn test_count_zeros() { + assert!(A.count_zeros() == $T::BITS - 3); + assert!(B.count_zeros() == $T::BITS - 2); + assert!(C.count_zeros() == $T::BITS - 5); + } + + fn test_leading_trailing_ones() { + const A: $T = 0b0101_1111; + assert_eq_const_safe!(A.trailing_ones(), 5); + assert_eq_const_safe!((!A).leading_ones(), $T::BITS - 7); + + assert_eq_const_safe!(A.reverse_bits().leading_ones(), 5); + + assert_eq_const_safe!(_1.leading_ones(), $T::BITS); + assert_eq_const_safe!(_1.trailing_ones(), $T::BITS); + + assert_eq_const_safe!((_1 << 1).trailing_ones(), 0); + assert_eq_const_safe!((_1 >> 1).leading_ones(), 0); + + assert_eq_const_safe!((_1 << 1).leading_ones(), $T::BITS - 1); + assert_eq_const_safe!((_1 >> 1).trailing_ones(), $T::BITS - 1); + + assert_eq_const_safe!(_0.leading_ones(), 0); + assert_eq_const_safe!(_0.trailing_ones(), 0); + + const X: $T = 0b0010_1100; + assert_eq_const_safe!(X.leading_ones(), 0); + assert_eq_const_safe!(X.trailing_ones(), 0); + } + + fn test_rotate() { + assert_eq_const_safe!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq_const_safe!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq_const_safe!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq_const_safe!(_0.rotate_left(124), _0); + assert_eq_const_safe!(_1.rotate_left(124), _1); + assert_eq_const_safe!(_0.rotate_right(124), _0); + assert_eq_const_safe!(_1.rotate_right(124), _1); + + // Rotating by 0 should have no effect + assert_eq_const_safe!(A.rotate_left(0), A); + assert_eq_const_safe!(B.rotate_left(0), B); + assert_eq_const_safe!(C.rotate_left(0), C); + // Rotating by a multiple of word size should also have no effect + assert_eq_const_safe!(A.rotate_left(128), A); + assert_eq_const_safe!(B.rotate_left(128), B); + assert_eq_const_safe!(C.rotate_left(128), C); + } + + fn test_swap_bytes() { + assert_eq_const_safe!(A.swap_bytes().swap_bytes(), A); + assert_eq_const_safe!(B.swap_bytes().swap_bytes(), B); + assert_eq_const_safe!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq_const_safe!(_0.swap_bytes(), _0); + assert_eq_const_safe!(_1.swap_bytes(), _1); + } + + fn test_reverse_bits() { + assert_eq_const_safe!(A.reverse_bits().reverse_bits(), A); + assert_eq_const_safe!(B.reverse_bits().reverse_bits(), B); + assert_eq_const_safe!(C.reverse_bits().reverse_bits(), C); + + // Swapping these should make no difference + assert_eq_const_safe!(_0.reverse_bits(), _0); + assert_eq_const_safe!(_1.reverse_bits(), _1); + } + + fn test_le() { + assert_eq_const_safe!($T::from_le(A.to_le()), A); + assert_eq_const_safe!($T::from_le(B.to_le()), B); + assert_eq_const_safe!($T::from_le(C.to_le()), C); + assert_eq_const_safe!($T::from_le(_0), _0); + assert_eq_const_safe!($T::from_le(_1), _1); + assert_eq_const_safe!(_0.to_le(), _0); + assert_eq_const_safe!(_1.to_le(), _1); + } + + fn test_be() { + assert_eq_const_safe!($T::from_be(A.to_be()), A); + assert_eq_const_safe!($T::from_be(B.to_be()), B); + assert_eq_const_safe!($T::from_be(C.to_be()), C); + assert_eq_const_safe!($T::from_be(_0), _0); + assert_eq_const_safe!($T::from_be(_1), _1); + assert_eq_const_safe!(_0.to_be(), _0); + assert_eq_const_safe!(_1.to_be(), _1); + } + + fn test_unsigned_checked_div() { + assert_eq_const_safe!((10 as $T).checked_div(2), Some(5)); + assert_eq_const_safe!((5 as $T).checked_div(0), None); + } } - #[test] - fn test_count_zeros() { - assert!(A.count_zeros() == $T::BITS - 3); - assert!(B.count_zeros() == $T::BITS - 2); - assert!(C.count_zeros() == $T::BITS - 5); - } - - #[test] - fn test_leading_trailing_ones() { - let a: $T = 0b0101_1111; - assert_eq!(a.trailing_ones(), 5); - assert_eq!((!a).leading_ones(), $T::BITS - 7); - - assert_eq!(a.reverse_bits().leading_ones(), 5); - - assert_eq!(_1.leading_ones(), $T::BITS); - assert_eq!(_1.trailing_ones(), $T::BITS); - - assert_eq!((_1 << 1).trailing_ones(), 0); - assert_eq!((_1 >> 1).leading_ones(), 0); - - assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1); - assert_eq!((_1 >> 1).trailing_ones(), $T::BITS - 1); - - assert_eq!(_0.leading_ones(), 0); - assert_eq!(_0.trailing_ones(), 0); - - let x: $T = 0b0010_1100; - assert_eq!(x.leading_ones(), 0); - assert_eq!(x.trailing_ones(), 0); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - - // Rotating by 0 should have no effect - assert_eq!(A.rotate_left(0), A); - assert_eq!(B.rotate_left(0), B); - assert_eq!(C.rotate_left(0), C); - // Rotating by a multiple of word size should also have no effect - assert_eq!(A.rotate_left(128), A); - assert_eq!(B.rotate_left(128), B); - assert_eq!(C.rotate_left(128), C); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_reverse_bits() { - assert_eq!(A.reverse_bits().reverse_bits(), A); - assert_eq!(B.reverse_bits().reverse_bits(), B); - assert_eq!(C.reverse_bits().reverse_bits(), C); - - // Swapping these should make no difference - assert_eq!(_0.reverse_bits(), _0); - assert_eq!(_1.reverse_bits(), _1); - } - - #[test] - fn test_le() { - assert_eq!($T::from_le(A.to_le()), A); - assert_eq!($T::from_le(B.to_le()), B); - assert_eq!($T::from_le(C.to_le()), C); - assert_eq!($T::from_le(_0), _0); - assert_eq!($T::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!($T::from_be(A.to_be()), A); - assert_eq!($T::from_be(B.to_be()), B); - assert_eq!($T::from_be(C.to_be()), C); - assert_eq!($T::from_be(_0), _0); - assert_eq!($T::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_unsigned_checked_div() { - assert!((10 as $T).checked_div(2) == Some(5)); - assert!((5 as $T).checked_div(0) == None); - } - - fn from_str(t: &str) -> Option { - FromStr::from_str(t).ok() + fn from_str(t: &str) -> Option { + core::str::FromStr::from_str(t).ok() } #[test] @@ -166,52 +158,55 @@ macro_rules! uint_module { assert_eq!(from_str::<$T>("x"), None); } - #[test] - pub fn test_parse_bytes() { - assert_eq!($T::from_str_radix("123", 10), Ok(123 as $T)); - assert_eq!($T::from_str_radix("1001", 2), Ok(9 as $T)); - assert_eq!($T::from_str_radix("123", 8), Ok(83 as $T)); - assert_eq!(u16::from_str_radix("123", 16), Ok(291 as u16)); - assert_eq!(u16::from_str_radix("ffff", 16), Ok(65535 as u16)); - assert_eq!($T::from_str_radix("z", 36), Ok(35 as $T)); + test_runtime_and_compiletime! { + fn test_parse_bytes() { + assert_eq_const_safe!($T::from_str_radix("123", 10), Ok(123 as $T)); + assert_eq_const_safe!($T::from_str_radix("1001", 2), Ok(9 as $T)); + assert_eq_const_safe!($T::from_str_radix("123", 8), Ok(83 as $T)); + assert_eq_const_safe!(u16::from_str_radix("123", 16), Ok(291 as u16)); + assert_eq_const_safe!(u16::from_str_radix("ffff", 16), Ok(65535 as u16)); + assert_eq_const_safe!($T::from_str_radix("z", 36), Ok(35 as $T)); - assert_eq!($T::from_str_radix("Z", 10).ok(), None::<$T>); - assert_eq!($T::from_str_radix("_", 2).ok(), None::<$T>); - } + assert!($T::from_str_radix("Z", 10).is_err()); + assert!($T::from_str_radix("_", 2).is_err()); + } - #[test] - fn test_pow() { - let mut r = 2 as $T; - assert_eq!(r.pow(2), 4 as $T); - assert_eq!(r.pow(0), 1 as $T); - assert_eq!(r.wrapping_pow(2), 4 as $T); - assert_eq!(r.wrapping_pow(0), 1 as $T); - assert_eq!(r.checked_pow(2), Some(4 as $T)); - assert_eq!(r.checked_pow(0), Some(1 as $T)); - assert_eq!(r.overflowing_pow(2), (4 as $T, false)); - assert_eq!(r.overflowing_pow(0), (1 as $T, false)); - assert_eq!(r.saturating_pow(2), 4 as $T); - assert_eq!(r.saturating_pow(0), 1 as $T); + fn test_pow() { + { + const R: $T = 2; + assert_eq_const_safe!(R.pow(2), 4 as $T); + assert_eq_const_safe!(R.pow(0), 1 as $T); + assert_eq_const_safe!(R.wrapping_pow(2), 4 as $T); + assert_eq_const_safe!(R.wrapping_pow(0), 1 as $T); + assert_eq_const_safe!(R.checked_pow(2), Some(4 as $T)); + assert_eq_const_safe!(R.checked_pow(0), Some(1 as $T)); + assert_eq_const_safe!(R.overflowing_pow(2), (4 as $T, false)); + assert_eq_const_safe!(R.overflowing_pow(0), (1 as $T, false)); + assert_eq_const_safe!(R.saturating_pow(2), 4 as $T); + assert_eq_const_safe!(R.saturating_pow(0), 1 as $T); + } - r = MAX; - // use `^` to represent .pow() with no overflow. - // if itest::MAX == 2^j-1, then itest is a `j` bit int, - // so that `itest::MAX*itest::MAX == 2^(2*j)-2^(j+1)+1`, - // thussaturating_pow the overflowing result is exactly 1. - assert_eq!(r.wrapping_pow(2), 1 as $T); - assert_eq!(r.checked_pow(2), None); - assert_eq!(r.overflowing_pow(2), (1 as $T, true)); - assert_eq!(r.saturating_pow(2), MAX); - } + { + const R: $T = $T::MAX; + // use `^` to represent .pow() with no overflow. + // if itest::MAX == 2^j-1, then itest is a `j` bit int, + // so that `itest::MAX*itest::MAX == 2^(2*j)-2^(j+1)+1`, + // thussaturating_pow the overflowing result is exactly 1. + assert_eq_const_safe!(R.wrapping_pow(2), 1 as $T); + assert_eq_const_safe!(R.checked_pow(2), None); + assert_eq_const_safe!(R.overflowing_pow(2), (1 as $T, true)); + assert_eq_const_safe!(R.saturating_pow(2), MAX); + } + } - #[test] - fn test_isqrt() { - assert_eq!((0 as $T).isqrt(), 0 as $T); - assert_eq!((1 as $T).isqrt(), 1 as $T); - assert_eq!((2 as $T).isqrt(), 1 as $T); - assert_eq!((99 as $T).isqrt(), 9 as $T); - assert_eq!((100 as $T).isqrt(), 10 as $T); - assert_eq!($T::MAX.isqrt(), (1 << ($T::BITS / 2)) - 1); + fn test_isqrt() { + assert_eq_const_safe!((0 as $T).isqrt(), 0 as $T); + assert_eq_const_safe!((1 as $T).isqrt(), 1 as $T); + assert_eq_const_safe!((2 as $T).isqrt(), 1 as $T); + assert_eq_const_safe!((99 as $T).isqrt(), 9 as $T); + assert_eq_const_safe!((100 as $T).isqrt(), 10 as $T); + assert_eq_const_safe!($T::MAX.isqrt(), (1 << ($T::BITS / 2)) - 1); + } } #[cfg(not(miri))] // Miri is too slow @@ -233,85 +228,79 @@ macro_rules! uint_module { } } - #[test] - fn test_div_floor() { - assert_eq!((8 as $T).div_floor(3), 2); - } + test_runtime_and_compiletime! { + fn test_div_floor() { + assert_eq_const_safe!((8 as $T).div_floor(3), 2); + } - #[test] - fn test_div_ceil() { - assert_eq!((8 as $T).div_ceil(3), 3); - } + fn test_div_ceil() { + assert_eq_const_safe!((8 as $T).div_ceil(3), 3); + } - #[test] - fn test_next_multiple_of() { - assert_eq!((16 as $T).next_multiple_of(8), 16); - assert_eq!((23 as $T).next_multiple_of(8), 24); - assert_eq!(MAX.next_multiple_of(1), MAX); - } + fn test_next_multiple_of() { + assert_eq_const_safe!((16 as $T).next_multiple_of(8), 16); + assert_eq_const_safe!((23 as $T).next_multiple_of(8), 24); + assert_eq_const_safe!(MAX.next_multiple_of(1), MAX); + } - #[test] - fn test_checked_next_multiple_of() { - assert_eq!((16 as $T).checked_next_multiple_of(8), Some(16)); - assert_eq!((23 as $T).checked_next_multiple_of(8), Some(24)); - assert_eq!((1 as $T).checked_next_multiple_of(0), None); - assert_eq!(MAX.checked_next_multiple_of(2), None); - } + fn test_checked_next_multiple_of() { + assert_eq_const_safe!((16 as $T).checked_next_multiple_of(8), Some(16)); + assert_eq_const_safe!((23 as $T).checked_next_multiple_of(8), Some(24)); + assert_eq_const_safe!((1 as $T).checked_next_multiple_of(0), None); + assert_eq_const_safe!(MAX.checked_next_multiple_of(2), None); + } - #[test] - fn test_is_next_multiple_of() { - assert!((12 as $T).is_multiple_of(4)); - assert!(!(12 as $T).is_multiple_of(5)); - assert!((0 as $T).is_multiple_of(0)); - assert!(!(12 as $T).is_multiple_of(0)); - } + fn test_is_next_multiple_of() { + assert!((12 as $T).is_multiple_of(4)); + assert!(!(12 as $T).is_multiple_of(5)); + assert!((0 as $T).is_multiple_of(0)); + assert!(!(12 as $T).is_multiple_of(0)); + } - #[test] - fn test_carrying_add() { - assert_eq!($T::MAX.carrying_add(1, false), (0, true)); - assert_eq!($T::MAX.carrying_add(0, true), (0, true)); - assert_eq!($T::MAX.carrying_add(1, true), (1, true)); + fn test_carrying_add() { + assert_eq_const_safe!($T::MAX.carrying_add(1, false), (0, true)); + assert_eq_const_safe!($T::MAX.carrying_add(0, true), (0, true)); + assert_eq_const_safe!($T::MAX.carrying_add(1, true), (1, true)); - assert_eq!($T::MIN.carrying_add($T::MAX, false), ($T::MAX, false)); - assert_eq!($T::MIN.carrying_add(0, true), (1, false)); - assert_eq!($T::MIN.carrying_add($T::MAX, true), (0, true)); - } + assert_eq_const_safe!($T::MIN.carrying_add($T::MAX, false), ($T::MAX, false)); + assert_eq_const_safe!($T::MIN.carrying_add(0, true), (1, false)); + assert_eq_const_safe!($T::MIN.carrying_add($T::MAX, true), (0, true)); + } - #[test] - fn test_borrowing_sub() { - assert_eq!($T::MIN.borrowing_sub(1, false), ($T::MAX, true)); - assert_eq!($T::MIN.borrowing_sub(0, true), ($T::MAX, true)); - assert_eq!($T::MIN.borrowing_sub(1, true), ($T::MAX - 1, true)); + fn test_borrowing_sub() { + assert_eq_const_safe!($T::MIN.borrowing_sub(1, false), ($T::MAX, true)); + assert_eq_const_safe!($T::MIN.borrowing_sub(0, true), ($T::MAX, true)); + assert_eq_const_safe!($T::MIN.borrowing_sub(1, true), ($T::MAX - 1, true)); - assert_eq!($T::MAX.borrowing_sub($T::MAX, false), (0, false)); - assert_eq!($T::MAX.borrowing_sub(0, true), ($T::MAX - 1, false)); - assert_eq!($T::MAX.borrowing_sub($T::MAX, true), ($T::MAX, true)); - } + assert_eq_const_safe!($T::MAX.borrowing_sub($T::MAX, false), (0, false)); + assert_eq_const_safe!($T::MAX.borrowing_sub(0, true), ($T::MAX - 1, false)); + assert_eq_const_safe!($T::MAX.borrowing_sub($T::MAX, true), ($T::MAX, true)); + } - #[test] - fn test_midpoint() { - assert_eq!(<$T>::midpoint(1, 3), 2); - assert_eq!(<$T>::midpoint(3, 1), 2); + fn test_midpoint() { + assert_eq_const_safe!(<$T>::midpoint(1, 3), 2); + assert_eq_const_safe!(<$T>::midpoint(3, 1), 2); - assert_eq!(<$T>::midpoint(0, 0), 0); - assert_eq!(<$T>::midpoint(0, 2), 1); - assert_eq!(<$T>::midpoint(2, 0), 1); - assert_eq!(<$T>::midpoint(2, 2), 2); + assert_eq_const_safe!(<$T>::midpoint(0, 0), 0); + assert_eq_const_safe!(<$T>::midpoint(0, 2), 1); + assert_eq_const_safe!(<$T>::midpoint(2, 0), 1); + assert_eq_const_safe!(<$T>::midpoint(2, 2), 2); - assert_eq!(<$T>::midpoint(1, 4), 2); - assert_eq!(<$T>::midpoint(4, 1), 2); - assert_eq!(<$T>::midpoint(3, 4), 3); - assert_eq!(<$T>::midpoint(4, 3), 3); + assert_eq_const_safe!(<$T>::midpoint(1, 4), 2); + assert_eq_const_safe!(<$T>::midpoint(4, 1), 2); + assert_eq_const_safe!(<$T>::midpoint(3, 4), 3); + assert_eq_const_safe!(<$T>::midpoint(4, 3), 3); - assert_eq!(<$T>::midpoint(<$T>::MIN, <$T>::MAX), (<$T>::MAX - <$T>::MIN) / 2); - assert_eq!(<$T>::midpoint(<$T>::MAX, <$T>::MIN), (<$T>::MAX - <$T>::MIN) / 2); - assert_eq!(<$T>::midpoint(<$T>::MIN, <$T>::MIN), <$T>::MIN); - assert_eq!(<$T>::midpoint(<$T>::MAX, <$T>::MAX), <$T>::MAX); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MAX), (<$T>::MAX - <$T>::MIN) / 2); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MIN), (<$T>::MAX - <$T>::MIN) / 2); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MIN), <$T>::MIN); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MAX), <$T>::MAX); - assert_eq!(<$T>::midpoint(<$T>::MIN, 6), <$T>::MIN / 2 + 3); - assert_eq!(<$T>::midpoint(6, <$T>::MIN), <$T>::MIN / 2 + 3); - assert_eq!(<$T>::midpoint(<$T>::MAX, 6), (<$T>::MAX - <$T>::MIN) / 2 + 3); - assert_eq!(<$T>::midpoint(6, <$T>::MAX), (<$T>::MAX - <$T>::MIN) / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, 6), <$T>::MIN / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(6, <$T>::MIN), <$T>::MIN / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, 6), (<$T>::MAX - <$T>::MIN) / 2 + 3); + assert_eq_const_safe!(<$T>::midpoint(6, <$T>::MAX), (<$T>::MAX - <$T>::MIN) / 2 + 3); + } } }; } From d6146a84962709628795c59a82ecdf99cf29264d Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Mon, 14 Oct 2024 18:47:00 -0400 Subject: [PATCH 017/366] Add a `const_sockaddr_setters` feature Unstably add `const` to the `sockaddr_setters` methods. Included API: // core::net impl SocketAddr { pub const fn set_ip(&mut self, new_ip: IpAddr); pub const fn set_port(&mut self, new_port: u16); } impl SocketAddrV4 { pub const fn set_ip(&mut self, new_ip: Ipv4Addr); pub const fn set_port(&mut self, new_port: u16); } impl SocketAddrV6 { pub const fn set_ip(&mut self, new_ip: Ipv6Addr); pub const fn set_port(&mut self, new_port: u16); } Tracking issue: --- library/core/src/lib.rs | 1 + library/core/src/net/socket_addr.rs | 40 +++++++++++++++++------------ 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 08c0d6e34cd0..5afafe141fcc 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -136,6 +136,7 @@ #![feature(const_raw_ptr_comparison)] #![feature(const_size_of_val)] #![feature(const_size_of_val_raw)] +#![feature(const_sockaddr_setters)] #![feature(const_strict_overflow_ops)] #![feature(const_swap)] #![feature(const_try)] diff --git a/library/core/src/net/socket_addr.rs b/library/core/src/net/socket_addr.rs index 4e339172b682..d54941506099 100644 --- a/library/core/src/net/socket_addr.rs +++ b/library/core/src/net/socket_addr.rs @@ -159,9 +159,10 @@ impl SocketAddr { /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1))); /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1))); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_ip(&mut self, new_ip: IpAddr) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_ip(&mut self, new_ip: IpAddr) { // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away. match (self, new_ip) { (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip), @@ -202,9 +203,10 @@ impl SocketAddr { /// socket.set_port(1025); /// assert_eq!(socket.port(), 1025); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_port(&mut self, new_port: u16) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_port(&mut self, new_port: u16) { match *self { SocketAddr::V4(ref mut a) => a.set_port(new_port), SocketAddr::V6(ref mut a) => a.set_port(new_port), @@ -307,9 +309,10 @@ impl SocketAddrV4 { /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1)); /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1)); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_ip(&mut self, new_ip: Ipv4Addr) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_ip(&mut self, new_ip: Ipv4Addr) { self.ip = new_ip; } @@ -342,9 +345,10 @@ impl SocketAddrV4 { /// socket.set_port(4242); /// assert_eq!(socket.port(), 4242); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_port(&mut self, new_port: u16) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_port(&mut self, new_port: u16) { self.port = new_port; } } @@ -403,9 +407,10 @@ impl SocketAddrV6 { /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0)); /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0)); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_ip(&mut self, new_ip: Ipv6Addr) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_ip(&mut self, new_ip: Ipv6Addr) { self.ip = new_ip; } @@ -438,9 +443,10 @@ impl SocketAddrV6 { /// socket.set_port(4242); /// assert_eq!(socket.port(), 4242); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_port(&mut self, new_port: u16) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_port(&mut self, new_port: u16) { self.port = new_port; } @@ -485,9 +491,10 @@ impl SocketAddrV6 { /// socket.set_flowinfo(56); /// assert_eq!(socket.flowinfo(), 56); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_flowinfo(&mut self, new_flowinfo: u32) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_flowinfo(&mut self, new_flowinfo: u32) { self.flowinfo = new_flowinfo; } @@ -527,9 +534,10 @@ impl SocketAddrV6 { /// socket.set_scope_id(42); /// assert_eq!(socket.scope_id(), 42); /// ``` - #[stable(feature = "sockaddr_setters", since = "1.9.0")] #[inline] - pub fn set_scope_id(&mut self, new_scope_id: u32) { + #[stable(feature = "sockaddr_setters", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_sockaddr_setters", issue = "131714")] + pub const fn set_scope_id(&mut self, new_scope_id: u32) { self.scope_id = new_scope_id; } } From 2af15d2ffdf52480ca3955e82535979f1b80e8e0 Mon Sep 17 00:00:00 2001 From: Johannes Altmanninger Date: Tue, 15 Oct 2024 08:33:14 +0200 Subject: [PATCH 018/366] line-index method to allow clamping column to line length Part of #18240 --- .../rust-analyzer/lib/line-index/Cargo.toml | 2 +- .../rust-analyzer/lib/line-index/src/lib.rs | 8 +++++++ .../rust-analyzer/lib/line-index/src/tests.rs | 23 +++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/lib/line-index/Cargo.toml b/src/tools/rust-analyzer/lib/line-index/Cargo.toml index 8ae4954dd0de..14196ba3d097 100644 --- a/src/tools/rust-analyzer/lib/line-index/Cargo.toml +++ b/src/tools/rust-analyzer/lib/line-index/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "line-index" -version = "0.1.1" +version = "0.1.2" description = "Maps flat `TextSize` offsets to/from `(line, column)` representation." license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/line-index" diff --git a/src/tools/rust-analyzer/lib/line-index/src/lib.rs b/src/tools/rust-analyzer/lib/line-index/src/lib.rs index 66875e25242b..6f0455ee98ba 100644 --- a/src/tools/rust-analyzer/lib/line-index/src/lib.rs +++ b/src/tools/rust-analyzer/lib/line-index/src/lib.rs @@ -177,6 +177,14 @@ impl LineIndex { Some(LineCol { line: line_col.line, col }) } + /// Returns the given line's range. + pub fn line(&self, line: u32) -> Option { + let start = self.start_offset(line as usize)?; + let next_newline = self.newlines.get(line as usize).copied().unwrap_or(self.len); + let line_length = next_newline - start; + Some(TextRange::new(start, start + line_length)) + } + /// Given a range [start, end), returns a sorted iterator of non-empty ranges [start, x1), [x1, /// x2), ..., [xn, end) where all the xi, which are positions of newlines, are inside the range /// [start, end). diff --git a/src/tools/rust-analyzer/lib/line-index/src/tests.rs b/src/tools/rust-analyzer/lib/line-index/src/tests.rs index 57fad1dfc057..f2bb04aec323 100644 --- a/src/tools/rust-analyzer/lib/line-index/src/tests.rs +++ b/src/tools/rust-analyzer/lib/line-index/src/tests.rs @@ -195,3 +195,26 @@ fn test_every_chars() { } } } + +#[test] +fn test_line() { + use text_size::TextRange; + + macro_rules! validate { + ($text:expr, $line:expr, $expected_start:literal .. $expected_end:literal) => { + let line_index = LineIndex::new($text); + assert_eq!( + line_index.line($line), + Some(TextRange::new( + TextSize::from($expected_start), + TextSize::from($expected_end) + )) + ); + }; + } + + validate!("", 0, 0..0); + validate!("\n", 1, 1..1); + validate!("\nabc", 1, 1..4); + validate!("\nabc\ndef", 1, 1..5); +} From d11a9702ab560ebd54dca1823d6106e1a8811d84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Ma=C4=87kowski?= Date: Tue, 15 Oct 2024 13:26:09 +0200 Subject: [PATCH 019/366] Add doc(plugins), doc(passes), etc. to INVALID_DOC_ATTRIBUTES --- compiler/rustc_passes/messages.ftl | 13 ++++++++ compiler/rustc_passes/src/check_attr.rs | 26 ++++++++++------ compiler/rustc_passes/src/errors.rs | 21 +++++++++++++ src/librustdoc/core.rs | 39 ++---------------------- tests/rustdoc-ui/deprecated-attrs.rs | 19 +++++++----- tests/rustdoc-ui/deprecated-attrs.stderr | 35 +++++++++++---------- 6 files changed, 84 insertions(+), 69 deletions(-) diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index e5a14f6a1565..cd866edaabdc 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -245,6 +245,19 @@ passes_doc_test_unknown_include = unknown `doc` attribute `{$path}` .suggestion = use `doc = include_str!` instead +passes_doc_test_unknown_passes = + unknown `doc` attribute `{$path}` + .note = `doc` attribute `{$path}` no longer functions; see issue #44136 + .label = no longer functions + .help = you may want to use `doc(document_private_items)` + .no_op_note = `doc({$path})` is now a no-op + +passes_doc_test_unknown_plugins = + unknown `doc` attribute `{$path}` + .note = `doc` attribute `{$path}` no longer functions; see issue #44136 and CVE-2018-1000622 + .label = no longer functions + .no_op_note = `doc({$path})` is now a no-op + passes_doc_test_unknown_spotlight = unknown `doc` attribute `{$path}` .note = `doc(spotlight)` was renamed to `doc(notable_trait)` diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 7ce29260e367..f8cb34f791b8 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1187,15 +1187,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { sym::masked => self.check_doc_masked(attr, meta, hir_id, target), - // no_default_passes: deprecated - // passes: deprecated - // plugins: removed, but rustdoc warns about it itself - sym::cfg - | sym::hidden - | sym::no_default_passes - | sym::notable_trait - | sym::passes - | sym::plugins => {} + sym::cfg | sym::hidden | sym::notable_trait => {} sym::rust_logo => { if self.check_attr_crate_level(attr, meta, hir_id) @@ -1244,6 +1236,22 @@ impl<'tcx> CheckAttrVisitor<'tcx> { sugg: (attr.meta().unwrap().span, applicability), }, ); + } else if i_meta.has_name(sym::passes) + || i_meta.has_name(sym::no_default_passes) + { + self.tcx.emit_node_span_lint( + INVALID_DOC_ATTRIBUTES, + hir_id, + i_meta.span, + errors::DocTestUnknownPasses { path, span: i_meta.span }, + ); + } else if i_meta.has_name(sym::plugins) { + self.tcx.emit_node_span_lint( + INVALID_DOC_ATTRIBUTES, + hir_id, + i_meta.span, + errors::DocTestUnknownPlugins { path, span: i_meta.span }, + ); } else { self.tcx.emit_node_span_lint( INVALID_DOC_ATTRIBUTES, diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 6dc3dfba58f0..630fb80bb7ff 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -317,6 +317,27 @@ pub(crate) struct DocTestUnknownSpotlight { pub span: Span, } +#[derive(LintDiagnostic)] +#[diag(passes_doc_test_unknown_passes)] +#[note] +#[help] +#[note(passes_no_op_note)] +pub(crate) struct DocTestUnknownPasses { + pub path: String, + #[label] + pub span: Span, +} + +#[derive(LintDiagnostic)] +#[diag(passes_doc_test_unknown_plugins)] +#[note] +#[note(passes_no_op_note)] +pub(crate) struct DocTestUnknownPlugins { + pub path: String, + #[label] + pub span: Span, +} + #[derive(LintDiagnostic)] #[diag(passes_doc_test_unknown_include)] pub(crate) struct DocTestUnknownInclude { diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index aaf4c80f9976..63cd055796b0 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -8,7 +8,7 @@ use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; use rustc_errors::emitter::{DynEmitter, HumanEmitter, stderr_destination}; use rustc_errors::json::JsonEmitter; -use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, TerminalUrl}; +use rustc_errors::{ErrorGuaranteed, TerminalUrl}; use rustc_feature::UnstableFeatures; use rustc_hir::def::Res; use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId}; @@ -21,8 +21,8 @@ use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_session::config::{self, CrateType, ErrorOutputType, Input, ResolveDocLinks}; pub(crate) use rustc_session::config::{Options, UnstableOptions}; use rustc_session::{Session, lint}; +use rustc_span::source_map; use rustc_span::symbol::sym; -use rustc_span::{Span, source_map}; use tracing::{debug, info}; use crate::clean::inline::build_external_trait; @@ -380,45 +380,10 @@ pub(crate) fn run_global_ctxt( ); } - fn report_deprecated_attr(name: &str, dcx: DiagCtxtHandle<'_>, sp: Span) { - let mut msg = - dcx.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated")); - msg.note( - "see issue #44136 \ - for more information", - ); - - if name == "no_default_passes" { - msg.help("`#![doc(no_default_passes)]` no longer functions; you may want to use `#![doc(document_private_items)]`"); - } else if name.starts_with("passes") { - msg.help("`#![doc(passes = \"...\")]` no longer functions; you may want to use `#![doc(document_private_items)]`"); - } else if name.starts_with("plugins") { - msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 "); - } - - msg.emit(); - } - // Process all of the crate attributes, extracting plugin metadata along // with the passes which we are supposed to run. for attr in krate.module.attrs.lists(sym::doc) { - let dcx = ctxt.sess().dcx(); - let name = attr.name_or_empty(); - // `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect - if attr.is_word() && name == sym::no_default_passes { - report_deprecated_attr("no_default_passes", dcx, attr.span()); - } else if attr.value_str().is_some() { - match name { - sym::passes => { - report_deprecated_attr("passes = \"...\"", dcx, attr.span()); - } - sym::plugins => { - report_deprecated_attr("plugins = \"...\"", dcx, attr.span()); - } - _ => (), - } - } if attr.is_word() && name == sym::document_private_items { ctxt.render_options.document_private = true; diff --git a/tests/rustdoc-ui/deprecated-attrs.rs b/tests/rustdoc-ui/deprecated-attrs.rs index e4802ee25182..3b59e05a012e 100644 --- a/tests/rustdoc-ui/deprecated-attrs.rs +++ b/tests/rustdoc-ui/deprecated-attrs.rs @@ -1,16 +1,21 @@ -//@ check-pass //@ compile-flags: --passes unknown-pass //@ error-pattern: the `passes` flag no longer functions #![doc(no_default_passes)] -//~^ WARNING attribute is deprecated +//~^ ERROR unknown `doc` attribute `no_default_passes` +//~| NOTE no longer functions //~| NOTE see issue #44136 -//~| HELP no longer functions; you may want to use `#![doc(document_private_items)]` +//~| HELP you may want to use `doc(document_private_items)` +//~| NOTE `doc(no_default_passes)` is now a no-op +//~| NOTE `#[deny(invalid_doc_attributes)]` on by default #![doc(passes = "collapse-docs unindent-comments")] -//~^ WARNING attribute is deprecated +//~^ ERROR unknown `doc` attribute `passes` +//~| NOTE no longer functions //~| NOTE see issue #44136 -//~| HELP no longer functions; you may want to use `#![doc(document_private_items)]` +//~| HELP you may want to use `doc(document_private_items)` +//~| NOTE `doc(passes)` is now a no-op #![doc(plugins = "xxx")] -//~^ WARNING attribute is deprecated +//~^ ERROR unknown `doc` attribute `plugins` //~| NOTE see issue #44136 -//~| WARNING no longer functions; see CVE +//~| NOTE no longer functions +//~| NOTE `doc(plugins)` is now a no-op diff --git a/tests/rustdoc-ui/deprecated-attrs.stderr b/tests/rustdoc-ui/deprecated-attrs.stderr index 45b20ce70ef0..a30523e73297 100644 --- a/tests/rustdoc-ui/deprecated-attrs.stderr +++ b/tests/rustdoc-ui/deprecated-attrs.stderr @@ -3,32 +3,35 @@ warning: the `passes` flag no longer functions = note: see issue #44136 for more information = help: you may want to use --document-private-items -warning: the `#![doc(no_default_passes)]` attribute is deprecated - --> $DIR/deprecated-attrs.rs:5:8 +error: unknown `doc` attribute `no_default_passes` + --> $DIR/deprecated-attrs.rs:4:8 | LL | #![doc(no_default_passes)] - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^ no longer functions | - = note: see issue #44136 for more information - = help: `#![doc(no_default_passes)]` no longer functions; you may want to use `#![doc(document_private_items)]` + = note: `doc` attribute `no_default_passes` no longer functions; see issue #44136 + = help: you may want to use `doc(document_private_items)` + = note: `doc(no_default_passes)` is now a no-op + = note: `#[deny(invalid_doc_attributes)]` on by default -warning: the `#![doc(passes = "...")]` attribute is deprecated - --> $DIR/deprecated-attrs.rs:9:8 +error: unknown `doc` attribute `passes` + --> $DIR/deprecated-attrs.rs:11:8 | LL | #![doc(passes = "collapse-docs unindent-comments")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no longer functions | - = note: see issue #44136 for more information - = help: `#![doc(passes = "...")]` no longer functions; you may want to use `#![doc(document_private_items)]` + = note: `doc` attribute `passes` no longer functions; see issue #44136 + = help: you may want to use `doc(document_private_items)` + = note: `doc(passes)` is now a no-op -warning: the `#![doc(plugins = "...")]` attribute is deprecated - --> $DIR/deprecated-attrs.rs:13:8 +error: unknown `doc` attribute `plugins` + --> $DIR/deprecated-attrs.rs:17:8 | LL | #![doc(plugins = "xxx")] - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ no longer functions | - = note: see issue #44136 for more information - = warning: `#![doc(plugins = "...")]` no longer functions; see CVE-2018-1000622 + = note: `doc` attribute `plugins` no longer functions; see issue #44136 and CVE-2018-1000622 + = note: `doc(plugins)` is now a no-op -warning: 3 warnings emitted +error: aborting due to 3 previous errors From f641c32aad3006d3865a2eb65f60c3c19cf9025e Mon Sep 17 00:00:00 2001 From: Kajetan Puchalski Date: Mon, 14 Oct 2024 16:53:22 +0100 Subject: [PATCH 020/366] rustc_target: Add pauth-lr aarch64 target feature Add the pauth-lr target feature, corresponding to aarch64 FEAT_PAuth_LR. This feature has been added in LLVM 19. It is currently not supported by the Linux hwcap and so we cannot add runtime feature detection for it at this time. --- compiler/rustc_codegen_llvm/src/llvm_util.rs | 1 + compiler/rustc_target/src/target_features.rs | 2 ++ tests/ui/check-cfg/mix.stderr | 2 +- tests/ui/check-cfg/well-known-values.stderr | 2 +- 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 57936215ff13..aa38c02289d1 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -248,6 +248,7 @@ pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option Some(LLVMFeature::new("perfmon")), ("aarch64", "paca") => Some(LLVMFeature::new("pauth")), ("aarch64", "pacg") => Some(LLVMFeature::new("pauth")), + ("aarch64", "pauth-lr") if get_version().0 < 19 => None, // Before LLVM 20 those two features were packaged together as b16b16 ("aarch64", "sve-b16b16") if get_version().0 < 20 => Some(LLVMFeature::new("b16b16")), ("aarch64", "sme-b16b16") if get_version().0 < 20 => Some(LLVMFeature::new("b16b16")), diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index e92366d5c5c3..88de6f8998e4 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -167,6 +167,8 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("pacg", Stable, &[]), // FEAT_PAN ("pan", Stable, &[]), + // FEAT_PAuth_LR + ("pauth-lr", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_PMUv3 ("pmuv3", Stable, &[]), // FEAT_RNG diff --git a/tests/ui/check-cfg/mix.stderr b/tests/ui/check-cfg/mix.stderr index c21016e92909..7589551a87c6 100644 --- a/tests/ui/check-cfg/mix.stderr +++ b/tests/ui/check-cfg/mix.stderr @@ -251,7 +251,7 @@ warning: unexpected `cfg` condition value: `zebra` LL | cfg!(target_feature = "zebra"); | ^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, and `avx512vpopcntdq` and 245 more + = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, and `avx512vpopcntdq` and 246 more = note: see for more information about checking conditional configuration warning: 27 warnings emitted diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr index da790bbd5285..b0ca09a59ed5 100644 --- a/tests/ui/check-cfg/well-known-values.stderr +++ b/tests/ui/check-cfg/well-known-values.stderr @@ -174,7 +174,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` LL | target_feature = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `avxifma`, `avxneconvert`, `avxvnni`, `avxvnniint16`, `avxvnniint8`, `backchain`, `bf16`, `bmi1`, `bmi2`, `bti`, `bulk-memory`, `c`, `cache`, `cmpxchg16b`, `crc`, `crt-static`, `cssc`, `d`, `d32`, `dit`, `doloop`, `dotprod`, `dpb`, `dpb2`, `dsp`, `dsp1e2`, `dspe60`, `e`, `e1`, `e2`, `ecv`, `edsp`, `elrw`, `ermsb`, `exception-handling`, `extended-const`, `f`, `f16c`, `f32mm`, `f64mm`, `faminmax`, `fcma`, `fdivdu`, `fhm`, `flagm`, `flagm2`, `float1e2`, `float1e3`, `float3e4`, `float7e60`, `floate1`, `fma`, `fp-armv8`, `fp16`, `fp64`, `fp8`, `fp8dot2`, `fp8dot4`, `fp8fma`, `fpuv2_df`, `fpuv2_sf`, `fpuv3_df`, `fpuv3_hf`, `fpuv3_hi`, `fpuv3_sf`, `frecipe`, `frintts`, `fxsr`, `gfni`, `hard-float`, `hard-float-abi`, `hard-tp`, `hbc`, `high-registers`, `hvx`, `hvx-length128b`, `hwdiv`, `i8mm`, `jsconv`, `lahfsahf`, `lasx`, `lbt`, `lor`, `lse`, `lse128`, `lse2`, `lsx`, `lut`, `lvz`, `lzcnt`, `m`, `mclass`, `mops`, `movbe`, `mp`, `mp1e2`, `msa`, `mte`, `multivalue`, `mutable-globals`, `neon`, `nontrapping-fptoint`, `nvic`, `paca`, `pacg`, `pan`, `partword-atomics`, `pclmulqdq`, `pmuv3`, `popcnt`, `power10-vector`, `power8-altivec`, `power8-vector`, `power9-altivec`, `power9-vector`, `prfchw`, `quadword-atomics`, `rand`, `ras`, `rclass`, `rcpc`, `rcpc2`, `rcpc3`, `rdm`, `rdrand`, `rdseed`, `reference-types`, `relax`, `relaxed-simd`, `rtm`, `sb`, `sha`, `sha2`, `sha3`, `sha512`, `sign-ext`, `simd128`, `sm3`, `sm4`, `sme`, `sme-b16b16`, `sme-f16f16`, `sme-f64f64`, `sme-f8f16`, `sme-f8f32`, `sme-fa64`, `sme-i16i64`, `sme-lutv2`, `sme2`, `sme2p1`, `spe`, `ssbs`, `sse`, `sse2`, `sse3`, `sse4.1`, `sse4.2`, `sse4a`, `ssse3`, `ssve-fp8dot2`, `ssve-fp8dot4`, `ssve-fp8fma`, `sve`, `sve-b16b16`, `sve2`, `sve2-aes`, `sve2-bitperm`, `sve2-sha3`, `sve2-sm4`, `sve2p1`, `tbm`, `thumb-mode`, `thumb2`, `tme`, `trust`, `trustzone`, `ual`, `unaligned-scalar-mem`, `v`, `v5te`, `v6`, `v6k`, `v6t2`, `v7`, `v8`, `v8.1a`, `v8.2a`, `v8.3a`, `v8.4a`, `v8.5a`, `v8.6a`, `v8.7a`, `v8.8a`, `v8.9a`, `v9.1a`, `v9.2a`, `v9.3a`, `v9.4a`, `v9.5a`, `v9a`, `vaes`, `vdsp2e60f`, `vdspv1`, `vdspv2`, `vector`, `vfp2`, `vfp3`, `vfp4`, `vh`, `virt`, `virtualization`, `vpclmulqdq`, `vsx`, `wfxt`, `xop`, `xsave`, `xsavec`, `xsaveopt`, `xsaves`, `zaamo`, `zabha`, `zalrsc`, `zba`, `zbb`, `zbc`, `zbkb`, `zbkc`, `zbkx`, `zbs`, `zdinx`, `zfh`, `zfhmin`, `zfinx`, `zhinx`, `zhinxmin`, `zk`, `zkn`, `zknd`, `zkne`, `zknh`, `zkr`, `zks`, `zksed`, `zksh`, and `zkt` + = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `avxifma`, `avxneconvert`, `avxvnni`, `avxvnniint16`, `avxvnniint8`, `backchain`, `bf16`, `bmi1`, `bmi2`, `bti`, `bulk-memory`, `c`, `cache`, `cmpxchg16b`, `crc`, `crt-static`, `cssc`, `d`, `d32`, `dit`, `doloop`, `dotprod`, `dpb`, `dpb2`, `dsp`, `dsp1e2`, `dspe60`, `e`, `e1`, `e2`, `ecv`, `edsp`, `elrw`, `ermsb`, `exception-handling`, `extended-const`, `f`, `f16c`, `f32mm`, `f64mm`, `faminmax`, `fcma`, `fdivdu`, `fhm`, `flagm`, `flagm2`, `float1e2`, `float1e3`, `float3e4`, `float7e60`, `floate1`, `fma`, `fp-armv8`, `fp16`, `fp64`, `fp8`, `fp8dot2`, `fp8dot4`, `fp8fma`, `fpuv2_df`, `fpuv2_sf`, `fpuv3_df`, `fpuv3_hf`, `fpuv3_hi`, `fpuv3_sf`, `frecipe`, `frintts`, `fxsr`, `gfni`, `hard-float`, `hard-float-abi`, `hard-tp`, `hbc`, `high-registers`, `hvx`, `hvx-length128b`, `hwdiv`, `i8mm`, `jsconv`, `lahfsahf`, `lasx`, `lbt`, `lor`, `lse`, `lse128`, `lse2`, `lsx`, `lut`, `lvz`, `lzcnt`, `m`, `mclass`, `mops`, `movbe`, `mp`, `mp1e2`, `msa`, `mte`, `multivalue`, `mutable-globals`, `neon`, `nontrapping-fptoint`, `nvic`, `paca`, `pacg`, `pan`, `partword-atomics`, `pauth-lr`, `pclmulqdq`, `pmuv3`, `popcnt`, `power10-vector`, `power8-altivec`, `power8-vector`, `power9-altivec`, `power9-vector`, `prfchw`, `quadword-atomics`, `rand`, `ras`, `rclass`, `rcpc`, `rcpc2`, `rcpc3`, `rdm`, `rdrand`, `rdseed`, `reference-types`, `relax`, `relaxed-simd`, `rtm`, `sb`, `sha`, `sha2`, `sha3`, `sha512`, `sign-ext`, `simd128`, `sm3`, `sm4`, `sme`, `sme-b16b16`, `sme-f16f16`, `sme-f64f64`, `sme-f8f16`, `sme-f8f32`, `sme-fa64`, `sme-i16i64`, `sme-lutv2`, `sme2`, `sme2p1`, `spe`, `ssbs`, `sse`, `sse2`, `sse3`, `sse4.1`, `sse4.2`, `sse4a`, `ssse3`, `ssve-fp8dot2`, `ssve-fp8dot4`, `ssve-fp8fma`, `sve`, `sve-b16b16`, `sve2`, `sve2-aes`, `sve2-bitperm`, `sve2-sha3`, `sve2-sm4`, `sve2p1`, `tbm`, `thumb-mode`, `thumb2`, `tme`, `trust`, `trustzone`, `ual`, `unaligned-scalar-mem`, `v`, `v5te`, `v6`, `v6k`, `v6t2`, `v7`, `v8`, `v8.1a`, `v8.2a`, `v8.3a`, `v8.4a`, `v8.5a`, `v8.6a`, `v8.7a`, `v8.8a`, `v8.9a`, `v9.1a`, `v9.2a`, `v9.3a`, `v9.4a`, `v9.5a`, `v9a`, `vaes`, `vdsp2e60f`, `vdspv1`, `vdspv2`, `vector`, `vfp2`, `vfp3`, `vfp4`, `vh`, `virt`, `virtualization`, `vpclmulqdq`, `vsx`, `wfxt`, `xop`, `xsave`, `xsavec`, `xsaveopt`, `xsaves`, `zaamo`, `zabha`, `zalrsc`, `zba`, `zbb`, `zbc`, `zbkb`, `zbkc`, `zbkx`, `zbs`, `zdinx`, `zfh`, `zfhmin`, `zfinx`, `zhinx`, `zhinxmin`, `zk`, `zkn`, `zknd`, `zkne`, `zknh`, `zkr`, `zks`, `zksed`, `zksh`, and `zkt` = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` From 3ea91c05db131ec7c4bd6d507b569a58cd19dd93 Mon Sep 17 00:00:00 2001 From: beetrees Date: Thu, 17 Oct 2024 01:13:17 +0100 Subject: [PATCH 021/366] Always specify `llvm_abiname` for RISC-V targets --- .../spec/targets/riscv32i_unknown_none_elf.rs | 1 + .../spec/targets/riscv32im_risc0_zkvm_elf.rs | 1 + .../targets/riscv32im_unknown_none_elf.rs | 1 + .../targets/riscv32ima_unknown_none_elf.rs | 1 + .../spec/targets/riscv32imac_esp_espidf.rs | 1 + .../targets/riscv32imac_unknown_none_elf.rs | 1 + .../targets/riscv32imac_unknown_nuttx_elf.rs | 1 + .../targets/riscv32imac_unknown_xous_elf.rs | 1 + .../src/spec/targets/riscv32imc_esp_espidf.rs | 1 + .../targets/riscv32imc_unknown_none_elf.rs | 1 + .../targets/riscv32imc_unknown_nuttx_elf.rs | 1 + .../targets/riscv64imac_unknown_none_elf.rs | 1 + .../targets/riscv64imac_unknown_nuttx_elf.rs | 1 + .../rustc_target/src/spec/tests/tests_impl.rs | 11 +++++ .../riscv-soft-abi-with-float-features.rs | 46 +++++++++++++++++++ tests/codegen/riscv-target-abi.rs | 2 +- 16 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 tests/assembly/riscv-soft-abi-with-float-features.rs diff --git a/compiler/rustc_target/src/spec/targets/riscv32i_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32i_unknown_none_elf.rs index 1995de9dd2d7..0e0e13fd1d8e 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32i_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32i_unknown_none_elf.rs @@ -20,6 +20,7 @@ pub(crate) fn target() -> Target { max_atomic_width: Some(32), atomic_cas: false, features: "+forced-atomics".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs index bd37cf80b483..669c1702fda8 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs @@ -29,6 +29,7 @@ pub(crate) fn target() -> Target { atomic_cas: true, features: "+m".into(), + llvm_abiname: "ilp32".into(), executables: true, panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/targets/riscv32im_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32im_unknown_none_elf.rs index 32df30ddb5e3..477a6c0e9eb9 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32im_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32im_unknown_none_elf.rs @@ -20,6 +20,7 @@ pub(crate) fn target() -> Target { max_atomic_width: Some(32), atomic_cas: false, features: "+m,+forced-atomics".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32ima_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32ima_unknown_none_elf.rs index 61c887031bcf..68146788d207 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32ima_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32ima_unknown_none_elf.rs @@ -19,6 +19,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv32".into(), max_atomic_width: Some(32), features: "+m,+a".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs b/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs index 9795af565694..e12c3af6f8f3 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs @@ -27,6 +27,7 @@ pub(crate) fn target() -> Target { atomic_cas: true, features: "+m,+a,+c".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_none_elf.rs index cc28198e3ff0..adc76f3cdb58 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_none_elf.rs @@ -19,6 +19,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv32".into(), max_atomic_width: Some(32), features: "+m,+a,+c".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs index 62397dcae9a1..31c9180c509c 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs @@ -21,6 +21,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv32".into(), max_atomic_width: Some(32), features: "+m,+a,+c".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Unwind, relocation_model: RelocModel::Static, ..Default::default() diff --git a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_xous_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_xous_elf.rs index 0eaabc60cbcd..88d112a012d0 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_xous_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_xous_elf.rs @@ -20,6 +20,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv32".into(), max_atomic_width: Some(32), features: "+m,+a,+c".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Unwind, relocation_model: RelocModel::Static, ..Default::default() diff --git a/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs b/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs index 9ae84ace457d..cec97f865389 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs @@ -30,6 +30,7 @@ pub(crate) fn target() -> Target { atomic_cas: true, features: "+m,+c".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_none_elf.rs index 0ae49debc3a3..0e00fc69b41a 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_none_elf.rs @@ -20,6 +20,7 @@ pub(crate) fn target() -> Target { max_atomic_width: Some(32), atomic_cas: false, features: "+m,+c,+forced-atomics".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, diff --git a/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs index 5f3917edf701..e86549806ddb 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs @@ -21,6 +21,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv32".into(), max_atomic_width: Some(32), features: "+m,+c".into(), + llvm_abiname: "ilp32".into(), panic_strategy: PanicStrategy::Unwind, relocation_model: RelocModel::Static, ..Default::default() diff --git a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs index d514f8efcd08..d62ecc07a5d4 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs @@ -22,6 +22,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv64".into(), max_atomic_width: Some(64), features: "+m,+a,+c".into(), + llvm_abiname: "lp64".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, code_model: Some(CodeModel::Medium), diff --git a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs index a737e46de1ba..9c1816655811 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs @@ -24,6 +24,7 @@ pub(crate) fn target() -> Target { cpu: "generic-rv64".into(), max_atomic_width: Some(64), features: "+m,+a,+c".into(), + llvm_abiname: "lp64".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, code_model: Some(CodeModel::Medium), diff --git a/compiler/rustc_target/src/spec/tests/tests_impl.rs b/compiler/rustc_target/src/spec/tests/tests_impl.rs index fc5bd846e024..7ed21954fba0 100644 --- a/compiler/rustc_target/src/spec/tests/tests_impl.rs +++ b/compiler/rustc_target/src/spec/tests/tests_impl.rs @@ -152,6 +152,17 @@ impl Target { if self.crt_static_default || self.crt_static_allows_dylibs { assert!(self.crt_static_respected); } + + // Check that RISC-V targets always specify which ABI they use. + match &*self.arch { + "riscv32" => { + assert_matches!(&*self.llvm_abiname, "ilp32" | "ilp32f" | "ilp32d" | "ilp32e") + } + "riscv64" => { + assert_matches!(&*self.llvm_abiname, "lp64" | "lp64f" | "lp64d" | "lp64q") + } + _ => {} + } } // Add your target to the whitelist if it has `std` library diff --git a/tests/assembly/riscv-soft-abi-with-float-features.rs b/tests/assembly/riscv-soft-abi-with-float-features.rs new file mode 100644 index 000000000000..733137f57009 --- /dev/null +++ b/tests/assembly/riscv-soft-abi-with-float-features.rs @@ -0,0 +1,46 @@ +//@ assembly-output: emit-asm +//@ compile-flags: --target riscv64imac-unknown-none-elf -Ctarget-feature=+f,+d +//@ needs-llvm-components: riscv + +#![feature(no_core, lang_items, f16)] +#![crate_type = "lib"] +#![no_core] + +#[lang = "sized"] +trait Sized {} + +#[lang = "copy"] +trait Copy {} + +impl Copy for f16 {} +impl Copy for f32 {} +impl Copy for f64 {} + +// This test checks that the floats are all returned in `a0` as required by the `lp64` ABI. + +// CHECK-LABEL: read_f16 +#[no_mangle] +pub extern "C" fn read_f16(x: &f16) -> f16 { + // CHECK: lh a0, 0(a0) + // CHECK-NEXT: lui a1, 1048560 + // CHECK-NEXT: or a0, a0, a1 + // CHECK-NEXT: ret + *x +} + +// CHECK-LABEL: read_f32 +#[no_mangle] +pub extern "C" fn read_f32(x: &f32) -> f32 { + // CHECK: flw fa5, 0(a0) + // CHECK-NEXT: fmv.x.w a0, fa5 + // CHECK-NEXT: ret + *x +} + +// CHECK-LABEL: read_f64 +#[no_mangle] +pub extern "C" fn read_f64(x: &f64) -> f64 { + // CHECK: ld a0, 0(a0) + // CHECK-NEXT: ret + *x +} diff --git a/tests/codegen/riscv-target-abi.rs b/tests/codegen/riscv-target-abi.rs index 5d545af9c769..88da4ece7ba3 100644 --- a/tests/codegen/riscv-target-abi.rs +++ b/tests/codegen/riscv-target-abi.rs @@ -10,7 +10,7 @@ //@[riscv32imac] compile-flags: --target=riscv32imac-unknown-none-elf //@[riscv32imac] needs-llvm-components: riscv -// riscv32imac-NOT: !"target-abi" +// riscv32imac: !{i32 1, !"target-abi", !"ilp32"} #![feature(no_core, lang_items)] #![crate_type = "lib"] From 7c2373e89706c6f08f1b594785973d127d250597 Mon Sep 17 00:00:00 2001 From: Giga Bowser <45986823+Giga-Bowser@users.noreply.github.com> Date: Thu, 17 Oct 2024 10:04:28 -0400 Subject: [PATCH 022/366] Re-use code for wrapping/unwrapping return types --- .../src/handlers/unwrap_option_return_type.rs | 1143 --------- .../src/handlers/unwrap_result_return_type.rs | 1115 --------- .../src/handlers/unwrap_return_type.rs | 2159 +++++++++++++++++ ..._type_in_result.rs => wrap_return_type.rs} | 1187 ++++++++- .../handlers/wrap_return_type_in_option.rs | 1173 --------- .../crates/ide-assists/src/lib.rs | 14 +- 6 files changed, 3304 insertions(+), 3487 deletions(-) delete mode 100644 src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs delete mode 100644 src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_result_return_type.rs create mode 100644 src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs rename src/tools/rust-analyzer/crates/ide-assists/src/handlers/{wrap_return_type_in_result.rs => wrap_return_type.rs} (51%) delete mode 100644 src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs deleted file mode 100644 index 8dc40842406b..000000000000 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_option_return_type.rs +++ /dev/null @@ -1,1143 +0,0 @@ -use ide_db::{ - famous_defs::FamousDefs, - syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, -}; -use itertools::Itertools; -use syntax::{ - ast::{self, Expr, HasGenericArgs}, - match_ast, AstNode, NodeOrToken, SyntaxKind, TextRange, -}; - -use crate::{AssistContext, AssistId, AssistKind, Assists}; - -// Assist: unwrap_option_return_type -// -// Unwrap the function's return type. -// -// ``` -// # //- minicore: option -// fn foo() -> Option$0 { Some(42i32) } -// ``` -// -> -// ``` -// fn foo() -> i32 { 42i32 } -// ``` -pub(crate) fn unwrap_option_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - let ret_type = ctx.find_node_at_offset::()?; - let parent = ret_type.syntax().parent()?; - let body = match_ast! { - match parent { - ast::Fn(func) => func.body()?, - ast::ClosureExpr(closure) => match closure.body()? { - Expr::BlockExpr(block) => block, - // closures require a block when a return type is specified - _ => return None, - }, - _ => return None, - } - }; - - let type_ref = &ret_type.ty()?; - let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else { - return None; - }; - let option_enum = - FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_option_Option()?; - if ret_enum != option_enum { - return None; - } - - let ok_type = unwrap_option_type(type_ref)?; - - acc.add( - AssistId("unwrap_option_return_type", AssistKind::RefactorRewrite), - "Unwrap Option return type", - type_ref.syntax().text_range(), - |builder| { - let body = ast::Expr::BlockExpr(body); - - let mut exprs_to_unwrap = Vec::new(); - let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); - walk_expr(&body, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } - } - }); - for_each_tail_expr(&body, tail_cb); - - let is_unit_type = is_unit_type(&ok_type); - if is_unit_type { - let mut text_range = ret_type.syntax().text_range(); - - if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() { - if token.kind() == SyntaxKind::WHITESPACE { - text_range = TextRange::new(text_range.start(), token.text_range().end()); - } - } - - builder.delete(text_range); - } else { - builder.replace(type_ref.syntax().text_range(), ok_type.syntax().text()); - } - - for ret_expr_arg in exprs_to_unwrap { - let ret_expr_str = ret_expr_arg.to_string(); - if ret_expr_str.starts_with("Some(") { - let arg_list = ret_expr_arg.syntax().children().find_map(ast::ArgList::cast); - if let Some(arg_list) = arg_list { - if is_unit_type { - match ret_expr_arg.syntax().prev_sibling_or_token() { - // Useful to delete the entire line without leaving trailing whitespaces - Some(whitespace) => { - let new_range = TextRange::new( - whitespace.text_range().start(), - ret_expr_arg.syntax().text_range().end(), - ); - builder.delete(new_range); - } - None => { - builder.delete(ret_expr_arg.syntax().text_range()); - } - } - } else { - builder.replace( - ret_expr_arg.syntax().text_range(), - arg_list.args().join(", "), - ); - } - } - } else if ret_expr_str == "None" { - builder.replace(ret_expr_arg.syntax().text_range(), "()"); - } - } - }, - ) -} - -fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { - match e { - Expr::BreakExpr(break_expr) => { - if let Some(break_expr_arg) = break_expr.expr() { - for_each_tail_expr(&break_expr_arg, &mut |e| tail_cb_impl(acc, e)) - } - } - Expr::ReturnExpr(_) => { - // all return expressions have already been handled by the walk loop - } - e => acc.push(e.clone()), - } -} - -// Tries to extract `T` from `Option`. -fn unwrap_option_type(ty: &ast::Type) -> Option { - let ast::Type::PathType(path_ty) = ty else { - return None; - }; - let path = path_ty.path()?; - let segment = path.first_segment()?; - let generic_arg_list = segment.generic_arg_list()?; - let generic_args: Vec<_> = generic_arg_list.generic_args().collect(); - let ast::GenericArg::TypeArg(some_type) = generic_args.first()? else { - return None; - }; - some_type.ty() -} - -fn is_unit_type(ty: &ast::Type) -> bool { - let ast::Type::TupleType(tuple) = ty else { return false }; - tuple.fields().next().is_none() -} - -#[cfg(test)] -mod tests { - use crate::tests::{check_assist, check_assist_not_applicable}; - - use super::*; - - #[test] - fn unwrap_option_return_type_simple() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let test = "test"; - return Some(42i32); -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - return 42i32; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_unit_type() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option<()$0> { - Some(()) -} -"#, - r#" -fn foo() { -} -"#, - ); - - // Unformatted return type - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option<()$0>{ - Some(()) -} -"#, - r#" -fn foo() { -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_none() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - if true { - Some(42) - } else { - None - } -} -"#, - r#" -fn foo() -> i32 { - if true { - 42 - } else { - () - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_ending_with_parent() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - if true { - Some(42) - } else { - foo() - } -} -"#, - r#" -fn foo() -> i32 { - if true { - 42 - } else { - foo() - } -} -"#, - ); - } - - #[test] - fn unwrap_return_type_break_split_tail() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - loop { - break if true { - Some(1) - } else { - Some(0) - }; - } -} -"#, - r#" -fn foo() -> i32 { - loop { - break if true { - 1 - } else { - 0 - }; - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_closure() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() { - || -> Option { - let test = "test"; - return Some(42i32); - }; -} -"#, - r#" -fn foo() { - || -> i32 { - let test = "test"; - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_return_type_bad_cursor() { - check_assist_not_applicable( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> i32 { - let test = "test";$0 - return 42i32; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() { - || -> i32 { - let test = "test";$0 - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_closure_non_block() { - check_assist_not_applicable( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() { || -> i$032 3; } -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_return_type_already_not_option_std() { - check_assist_not_applicable( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> i32$0 { - let test = "test"; - return 42i32; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_return_type_already_not_option_closure() { - check_assist_not_applicable( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() { - || -> i32$0 { - let test = "test"; - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() ->$0 Option { - let test = "test"; - Some(42i32) -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - 42i32 -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_closure() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() { - || ->$0 Option { - let test = "test"; - Some(42i32) - }; -} -"#, - r#" -fn foo() { - || -> i32 { - let test = "test"; - 42i32 - }; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_only() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { Some(42i32) } -"#, - r#" -fn foo() -> i32 { 42i32 } -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_block_like() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option$0 { - if true { - Some(42i32) - } else { - Some(24i32) - } -} -"#, - r#" -fn foo() -> i32 { - if true { - 42i32 - } else { - 24i32 - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_without_block_closure() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() { - || -> Option$0 { - if true { - Some(42i32) - } else { - Some(24i32) - } - }; -} -"#, - r#" -fn foo() { - || -> i32 { - if true { - 42i32 - } else { - 24i32 - } - }; -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_nested_if() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option$0 { - if true { - if false { - Some(1) - } else { - Some(2) - } - } else { - Some(24i32) - } -} -"#, - r#" -fn foo() -> i32 { - if true { - if false { - 1 - } else { - 2 - } - } else { - 24i32 - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_await() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -async fn foo() -> Option { - if true { - if false { - Some(1.await) - } else { - Some(2.await) - } - } else { - Some(24i32.await) - } -} -"#, - r#" -async fn foo() -> i32 { - if true { - if false { - 1.await - } else { - 2.await - } - } else { - 24i32.await - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_array() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option<[i32; 3]$0> { Some([1, 2, 3]) } -"#, - r#" -fn foo() -> [i32; 3] { [1, 2, 3] } -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_cast() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -$0> Option { - if true { - if false { - Some(1 as i32) - } else { - Some(2 as i32) - } - } else { - Some(24 as i32) - } -} -"#, - r#" -fn foo() -> i32 { - if true { - if false { - 1 as i32 - } else { - 2 as i32 - } - } else { - 24 as i32 - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_block_like_match() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let my_var = 5; - match my_var { - 5 => Some(42i32), - _ => Some(24i32), - } -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - match my_var { - 5 => 42i32, - _ => 24i32, - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_loop_with_tail() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let my_var = 5; - loop { - println!("test"); - 5 - } - Some(my_var) -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - loop { - println!("test"); - 5 - } - my_var -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_loop_in_let_stmt() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let my_var = let x = loop { - break 1; - }; - Some(my_var) -} -"#, - r#" -fn foo() -> i32 { - let my_var = let x = loop { - break 1; - }; - my_var -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_block_like_match_return_expr() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option$0 { - let my_var = 5; - let res = match my_var { - 5 => 42i32, - _ => return Some(24i32), - }; - Some(res) -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - let res = match my_var { - 5 => 42i32, - _ => return 24i32, - }; - res -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let my_var = 5; - let res = if my_var == 5 { - 42i32 - } else { - return Some(24i32); - }; - Some(res) -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - let res = if my_var == 5 { - 42i32 - } else { - return 24i32; - }; - res -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_block_like_match_deeper() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let my_var = 5; - match my_var { - 5 => { - if true { - Some(42i32) - } else { - Some(25i32) - } - }, - _ => { - let test = "test"; - if test == "test" { - return Some(bar()); - } - Some(53i32) - }, - } -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - match my_var { - 5 => { - if true { - 42i32 - } else { - 25i32 - } - }, - _ => { - let test = "test"; - if test == "test" { - return bar(); - } - 53i32 - }, - } -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_tail_block_like_early_return() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let test = "test"; - if test == "test" { - return Some(24i32); - } - Some(53i32) -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - if test == "test" { - return 24i32; - } - 53i32 -} -"#, - ); - } - - #[test] - fn wrap_return_in_tail_position() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(num: i32) -> $0Option { - return Some(num) -} -"#, - r#" -fn foo(num: i32) -> i32 { - return num -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_closure() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(the_field: u32) -> Option { - let true_closure = || { return true; }; - if the_field < 5 { - let mut i = 0; - if true_closure() { - return Some(99); - } else { - return Some(0); - } - } - Some(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - let true_closure = || { return true; }; - if the_field < 5 { - let mut i = 0; - if true_closure() { - return 99; - } else { - return 0; - } - } - the_field -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(the_field: u32) -> Option { - let true_closure = || { - return true; - }; - if the_field < 5 { - let mut i = 0; - - - if true_closure() { - return Some(99); - } else { - return Some(0); - } - } - let t = None; - - Some(t.unwrap_or_else(|| the_field)) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - let true_closure = || { - return true; - }; - if the_field < 5 { - let mut i = 0; - - - if true_closure() { - return 99; - } else { - return 0; - } - } - let t = None; - - t.unwrap_or_else(|| the_field) -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_simple_with_weird_forms() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo() -> Option { - let test = "test"; - if test == "test" { - return Some(24i32); - } - let mut i = 0; - loop { - if i == 1 { - break Some(55); - } - i += 1; - } -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - if test == "test" { - return 24i32; - } - let mut i = 0; - loop { - if i == 1 { - break 55; - } - i += 1; - } -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - loop { - if i > 5 { - return Some(55u32); - } - i += 3; - } - match i { - 5 => return Some(99), - _ => return Some(0), - }; - } - Some(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - loop { - if i > 5 { - return 55u32; - } - i += 3; - } - match i { - 5 => return 99, - _ => return 0, - }; - } - the_field -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - match i { - 5 => return Some(99), - _ => return Some(0), - } - } - Some(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - match i { - 5 => return 99, - _ => return 0, - } - } - the_field -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return Some(99) - } else { - return Some(0) - } - } - Some(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return 99 - } else { - return 0 - } - } - the_field -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return Some(99); - } else { - return Some(0); - } - } - Some(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return 99; - } else { - return 0; - } - } - the_field -} -"#, - ); - } - - #[test] - fn unwrap_option_return_type_nested_type() { - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option, result -fn foo() -> Option> { - Some(Ok(42)) -} -"#, - r#" -fn foo() -> Result { - Ok(42) -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option, result -fn foo() -> Option, ()>> { - Some(Err()) -} -"#, - r#" -fn foo() -> Result, ()> { - Err() -} -"#, - ); - - check_assist( - unwrap_option_return_type, - r#" -//- minicore: option, result, iterators -fn foo() -> Option$0> { - Some(Some(42).into_iter()) -} -"#, - r#" -fn foo() -> impl Iterator { - Some(42).into_iter() -} -"#, - ); - } -} diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_result_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_result_return_type.rs deleted file mode 100644 index a1987247cb63..000000000000 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_result_return_type.rs +++ /dev/null @@ -1,1115 +0,0 @@ -use ide_db::{ - famous_defs::FamousDefs, - syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, -}; -use itertools::Itertools; -use syntax::{ - ast::{self, Expr, HasGenericArgs}, - match_ast, AstNode, NodeOrToken, SyntaxKind, TextRange, -}; - -use crate::{AssistContext, AssistId, AssistKind, Assists}; - -// Assist: unwrap_result_return_type -// -// Unwrap the function's return type. -// -// ``` -// # //- minicore: result -// fn foo() -> Result$0 { Ok(42i32) } -// ``` -// -> -// ``` -// fn foo() -> i32 { 42i32 } -// ``` -pub(crate) fn unwrap_result_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - let ret_type = ctx.find_node_at_offset::()?; - let parent = ret_type.syntax().parent()?; - let body = match_ast! { - match parent { - ast::Fn(func) => func.body()?, - ast::ClosureExpr(closure) => match closure.body()? { - Expr::BlockExpr(block) => block, - // closures require a block when a return type is specified - _ => return None, - }, - _ => return None, - } - }; - - let type_ref = &ret_type.ty()?; - let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else { - return None; - }; - let result_enum = - FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_result_Result()?; - if ret_enum != result_enum { - return None; - } - - let ok_type = unwrap_result_type(type_ref)?; - - acc.add( - AssistId("unwrap_result_return_type", AssistKind::RefactorRewrite), - "Unwrap Result return type", - type_ref.syntax().text_range(), - |builder| { - let body = ast::Expr::BlockExpr(body); - - let mut exprs_to_unwrap = Vec::new(); - let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); - walk_expr(&body, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } - } - }); - for_each_tail_expr(&body, tail_cb); - - let is_unit_type = is_unit_type(&ok_type); - if is_unit_type { - let mut text_range = ret_type.syntax().text_range(); - - if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() { - if token.kind() == SyntaxKind::WHITESPACE { - text_range = TextRange::new(text_range.start(), token.text_range().end()); - } - } - - builder.delete(text_range); - } else { - builder.replace(type_ref.syntax().text_range(), ok_type.syntax().text()); - } - - for ret_expr_arg in exprs_to_unwrap { - let ret_expr_str = ret_expr_arg.to_string(); - if ret_expr_str.starts_with("Ok(") || ret_expr_str.starts_with("Err(") { - let arg_list = ret_expr_arg.syntax().children().find_map(ast::ArgList::cast); - if let Some(arg_list) = arg_list { - if is_unit_type { - match ret_expr_arg.syntax().prev_sibling_or_token() { - // Useful to delete the entire line without leaving trailing whitespaces - Some(whitespace) => { - let new_range = TextRange::new( - whitespace.text_range().start(), - ret_expr_arg.syntax().text_range().end(), - ); - builder.delete(new_range); - } - None => { - builder.delete(ret_expr_arg.syntax().text_range()); - } - } - } else { - builder.replace( - ret_expr_arg.syntax().text_range(), - arg_list.args().join(", "), - ); - } - } - } - } - }, - ) -} - -fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { - match e { - Expr::BreakExpr(break_expr) => { - if let Some(break_expr_arg) = break_expr.expr() { - for_each_tail_expr(&break_expr_arg, &mut |e| tail_cb_impl(acc, e)) - } - } - Expr::ReturnExpr(_) => { - // all return expressions have already been handled by the walk loop - } - e => acc.push(e.clone()), - } -} - -// Tries to extract `T` from `Result`. -fn unwrap_result_type(ty: &ast::Type) -> Option { - let ast::Type::PathType(path_ty) = ty else { - return None; - }; - let path = path_ty.path()?; - let segment = path.first_segment()?; - let generic_arg_list = segment.generic_arg_list()?; - let generic_args: Vec<_> = generic_arg_list.generic_args().collect(); - let ast::GenericArg::TypeArg(ok_type) = generic_args.first()? else { - return None; - }; - ok_type.ty() -} - -fn is_unit_type(ty: &ast::Type) -> bool { - let ast::Type::TupleType(tuple) = ty else { return false }; - tuple.fields().next().is_none() -} - -#[cfg(test)] -mod tests { - use crate::tests::{check_assist, check_assist_not_applicable}; - - use super::*; - - #[test] - fn unwrap_result_return_type_simple() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let test = "test"; - return Ok(42i32); -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - return 42i32; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_unit_type() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result<(), Box> { - Ok(()) -} -"#, - r#" -fn foo() { -} -"#, - ); - - // Unformatted return type - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result<(), Box>{ - Ok(()) -} -"#, - r#" -fn foo() { -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_ending_with_parent() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result> { - if true { - Ok(42) - } else { - foo() - } -} -"#, - r#" -fn foo() -> i32 { - if true { - 42 - } else { - foo() - } -} -"#, - ); - } - - #[test] - fn unwrap_return_type_break_split_tail() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - loop { - break if true { - Ok(1) - } else { - Ok(0) - }; - } -} -"#, - r#" -fn foo() -> i32 { - loop { - break if true { - 1 - } else { - 0 - }; - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_closure() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() { - || -> Result { - let test = "test"; - return Ok(42i32); - }; -} -"#, - r#" -fn foo() { - || -> i32 { - let test = "test"; - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_return_type_bad_cursor() { - check_assist_not_applicable( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> i32 { - let test = "test";$0 - return 42i32; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() { - || -> i32 { - let test = "test";$0 - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_closure_non_block() { - check_assist_not_applicable( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() { || -> i$032 3; } -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_return_type_already_not_result_std() { - check_assist_not_applicable( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> i32$0 { - let test = "test"; - return 42i32; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_return_type_already_not_result_closure() { - check_assist_not_applicable( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() { - || -> i32$0 { - let test = "test"; - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() ->$0 Result { - let test = "test"; - Ok(42i32) -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - 42i32 -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_closure() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() { - || ->$0 Result { - let test = "test"; - Ok(42i32) - }; -} -"#, - r#" -fn foo() { - || -> i32 { - let test = "test"; - 42i32 - }; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_only() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { Ok(42i32) } -"#, - r#" -fn foo() -> i32 { 42i32 } -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_block_like() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result$0 { - if true { - Ok(42i32) - } else { - Ok(24i32) - } -} -"#, - r#" -fn foo() -> i32 { - if true { - 42i32 - } else { - 24i32 - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_without_block_closure() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() { - || -> Result$0 { - if true { - Ok(42i32) - } else { - Ok(24i32) - } - }; -} -"#, - r#" -fn foo() { - || -> i32 { - if true { - 42i32 - } else { - 24i32 - } - }; -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_nested_if() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result$0 { - if true { - if false { - Ok(1) - } else { - Ok(2) - } - } else { - Ok(24i32) - } -} -"#, - r#" -fn foo() -> i32 { - if true { - if false { - 1 - } else { - 2 - } - } else { - 24i32 - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_await() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -async fn foo() -> Result { - if true { - if false { - Ok(1.await) - } else { - Ok(2.await) - } - } else { - Ok(24i32.await) - } -} -"#, - r#" -async fn foo() -> i32 { - if true { - if false { - 1.await - } else { - 2.await - } - } else { - 24i32.await - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_array() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result<[i32; 3]$0> { Ok([1, 2, 3]) } -"#, - r#" -fn foo() -> [i32; 3] { [1, 2, 3] } -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_cast() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -$0> Result { - if true { - if false { - Ok(1 as i32) - } else { - Ok(2 as i32) - } - } else { - Ok(24 as i32) - } -} -"#, - r#" -fn foo() -> i32 { - if true { - if false { - 1 as i32 - } else { - 2 as i32 - } - } else { - 24 as i32 - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_block_like_match() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let my_var = 5; - match my_var { - 5 => Ok(42i32), - _ => Ok(24i32), - } -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - match my_var { - 5 => 42i32, - _ => 24i32, - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_loop_with_tail() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let my_var = 5; - loop { - println!("test"); - 5 - } - Ok(my_var) -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - loop { - println!("test"); - 5 - } - my_var -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_loop_in_let_stmt() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let my_var = let x = loop { - break 1; - }; - Ok(my_var) -} -"#, - r#" -fn foo() -> i32 { - let my_var = let x = loop { - break 1; - }; - my_var -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_block_like_match_return_expr() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result$0 { - let my_var = 5; - let res = match my_var { - 5 => 42i32, - _ => return Ok(24i32), - }; - Ok(res) -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - let res = match my_var { - 5 => 42i32, - _ => return 24i32, - }; - res -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let my_var = 5; - let res = if my_var == 5 { - 42i32 - } else { - return Ok(24i32); - }; - Ok(res) -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - let res = if my_var == 5 { - 42i32 - } else { - return 24i32; - }; - res -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_block_like_match_deeper() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let my_var = 5; - match my_var { - 5 => { - if true { - Ok(42i32) - } else { - Ok(25i32) - } - }, - _ => { - let test = "test"; - if test == "test" { - return Ok(bar()); - } - Ok(53i32) - }, - } -} -"#, - r#" -fn foo() -> i32 { - let my_var = 5; - match my_var { - 5 => { - if true { - 42i32 - } else { - 25i32 - } - }, - _ => { - let test = "test"; - if test == "test" { - return bar(); - } - 53i32 - }, - } -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_tail_block_like_early_return() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let test = "test"; - if test == "test" { - return Ok(24i32); - } - Ok(53i32) -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - if test == "test" { - return 24i32; - } - 53i32 -} -"#, - ); - } - - #[test] - fn wrap_return_in_tail_position() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(num: i32) -> $0Result { - return Ok(num) -} -"#, - r#" -fn foo(num: i32) -> i32 { - return num -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_closure() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(the_field: u32) -> Result { - let true_closure = || { return true; }; - if the_field < 5 { - let mut i = 0; - if true_closure() { - return Ok(99); - } else { - return Ok(0); - } - } - Ok(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - let true_closure = || { return true; }; - if the_field < 5 { - let mut i = 0; - if true_closure() { - return 99; - } else { - return 0; - } - } - the_field -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(the_field: u32) -> Result { - let true_closure = || { - return true; - }; - if the_field < 5 { - let mut i = 0; - - - if true_closure() { - return Ok(99); - } else { - return Ok(0); - } - } - let t = None; - - Ok(t.unwrap_or_else(|| the_field)) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - let true_closure = || { - return true; - }; - if the_field < 5 { - let mut i = 0; - - - if true_closure() { - return 99; - } else { - return 0; - } - } - let t = None; - - t.unwrap_or_else(|| the_field) -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_simple_with_weird_forms() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo() -> Result { - let test = "test"; - if test == "test" { - return Ok(24i32); - } - let mut i = 0; - loop { - if i == 1 { - break Ok(55); - } - i += 1; - } -} -"#, - r#" -fn foo() -> i32 { - let test = "test"; - if test == "test" { - return 24i32; - } - let mut i = 0; - loop { - if i == 1 { - break 55; - } - i += 1; - } -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(the_field: u32) -> Result { - if the_field < 5 { - let mut i = 0; - loop { - if i > 5 { - return Ok(55u32); - } - i += 3; - } - match i { - 5 => return Ok(99), - _ => return Ok(0), - }; - } - Ok(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - loop { - if i > 5 { - return 55u32; - } - i += 3; - } - match i { - 5 => return 99, - _ => return 0, - }; - } - the_field -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(the_field: u32) -> Result { - if the_field < 5 { - let mut i = 0; - match i { - 5 => return Ok(99), - _ => return Ok(0), - } - } - Ok(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - match i { - 5 => return 99, - _ => return 0, - } - } - the_field -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(the_field: u32) -> Result { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return Ok(99) - } else { - return Ok(0) - } - } - Ok(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return 99 - } else { - return 0 - } - } - the_field -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result -fn foo(the_field: u32) -> Result { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return Ok(99); - } else { - return Ok(0); - } - } - Ok(the_field) -} -"#, - r#" -fn foo(the_field: u32) -> u32 { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return 99; - } else { - return 0; - } - } - the_field -} -"#, - ); - } - - #[test] - fn unwrap_result_return_type_nested_type() { - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result, option -fn foo() -> Result, ()> { - Ok(Some(42)) -} -"#, - r#" -fn foo() -> Option { - Some(42) -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result, option -fn foo() -> Result>, ()> { - Ok(None) -} -"#, - r#" -fn foo() -> Option> { - None -} -"#, - ); - - check_assist( - unwrap_result_return_type, - r#" -//- minicore: result, option, iterators -fn foo() -> Result$0, ()> { - Ok(Some(42).into_iter()) -} -"#, - r#" -fn foo() -> impl Iterator { - Some(42).into_iter() -} -"#, - ); - } -} diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs new file mode 100644 index 000000000000..b7f873c7798e --- /dev/null +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs @@ -0,0 +1,2159 @@ +use ide_db::{ + famous_defs::FamousDefs, + syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, +}; +use itertools::Itertools; +use syntax::{ + ast::{self, Expr, HasGenericArgs}, + match_ast, AstNode, NodeOrToken, SyntaxKind, TextRange, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: unwrap_option_return_type +// +// Unwrap the function's return type. +// +// ``` +// # //- minicore: option +// fn foo() -> Option$0 { Some(42i32) } +// ``` +// -> +// ``` +// fn foo() -> i32 { 42i32 } +// ``` +pub(crate) fn unwrap_option_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + unwrap_return_type(acc, ctx, UnwrapperKind::Option) +} + +// Assist: unwrap_result_return_type +// +// Unwrap the function's return type. +// +// ``` +// # //- minicore: result +// fn foo() -> Result$0 { Ok(42i32) } +// ``` +// -> +// ``` +// fn foo() -> i32 { 42i32 } +// ``` +pub(crate) fn unwrap_result_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + unwrap_return_type(acc, ctx, UnwrapperKind::Result) +} + +fn unwrap_return_type( + acc: &mut Assists, + ctx: &AssistContext<'_>, + kind: UnwrapperKind, +) -> Option<()> { + let ret_type = ctx.find_node_at_offset::()?; + let parent = ret_type.syntax().parent()?; + let body = match_ast! { + match parent { + ast::Fn(func) => func.body()?, + ast::ClosureExpr(closure) => match closure.body()? { + Expr::BlockExpr(block) => block, + // closures require a block when a return type is specified + _ => return None, + }, + _ => return None, + } + }; + + let type_ref = &ret_type.ty()?; + let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else { + return None; + }; + let core_enum = + kind.core_type(FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()))?; + if ret_enum != core_enum { + return None; + } + + let happy_type = extract_wrapped_type(type_ref)?; + + acc.add(kind.assist_id(), kind.label(), type_ref.syntax().text_range(), |builder| { + let body = ast::Expr::BlockExpr(body); + + let mut exprs_to_unwrap = Vec::new(); + let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); + walk_expr(&body, &mut |expr| { + if let Expr::ReturnExpr(ret_expr) = expr { + if let Some(ret_expr_arg) = &ret_expr.expr() { + for_each_tail_expr(ret_expr_arg, tail_cb); + } + } + }); + for_each_tail_expr(&body, tail_cb); + + let is_unit_type = is_unit_type(&happy_type); + if is_unit_type { + let mut text_range = ret_type.syntax().text_range(); + + if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() { + if token.kind() == SyntaxKind::WHITESPACE { + text_range = TextRange::new(text_range.start(), token.text_range().end()); + } + } + + builder.delete(text_range); + } else { + builder.replace(type_ref.syntax().text_range(), happy_type.syntax().text()); + } + + for ret_expr_arg in exprs_to_unwrap { + let ret_expr_str = ret_expr_arg.to_string(); + + let needs_replacing = match kind { + UnwrapperKind::Option => ret_expr_str.starts_with("Some("), + UnwrapperKind::Result => { + ret_expr_str.starts_with("Ok(") || ret_expr_str.starts_with("Err(") + } + }; + + if needs_replacing { + let arg_list = ret_expr_arg.syntax().children().find_map(ast::ArgList::cast); + if let Some(arg_list) = arg_list { + if is_unit_type { + match ret_expr_arg.syntax().prev_sibling_or_token() { + // Useful to delete the entire line without leaving trailing whitespaces + Some(whitespace) => { + let new_range = TextRange::new( + whitespace.text_range().start(), + ret_expr_arg.syntax().text_range().end(), + ); + builder.delete(new_range); + } + None => { + builder.delete(ret_expr_arg.syntax().text_range()); + } + } + } else { + builder.replace( + ret_expr_arg.syntax().text_range(), + arg_list.args().join(", "), + ); + } + } + } else if matches!(kind, UnwrapperKind::Option if ret_expr_str == "None") { + builder.replace(ret_expr_arg.syntax().text_range(), "()"); + } + } + }) +} + +enum UnwrapperKind { + Option, + Result, +} + +impl UnwrapperKind { + fn assist_id(&self) -> AssistId { + let s = match self { + UnwrapperKind::Option => "unwrap_option_return_type", + UnwrapperKind::Result => "unwrap_result_return_type", + }; + + AssistId(s, AssistKind::RefactorRewrite) + } + + fn label(&self) -> &'static str { + match self { + UnwrapperKind::Option => "Unwrap Option return type", + UnwrapperKind::Result => "Unwrap Result return type", + } + } + + fn core_type(&self, famous_defs: FamousDefs<'_, '_>) -> Option { + match self { + UnwrapperKind::Option => famous_defs.core_option_Option(), + UnwrapperKind::Result => famous_defs.core_result_Result(), + } + } +} + +fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { + match e { + Expr::BreakExpr(break_expr) => { + if let Some(break_expr_arg) = break_expr.expr() { + for_each_tail_expr(&break_expr_arg, &mut |e| tail_cb_impl(acc, e)) + } + } + Expr::ReturnExpr(_) => { + // all return expressions have already been handled by the walk loop + } + e => acc.push(e.clone()), + } +} + +// Tries to extract `T` from `Option` or `Result`. +fn extract_wrapped_type(ty: &ast::Type) -> Option { + let ast::Type::PathType(path_ty) = ty else { + return None; + }; + let path = path_ty.path()?; + let segment = path.first_segment()?; + let generic_arg_list = segment.generic_arg_list()?; + let generic_args: Vec<_> = generic_arg_list.generic_args().collect(); + let ast::GenericArg::TypeArg(happy_type) = generic_args.first()? else { + return None; + }; + happy_type.ty() +} + +fn is_unit_type(ty: &ast::Type) -> bool { + let ast::Type::TupleType(tuple) = ty else { return false }; + tuple.fields().next().is_none() +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn unwrap_option_return_type_simple() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + return Some(42i32); +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_unit_type() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option<()$0> { + Some(()) +} +"#, + r#" +fn foo() { +} +"#, + ); + + // Unformatted return type + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option<()$0>{ + Some(()) +} +"#, + r#" +fn foo() { +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_none() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + if true { + Some(42) + } else { + None + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42 + } else { + () + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_ending_with_parent() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + if true { + Some(42) + } else { + foo() + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42 + } else { + foo() + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_break_split_tail() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + loop { + break if true { + Some(1) + } else { + Some(0) + }; + } +} +"#, + r#" +fn foo() -> i32 { + loop { + break if true { + 1 + } else { + 0 + }; + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> Option { + let test = "test"; + return Some(42i32); + }; +} +"#, + r#" +fn foo() { + || -> i32 { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_bad_cursor() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> i32 { + let test = "test";$0 + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_bad_cursor_closure() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> i32 { + let test = "test";$0 + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_closure_non_block() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { || -> i$032 3; } +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_already_not_option_std() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> i32$0 { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_return_type_already_not_option_closure() { + check_assist_not_applicable( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> i32$0 { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() ->$0 Option { + let test = "test"; + Some(42i32) +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + 42i32 +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || ->$0 Option { + let test = "test"; + Some(42i32) + }; +} +"#, + r#" +fn foo() { + || -> i32 { + let test = "test"; + 42i32 + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_only() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { Some(42i32) } +"#, + r#" +fn foo() -> i32 { 42i32 } +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option$0 { + if true { + Some(42i32) + } else { + Some(24i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42i32 + } else { + 24i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_without_block_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() { + || -> Option$0 { + if true { + Some(42i32) + } else { + Some(24i32) + } + }; +} +"#, + r#" +fn foo() { + || -> i32 { + if true { + 42i32 + } else { + 24i32 + } + }; +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_nested_if() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option$0 { + if true { + if false { + Some(1) + } else { + Some(2) + } + } else { + Some(24i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + if false { + 1 + } else { + 2 + } + } else { + 24i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_await() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +async fn foo() -> Option { + if true { + if false { + Some(1.await) + } else { + Some(2.await) + } + } else { + Some(24i32.await) + } +} +"#, + r#" +async fn foo() -> i32 { + if true { + if false { + 1.await + } else { + 2.await + } + } else { + 24i32.await + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_array() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option<[i32; 3]$0> { Some([1, 2, 3]) } +"#, + r#" +fn foo() -> [i32; 3] { [1, 2, 3] } +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_cast() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -$0> Option { + if true { + if false { + Some(1 as i32) + } else { + Some(2 as i32) + } + } else { + Some(24 as i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + if false { + 1 as i32 + } else { + 2 as i32 + } + } else { + 24 as i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_match() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => Some(42i32), + _ => Some(24i32), + } +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + match my_var { + 5 => 42i32, + _ => 24i32, + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_loop_with_tail() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + loop { + println!("test"); + 5 + } + Some(my_var) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + loop { + println!("test"); + 5 + } + my_var +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_loop_in_let_stmt() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = let x = loop { + break 1; + }; + Some(my_var) +} +"#, + r#" +fn foo() -> i32 { + let my_var = let x = loop { + break 1; + }; + my_var +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_match_return_expr() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option$0 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return Some(24i32), + }; + Some(res) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return 24i32, + }; + res +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return Some(24i32); + }; + Some(res) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return 24i32; + }; + res +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_match_deeper() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => { + if true { + Some(42i32) + } else { + Some(25i32) + } + }, + _ => { + let test = "test"; + if test == "test" { + return Some(bar()); + } + Some(53i32) + }, + } +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + match my_var { + 5 => { + if true { + 42i32 + } else { + 25i32 + } + }, + _ => { + let test = "test"; + if test == "test" { + return bar(); + } + 53i32 + }, + } +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_tail_block_like_early_return() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + Some(53i32) +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + if test == "test" { + return 24i32; + } + 53i32 +} +"#, + ); + } + + #[test] + fn unwrap_option_return_in_tail_position() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(num: i32) -> $0Option { + return Some(num) +} +"#, + r#" +fn foo(num: i32) -> i32 { + return num +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_closure() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + let t = None; + + Some(t.unwrap_or_else(|| the_field)) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return 99; + } else { + return 0; + } + } + let t = None; + + t.unwrap_or_else(|| the_field) +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_simple_with_weird_forms() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + let mut i = 0; + loop { + if i == 1 { + break Some(55); + } + i += 1; + } +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + if i == 1 { + break 55; + } + i += 1; + } +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return Some(55u32); + } + i += 3; + } + match i { + 5 => return Some(99), + _ => return Some(0), + }; + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return 55u32; + } + i += 3; + } + match i { + 5 => return 99, + _ => return 0, + }; + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return Some(99), + _ => return Some(0), + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return 99, + _ => return 0, + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99) + } else { + return Some(0) + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99 + } else { + return 0 + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + ); + } + + #[test] + fn unwrap_option_return_type_nested_type() { + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option, result +fn foo() -> Option> { + Some(Ok(42)) +} +"#, + r#" +fn foo() -> Result { + Ok(42) +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option, result +fn foo() -> Option, ()>> { + Some(Err()) +} +"#, + r#" +fn foo() -> Result, ()> { + Err() +} +"#, + ); + + check_assist( + unwrap_option_return_type, + r#" +//- minicore: option, result, iterators +fn foo() -> Option$0> { + Some(Some(42).into_iter()) +} +"#, + r#" +fn foo() -> impl Iterator { + Some(42).into_iter() +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let test = "test"; + return Ok(42i32); +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_unit_type() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result<(), Box> { + Ok(()) +} +"#, + r#" +fn foo() { +} +"#, + ); + + // Unformatted return type + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result<(), Box>{ + Ok(()) +} +"#, + r#" +fn foo() { +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_ending_with_parent() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result> { + if true { + Ok(42) + } else { + foo() + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42 + } else { + foo() + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_break_split_tail() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + loop { + break if true { + Ok(1) + } else { + Ok(0) + }; + } +} +"#, + r#" +fn foo() -> i32 { + loop { + break if true { + 1 + } else { + 0 + }; + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_closure() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() { + || -> Result { + let test = "test"; + return Ok(42i32); + }; +} +"#, + r#" +fn foo() { + || -> i32 { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_return_type_bad_cursor() { + check_assist_not_applicable( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> i32 { + let test = "test";$0 + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_return_type_bad_cursor_closure() { + check_assist_not_applicable( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() { + || -> i32 { + let test = "test";$0 + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_closure_non_block() { + check_assist_not_applicable( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() { || -> i$032 3; } +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_return_type_already_not_result_std() { + check_assist_not_applicable( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> i32$0 { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_return_type_already_not_result_closure() { + check_assist_not_applicable( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() { + || -> i32$0 { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() ->$0 Result { + let test = "test"; + Ok(42i32) +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + 42i32 +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_closure() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() { + || ->$0 Result { + let test = "test"; + Ok(42i32) + }; +} +"#, + r#" +fn foo() { + || -> i32 { + let test = "test"; + 42i32 + }; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_only() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { Ok(42i32) } +"#, + r#" +fn foo() -> i32 { 42i32 } +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_block_like() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result$0 { + if true { + Ok(42i32) + } else { + Ok(24i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + 42i32 + } else { + 24i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_without_block_closure() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() { + || -> Result$0 { + if true { + Ok(42i32) + } else { + Ok(24i32) + } + }; +} +"#, + r#" +fn foo() { + || -> i32 { + if true { + 42i32 + } else { + 24i32 + } + }; +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_nested_if() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result$0 { + if true { + if false { + Ok(1) + } else { + Ok(2) + } + } else { + Ok(24i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + if false { + 1 + } else { + 2 + } + } else { + 24i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_await() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +async fn foo() -> Result { + if true { + if false { + Ok(1.await) + } else { + Ok(2.await) + } + } else { + Ok(24i32.await) + } +} +"#, + r#" +async fn foo() -> i32 { + if true { + if false { + 1.await + } else { + 2.await + } + } else { + 24i32.await + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_array() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result<[i32; 3]$0> { Ok([1, 2, 3]) } +"#, + r#" +fn foo() -> [i32; 3] { [1, 2, 3] } +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_cast() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -$0> Result { + if true { + if false { + Ok(1 as i32) + } else { + Ok(2 as i32) + } + } else { + Ok(24 as i32) + } +} +"#, + r#" +fn foo() -> i32 { + if true { + if false { + 1 as i32 + } else { + 2 as i32 + } + } else { + 24 as i32 + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_block_like_match() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let my_var = 5; + match my_var { + 5 => Ok(42i32), + _ => Ok(24i32), + } +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + match my_var { + 5 => 42i32, + _ => 24i32, + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_loop_with_tail() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let my_var = 5; + loop { + println!("test"); + 5 + } + Ok(my_var) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + loop { + println!("test"); + 5 + } + my_var +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_loop_in_let_stmt() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let my_var = let x = loop { + break 1; + }; + Ok(my_var) +} +"#, + r#" +fn foo() -> i32 { + let my_var = let x = loop { + break 1; + }; + my_var +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_block_like_match_return_expr() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result$0 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return Ok(24i32), + }; + Ok(res) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return 24i32, + }; + res +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return Ok(24i32); + }; + Ok(res) +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return 24i32; + }; + res +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_block_like_match_deeper() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let my_var = 5; + match my_var { + 5 => { + if true { + Ok(42i32) + } else { + Ok(25i32) + } + }, + _ => { + let test = "test"; + if test == "test" { + return Ok(bar()); + } + Ok(53i32) + }, + } +} +"#, + r#" +fn foo() -> i32 { + let my_var = 5; + match my_var { + 5 => { + if true { + 42i32 + } else { + 25i32 + } + }, + _ => { + let test = "test"; + if test == "test" { + return bar(); + } + 53i32 + }, + } +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_tail_block_like_early_return() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let test = "test"; + if test == "test" { + return Ok(24i32); + } + Ok(53i32) +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + if test == "test" { + return 24i32; + } + 53i32 +} +"#, + ); + } + + #[test] + fn unwrap_result_return_in_tail_position() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(num: i32) -> $0Result { + return Ok(num) +} +"#, + r#" +fn foo(num: i32) -> i32 { + return num +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_closure() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(the_field: u32) -> Result { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return Ok(99); + } else { + return Ok(0); + } + } + Ok(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(the_field: u32) -> Result { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return Ok(99); + } else { + return Ok(0); + } + } + let t = None; + + Ok(t.unwrap_or_else(|| the_field)) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return 99; + } else { + return 0; + } + } + let t = None; + + t.unwrap_or_else(|| the_field) +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_simple_with_weird_forms() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo() -> Result { + let test = "test"; + if test == "test" { + return Ok(24i32); + } + let mut i = 0; + loop { + if i == 1 { + break Ok(55); + } + i += 1; + } +} +"#, + r#" +fn foo() -> i32 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + if i == 1 { + break 55; + } + i += 1; + } +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return Ok(55u32); + } + i += 3; + } + match i { + 5 => return Ok(99), + _ => return Ok(0), + }; + } + Ok(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return 55u32; + } + i += 3; + } + match i { + 5 => return 99, + _ => return 0, + }; + } + the_field +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return Ok(99), + _ => return Ok(0), + } + } + Ok(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return 99, + _ => return 0, + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Ok(99) + } else { + return Ok(0) + } + } + Ok(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99 + } else { + return 0 + } + } + the_field +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Ok(99); + } else { + return Ok(0); + } + } + Ok(the_field) +} +"#, + r#" +fn foo(the_field: u32) -> u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + ); + } + + #[test] + fn unwrap_result_return_type_nested_type() { + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result, option +fn foo() -> Result, ()> { + Ok(Some(42)) +} +"#, + r#" +fn foo() -> Option { + Some(42) +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result, option +fn foo() -> Result>, ()> { + Ok(None) +} +"#, + r#" +fn foo() -> Option> { + None +} +"#, + ); + + check_assist( + unwrap_result_return_type, + r#" +//- minicore: result, option, iterators +fn foo() -> Result$0, ()> { + Ok(Some(42).into_iter()) +} +"#, + r#" +fn foo() -> impl Iterator { + Some(42).into_iter() +} +"#, + ); + } +} diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_result.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs similarity index 51% rename from src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_result.rs rename to src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs index 8f0e9b4fe09d..e6e1857a3f76 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_result.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -13,6 +13,22 @@ use syntax::{ use crate::{AssistContext, AssistId, AssistKind, Assists}; +// Assist: wrap_return_type_in_option +// +// Wrap the function's return type into Option. +// +// ``` +// # //- minicore: option +// fn foo() -> i32$0 { 42i32 } +// ``` +// -> +// ``` +// fn foo() -> Option { Some(42i32) } +// ``` +pub(crate) fn wrap_return_type_in_option(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + wrap_return_type(acc, ctx, WrapperKind::Option) +} + // Assist: wrap_return_type_in_result // // Wrap the function's return type into Result. @@ -26,6 +42,61 @@ use crate::{AssistContext, AssistId, AssistKind, Assists}; // fn foo() -> Result { Ok(42i32) } // ``` pub(crate) fn wrap_return_type_in_result(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + wrap_return_type(acc, ctx, WrapperKind::Result) +} + +enum WrapperKind { + Option, + Result, +} + +impl WrapperKind { + fn assist_id(&self) -> AssistId { + let s = match self { + WrapperKind::Option => "wrap_return_type_in_option", + WrapperKind::Result => "wrap_return_type_in_result", + }; + + AssistId(s, AssistKind::RefactorRewrite) + } + + fn label(&self) -> &'static str { + match self { + WrapperKind::Option => "Wrap return type in Option", + WrapperKind::Result => "Wrap return type in Result", + } + } + + fn happy_ident(&self) -> &'static str { + match self { + WrapperKind::Option => "Some", + WrapperKind::Result => "Ok", + } + } + + fn core_type(&self, famous_defs: FamousDefs<'_, '_>) -> Option { + match self { + WrapperKind::Option => famous_defs.core_option_Option(), + WrapperKind::Result => famous_defs.core_result_Result(), + } + } + + fn symbol(&self) -> hir::Symbol { + match self { + WrapperKind::Option => hir::sym::Option.clone(), + WrapperKind::Result => hir::sym::Result.clone(), + } + } + + fn wrap_type(&self, type_ref: &ast::Type) -> ast::Type { + match self { + WrapperKind::Option => make::ext::ty_option(type_ref.clone()), + WrapperKind::Result => make::ext::ty_result(type_ref.clone(), make::ty_placeholder()), + } + } +} + +fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>, kind: WrapperKind) -> Option<()> { let ret_type = ctx.find_node_at_offset::()?; let parent = ret_type.syntax().parent()?; let body = match_ast! { @@ -41,50 +112,49 @@ pub(crate) fn wrap_return_type_in_result(acc: &mut Assists, ctx: &AssistContext< }; let type_ref = &ret_type.ty()?; - let core_result = - FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_result_Result()?; + let core_wrapper = + kind.core_type(FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()))?; let ty = ctx.sema.resolve_type(type_ref)?.as_adt(); - if matches!(ty, Some(hir::Adt::Enum(ret_type)) if ret_type == core_result) { - // The return type is already wrapped in a Result - cov_mark::hit!(wrap_return_type_in_result_simple_return_type_already_result); + if matches!(ty, Some(hir::Adt::Enum(ret_type)) if ret_type == core_wrapper) { + // The return type is already wrapped + cov_mark::hit!(wrap_return_type_simple_return_type_already_wrapped); return None; } - acc.add( - AssistId("wrap_return_type_in_result", AssistKind::RefactorRewrite), - "Wrap return type in Result", - type_ref.syntax().text_range(), - |edit| { - let new_result_ty = result_type(ctx, &core_result, type_ref).clone_for_update(); - let body = edit.make_mut(ast::Expr::BlockExpr(body)); + acc.add(kind.assist_id(), kind.label(), type_ref.syntax().text_range(), |edit| { + let alias = wrapper_alias(ctx, &core_wrapper, type_ref, kind.symbol()); + let new_return_ty = alias.unwrap_or_else(|| kind.wrap_type(type_ref)).clone_for_update(); - let mut exprs_to_wrap = Vec::new(); - let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); - walk_expr(&body, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + let body = edit.make_mut(ast::Expr::BlockExpr(body)); + + let mut exprs_to_wrap = Vec::new(); + let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); + walk_expr(&body, &mut |expr| { + if let Expr::ReturnExpr(ret_expr) = expr { + if let Some(ret_expr_arg) = &ret_expr.expr() { + for_each_tail_expr(ret_expr_arg, tail_cb); } - }); - for_each_tail_expr(&body, tail_cb); - - for ret_expr_arg in exprs_to_wrap { - let ok_wrapped = make::expr_call( - make::expr_path(make::ext::ident_path("Ok")), - make::arg_list(iter::once(ret_expr_arg.clone())), - ) - .clone_for_update(); - ted::replace(ret_expr_arg.syntax(), ok_wrapped.syntax()); } + }); + for_each_tail_expr(&body, tail_cb); - let old_result_ty = edit.make_mut(type_ref.clone()); - ted::replace(old_result_ty.syntax(), new_result_ty.syntax()); + for ret_expr_arg in exprs_to_wrap { + let happy_wrapped = make::expr_call( + make::expr_path(make::ext::ident_path(kind.happy_ident())), + make::arg_list(iter::once(ret_expr_arg.clone())), + ) + .clone_for_update(); + ted::replace(ret_expr_arg.syntax(), happy_wrapped.syntax()); + } + let old_return_ty = edit.make_mut(type_ref.clone()); + ted::replace(old_return_ty.syntax(), new_return_ty.syntax()); + + if let WrapperKind::Result = kind { // Add a placeholder snippet at the first generic argument that doesn't equal the return type. // This is normally the error type, but that may not be the case when we inserted a type alias. - let args = new_result_ty.syntax().descendants().find_map(ast::GenericArgList::cast); + let args = new_return_ty.syntax().descendants().find_map(ast::GenericArgList::cast); let error_type_arg = args.and_then(|list| { list.generic_args().find(|arg| match arg { ast::GenericArg::TypeArg(_) => arg.syntax().text() != type_ref.syntax().text(), @@ -97,25 +167,27 @@ pub(crate) fn wrap_return_type_in_result(acc: &mut Assists, ctx: &AssistContext< edit.add_placeholder_snippet(cap, error_type_arg); } } - }, - ) + } + }) } -fn result_type( +// Try to find an wrapper type alias in the current scope (shadowing the default). +fn wrapper_alias( ctx: &AssistContext<'_>, - core_result: &hir::Enum, + core_wrapper: &hir::Enum, ret_type: &ast::Type, -) -> ast::Type { - // Try to find a Result type alias in the current scope (shadowing the default). - let result_path = hir::ModPath::from_segments( + wrapper: hir::Symbol, +) -> Option { + let wrapper_path = hir::ModPath::from_segments( hir::PathKind::Plain, - iter::once(hir::Name::new_symbol_root(hir::sym::Result.clone())), + iter::once(hir::Name::new_symbol_root(wrapper)), ); - let alias = ctx.sema.resolve_mod_path(ret_type.syntax(), &result_path).and_then(|def| { + + ctx.sema.resolve_mod_path(ret_type.syntax(), &wrapper_path).and_then(|def| { def.filter_map(|def| match def.as_module_def()? { hir::ModuleDef::TypeAlias(alias) => { let enum_ty = alias.ty(ctx.db()).as_adt()?.as_enum()?; - (&enum_ty == core_result).then_some(alias) + (&enum_ty == core_wrapper).then_some(alias) } _ => None, }) @@ -141,9 +213,7 @@ fn result_type( let name = name.as_str(); Some(make::ty(&format!("{name}<{generic_params}>"))) }) - }); - // If there is no applicable alias in scope use the default Result type. - alias.unwrap_or_else(|| make::ext::ty_result(ret_type.clone(), make::ty_placeholder())) + }) } fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { @@ -166,6 +236,1027 @@ mod tests { use super::*; + #[test] + fn wrap_return_type_in_option_simple() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i3$02 { + let test = "test"; + return 42i32; +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_break_split_tail() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i3$02 { + loop { + break if true { + 1 + } else { + 0 + }; + } +} +"#, + r#" +fn foo() -> Option { + loop { + break if true { + Some(1) + } else { + Some(0) + }; + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> i32$0 { + let test = "test"; + return 42i32; + }; +} +"#, + r#" +fn foo() { + || -> Option { + let test = "test"; + return Some(42i32); + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_bad_cursor() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32 { + let test = "test";$0 + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_bad_cursor_closure() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> i32 { + let test = "test";$0 + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_closure_non_block() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { || -> i$032 3; } +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_already_option_std() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> core::option::Option { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_already_option() { + cov_mark::check!(wrap_return_type_simple_return_type_already_wrapped); + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> Option { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_return_type_already_option_closure() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> Option { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_cursor() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> $0i32 { + let test = "test"; + return 42i32; +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() ->$0 i32 { + let test = "test"; + 42i32 +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + Some(42i32) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || ->$0 i32 { + let test = "test"; + 42i32 + }; +} +"#, + r#" +fn foo() { + || -> Option { + let test = "test"; + Some(42i32) + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_only() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { 42i32 } +"#, + r#" +fn foo() -> Option { Some(42i32) } +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + if true { + 42i32 + } else { + 24i32 + } +} +"#, + r#" +fn foo() -> Option { + if true { + Some(42i32) + } else { + Some(24i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_without_block_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() { + || -> i32$0 { + if true { + 42i32 + } else { + 24i32 + } + }; +} +"#, + r#" +fn foo() { + || -> Option { + if true { + Some(42i32) + } else { + Some(24i32) + } + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_nested_if() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + if true { + if false { + 1 + } else { + 2 + } + } else { + 24i32 + } +} +"#, + r#" +fn foo() -> Option { + if true { + if false { + Some(1) + } else { + Some(2) + } + } else { + Some(24i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_await() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +async fn foo() -> i$032 { + if true { + if false { + 1.await + } else { + 2.await + } + } else { + 24i32.await + } +} +"#, + r#" +async fn foo() -> Option { + if true { + if false { + Some(1.await) + } else { + Some(2.await) + } + } else { + Some(24i32.await) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_array() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> [i32;$0 3] { [1, 2, 3] } +"#, + r#" +fn foo() -> Option<[i32; 3]> { Some([1, 2, 3]) } +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_cast() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -$0> i32 { + if true { + if false { + 1 as i32 + } else { + 2 as i32 + } + } else { + 24 as i32 + } +} +"#, + r#" +fn foo() -> Option { + if true { + if false { + Some(1 as i32) + } else { + Some(2 as i32) + } + } else { + Some(24 as i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_match() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + match my_var { + 5 => 42i32, + _ => 24i32, + } +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => Some(42i32), + _ => Some(24i32), + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_loop_with_tail() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + loop { + println!("test"); + 5 + } + my_var +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + loop { + println!("test"); + 5 + } + Some(my_var) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_loop_in_let_stmt() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = let x = loop { + break 1; + }; + my_var +} +"#, + r#" +fn foo() -> Option { + let my_var = let x = loop { + break 1; + }; + Some(my_var) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_match_return_expr() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return 24i32, + }; + res +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return Some(24i32), + }; + Some(res) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return 24i32; + }; + res +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return Some(24i32); + }; + Some(res) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_match_deeper() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let my_var = 5; + match my_var { + 5 => { + if true { + 42i32 + } else { + 25i32 + } + }, + _ => { + let test = "test"; + if test == "test" { + return bar(); + } + 53i32 + }, + } +} +"#, + r#" +fn foo() -> Option { + let my_var = 5; + match my_var { + 5 => { + if true { + Some(42i32) + } else { + Some(25i32) + } + }, + _ => { + let test = "test"; + if test == "test" { + return Some(bar()); + } + Some(53i32) + }, + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_tail_block_like_early_return() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i$032 { + let test = "test"; + if test == "test" { + return 24i32; + } + 53i32 +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + Some(53i32) +} +"#, + ); + } + + #[test] + fn wrap_return_in_option_tail_position() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(num: i32) -> $0i32 { + return num +} +"#, + r#" +fn foo(num: i32) -> Option { + return Some(num) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_closure() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) ->$0 u32 { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u32$0 { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return 99; + } else { + return 0; + } + } + let t = None; + + t.unwrap_or_else(|| the_field) +} +"#, + r#" +fn foo(the_field: u32) -> Option { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return Some(99); + } else { + return Some(0); + } + } + let t = None; + + Some(t.unwrap_or_else(|| the_field)) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_option_simple_with_weird_forms() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i32$0 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + if i == 1 { + break 55; + } + i += 1; + } +} +"#, + r#" +fn foo() -> Option { + let test = "test"; + if test == "test" { + return Some(24i32); + } + let mut i = 0; + loop { + if i == 1 { + break Some(55); + } + i += 1; + } +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u32$0 { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return 55u32; + } + i += 3; + } + match i { + 5 => return 99, + _ => return 0, + }; + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return Some(55u32); + } + i += 3; + } + match i { + 5 => return Some(99), + _ => return Some(0), + }; + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u3$02 { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return 99, + _ => return 0, + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return Some(99), + _ => return Some(0), + } + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> u32$0 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99 + } else { + return 0 + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99) + } else { + return Some(0) + } + } + Some(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo(the_field: u32) -> $0u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Option { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Some(99); + } else { + return Some(0); + } + } + Some(the_field) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_local_option_type() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +type Option = core::option::Option; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +type Option = core::option::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +type Option2 = core::option::Option; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +type Option2 = core::option::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_imported_local_option_type() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::Option; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::*; + +fn foo() -> i3$02 { + return 42i32; +} +"#, + r#" +mod some_module { + pub type Option = core::option::Option; +} + +use some_module::*; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_local_option_type_from_function_body() { + check_assist( + wrap_return_type_in_option, + r#" +//- minicore: option +fn foo() -> i3$02 { + type Option = core::option::Option; + 0 +} +"#, + r#" +fn foo() -> Option { + type Option = core::option::Option; + Some(0) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_local_option_type_already_using_alias() { + check_assist_not_applicable( + wrap_return_type_in_option, + r#" +//- minicore: option +pub type Option = core::option::Option; + +fn foo() -> Option { + return Some(42i32); +} +"#, + ); + } + #[test] fn wrap_return_type_in_result_simple() { check_assist( @@ -187,7 +1278,7 @@ fn foo() -> Result { } #[test] - fn wrap_return_type_break_split_tail() { + fn wrap_return_type_in_result_break_split_tail() { check_assist( wrap_return_type_in_result, r#" @@ -297,7 +1388,7 @@ fn foo() -> core::result::Result { #[test] fn wrap_return_type_in_result_simple_return_type_already_result() { - cov_mark::check!(wrap_return_type_in_result_simple_return_type_already_result); + cov_mark::check!(wrap_return_type_simple_return_type_already_wrapped); check_assist_not_applicable( wrap_return_type_in_result, r#" @@ -786,7 +1877,7 @@ fn foo() -> Result { } #[test] - fn wrap_return_in_tail_position() { + fn wrap_return_in_result_tail_position() { check_assist( wrap_return_type_in_result, r#" diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs deleted file mode 100644 index 90cfc2ef17c7..000000000000 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type_in_option.rs +++ /dev/null @@ -1,1173 +0,0 @@ -use std::iter; - -use hir::HasSource; -use ide_db::{ - famous_defs::FamousDefs, - syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, -}; -use itertools::Itertools; -use syntax::{ - ast::{self, make, Expr, HasGenericParams}, - match_ast, ted, AstNode, ToSmolStr, -}; - -use crate::{AssistContext, AssistId, AssistKind, Assists}; - -// Assist: wrap_return_type_in_option -// -// Wrap the function's return type into Option. -// -// ``` -// # //- minicore: option -// fn foo() -> i32$0 { 42i32 } -// ``` -// -> -// ``` -// fn foo() -> Option { Some(42i32) } -// ``` -pub(crate) fn wrap_return_type_in_option(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - let ret_type = ctx.find_node_at_offset::()?; - let parent = ret_type.syntax().parent()?; - let body = match_ast! { - match parent { - ast::Fn(func) => func.body()?, - ast::ClosureExpr(closure) => match closure.body()? { - Expr::BlockExpr(block) => block, - // closures require a block when a return type is specified - _ => return None, - }, - _ => return None, - } - }; - - let type_ref = &ret_type.ty()?; - let core_option = - FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_option_Option()?; - - let ty = ctx.sema.resolve_type(type_ref)?.as_adt(); - if matches!(ty, Some(hir::Adt::Enum(ret_type)) if ret_type == core_option) { - // The return type is already wrapped in an Option - cov_mark::hit!(wrap_return_type_in_option_simple_return_type_already_option); - return None; - } - - acc.add( - AssistId("wrap_return_type_in_option", AssistKind::RefactorRewrite), - "Wrap return type in Option", - type_ref.syntax().text_range(), - |edit| { - let new_option_ty = option_type(ctx, &core_option, type_ref).clone_for_update(); - let body = edit.make_mut(ast::Expr::BlockExpr(body)); - - let mut exprs_to_wrap = Vec::new(); - let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); - walk_expr(&body, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } - } - }); - for_each_tail_expr(&body, tail_cb); - - for ret_expr_arg in exprs_to_wrap { - let some_wrapped = make::expr_call( - make::expr_path(make::ext::ident_path("Some")), - make::arg_list(iter::once(ret_expr_arg.clone())), - ) - .clone_for_update(); - ted::replace(ret_expr_arg.syntax(), some_wrapped.syntax()); - } - - let old_option_ty = edit.make_mut(type_ref.clone()); - ted::replace(old_option_ty.syntax(), new_option_ty.syntax()); - }, - ) -} - -fn option_type( - ctx: &AssistContext<'_>, - core_option: &hir::Enum, - ret_type: &ast::Type, -) -> ast::Type { - // Try to find an Option type alias in the current scope (shadowing the default). - let option_path = hir::ModPath::from_segments( - hir::PathKind::Plain, - iter::once(hir::Name::new_symbol_root(hir::sym::Option.clone())), - ); - let alias = ctx.sema.resolve_mod_path(ret_type.syntax(), &option_path).and_then(|def| { - def.filter_map(|def| match def.as_module_def()? { - hir::ModuleDef::TypeAlias(alias) => { - let enum_ty = alias.ty(ctx.db()).as_adt()?.as_enum()?; - (&enum_ty == core_option).then_some(alias) - } - _ => None, - }) - .find_map(|alias| { - let mut inserted_ret_type = false; - let generic_params = alias - .source(ctx.db())? - .value - .generic_param_list()? - .generic_params() - .map(|param| match param { - // Replace the very first type parameter with the functions return type. - ast::GenericParam::TypeParam(_) if !inserted_ret_type => { - inserted_ret_type = true; - ret_type.to_smolstr() - } - ast::GenericParam::LifetimeParam(_) => make::lifetime("'_").to_smolstr(), - _ => make::ty_placeholder().to_smolstr(), - }) - .join(", "); - - let name = alias.name(ctx.db()); - let name = name.as_str(); - Some(make::ty(&format!("{name}<{generic_params}>"))) - }) - }); - // If there is no applicable alias in scope use the default Option type. - alias.unwrap_or_else(|| make::ext::ty_option(ret_type.clone())) -} - -fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { - match e { - Expr::BreakExpr(break_expr) => { - if let Some(break_expr_arg) = break_expr.expr() { - for_each_tail_expr(&break_expr_arg, &mut |e| tail_cb_impl(acc, e)) - } - } - Expr::ReturnExpr(_) => { - // all return expressions have already been handled by the walk loop - } - e => acc.push(e.clone()), - } -} - -#[cfg(test)] -mod tests { - use crate::tests::{check_assist, check_assist_not_applicable}; - - use super::*; - - #[test] - fn wrap_return_type_in_option_simple() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i3$02 { - let test = "test"; - return 42i32; -} -"#, - r#" -fn foo() -> Option { - let test = "test"; - return Some(42i32); -} -"#, - ); - } - - #[test] - fn wrap_return_type_break_split_tail() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i3$02 { - loop { - break if true { - 1 - } else { - 0 - }; - } -} -"#, - r#" -fn foo() -> Option { - loop { - break if true { - Some(1) - } else { - Some(0) - }; - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_closure() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() { - || -> i32$0 { - let test = "test"; - return 42i32; - }; -} -"#, - r#" -fn foo() { - || -> Option { - let test = "test"; - return Some(42i32); - }; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_return_type_bad_cursor() { - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32 { - let test = "test";$0 - return 42i32; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() { - || -> i32 { - let test = "test";$0 - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_closure_non_block() { - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() { || -> i$032 3; } -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_return_type_already_option_std() { - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> core::option::Option { - let test = "test"; - return 42i32; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_return_type_already_option() { - cov_mark::check!(wrap_return_type_in_option_simple_return_type_already_option); - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> Option { - let test = "test"; - return 42i32; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_return_type_already_option_closure() { - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() { - || -> Option { - let test = "test"; - return 42i32; - }; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_cursor() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> $0i32 { - let test = "test"; - return 42i32; -} -"#, - r#" -fn foo() -> Option { - let test = "test"; - return Some(42i32); -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() ->$0 i32 { - let test = "test"; - 42i32 -} -"#, - r#" -fn foo() -> Option { - let test = "test"; - Some(42i32) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_closure() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() { - || ->$0 i32 { - let test = "test"; - 42i32 - }; -} -"#, - r#" -fn foo() { - || -> Option { - let test = "test"; - Some(42i32) - }; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_only() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { 42i32 } -"#, - r#" -fn foo() -> Option { Some(42i32) } -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_block_like() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - if true { - 42i32 - } else { - 24i32 - } -} -"#, - r#" -fn foo() -> Option { - if true { - Some(42i32) - } else { - Some(24i32) - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_without_block_closure() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() { - || -> i32$0 { - if true { - 42i32 - } else { - 24i32 - } - }; -} -"#, - r#" -fn foo() { - || -> Option { - if true { - Some(42i32) - } else { - Some(24i32) - } - }; -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_nested_if() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - if true { - if false { - 1 - } else { - 2 - } - } else { - 24i32 - } -} -"#, - r#" -fn foo() -> Option { - if true { - if false { - Some(1) - } else { - Some(2) - } - } else { - Some(24i32) - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_await() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -async fn foo() -> i$032 { - if true { - if false { - 1.await - } else { - 2.await - } - } else { - 24i32.await - } -} -"#, - r#" -async fn foo() -> Option { - if true { - if false { - Some(1.await) - } else { - Some(2.await) - } - } else { - Some(24i32.await) - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_array() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> [i32;$0 3] { [1, 2, 3] } -"#, - r#" -fn foo() -> Option<[i32; 3]> { Some([1, 2, 3]) } -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_cast() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -$0> i32 { - if true { - if false { - 1 as i32 - } else { - 2 as i32 - } - } else { - 24 as i32 - } -} -"#, - r#" -fn foo() -> Option { - if true { - if false { - Some(1 as i32) - } else { - Some(2 as i32) - } - } else { - Some(24 as i32) - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_block_like_match() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let my_var = 5; - match my_var { - 5 => 42i32, - _ => 24i32, - } -} -"#, - r#" -fn foo() -> Option { - let my_var = 5; - match my_var { - 5 => Some(42i32), - _ => Some(24i32), - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_loop_with_tail() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let my_var = 5; - loop { - println!("test"); - 5 - } - my_var -} -"#, - r#" -fn foo() -> Option { - let my_var = 5; - loop { - println!("test"); - 5 - } - Some(my_var) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_loop_in_let_stmt() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let my_var = let x = loop { - break 1; - }; - my_var -} -"#, - r#" -fn foo() -> Option { - let my_var = let x = loop { - break 1; - }; - Some(my_var) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_block_like_match_return_expr() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let my_var = 5; - let res = match my_var { - 5 => 42i32, - _ => return 24i32, - }; - res -} -"#, - r#" -fn foo() -> Option { - let my_var = 5; - let res = match my_var { - 5 => 42i32, - _ => return Some(24i32), - }; - Some(res) -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let my_var = 5; - let res = if my_var == 5 { - 42i32 - } else { - return 24i32; - }; - res -} -"#, - r#" -fn foo() -> Option { - let my_var = 5; - let res = if my_var == 5 { - 42i32 - } else { - return Some(24i32); - }; - Some(res) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_block_like_match_deeper() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let my_var = 5; - match my_var { - 5 => { - if true { - 42i32 - } else { - 25i32 - } - }, - _ => { - let test = "test"; - if test == "test" { - return bar(); - } - 53i32 - }, - } -} -"#, - r#" -fn foo() -> Option { - let my_var = 5; - match my_var { - 5 => { - if true { - Some(42i32) - } else { - Some(25i32) - } - }, - _ => { - let test = "test"; - if test == "test" { - return Some(bar()); - } - Some(53i32) - }, - } -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_tail_block_like_early_return() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i$032 { - let test = "test"; - if test == "test" { - return 24i32; - } - 53i32 -} -"#, - r#" -fn foo() -> Option { - let test = "test"; - if test == "test" { - return Some(24i32); - } - Some(53i32) -} -"#, - ); - } - - #[test] - fn wrap_return_in_tail_position() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(num: i32) -> $0i32 { - return num -} -"#, - r#" -fn foo(num: i32) -> Option { - return Some(num) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_closure() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(the_field: u32) ->$0 u32 { - let true_closure = || { return true; }; - if the_field < 5 { - let mut i = 0; - if true_closure() { - return 99; - } else { - return 0; - } - } - the_field -} -"#, - r#" -fn foo(the_field: u32) -> Option { - let true_closure = || { return true; }; - if the_field < 5 { - let mut i = 0; - if true_closure() { - return Some(99); - } else { - return Some(0); - } - } - Some(the_field) -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(the_field: u32) -> u32$0 { - let true_closure = || { - return true; - }; - if the_field < 5 { - let mut i = 0; - - - if true_closure() { - return 99; - } else { - return 0; - } - } - let t = None; - - t.unwrap_or_else(|| the_field) -} -"#, - r#" -fn foo(the_field: u32) -> Option { - let true_closure = || { - return true; - }; - if the_field < 5 { - let mut i = 0; - - - if true_closure() { - return Some(99); - } else { - return Some(0); - } - } - let t = None; - - Some(t.unwrap_or_else(|| the_field)) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_option_simple_with_weird_forms() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i32$0 { - let test = "test"; - if test == "test" { - return 24i32; - } - let mut i = 0; - loop { - if i == 1 { - break 55; - } - i += 1; - } -} -"#, - r#" -fn foo() -> Option { - let test = "test"; - if test == "test" { - return Some(24i32); - } - let mut i = 0; - loop { - if i == 1 { - break Some(55); - } - i += 1; - } -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(the_field: u32) -> u32$0 { - if the_field < 5 { - let mut i = 0; - loop { - if i > 5 { - return 55u32; - } - i += 3; - } - match i { - 5 => return 99, - _ => return 0, - }; - } - the_field -} -"#, - r#" -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - loop { - if i > 5 { - return Some(55u32); - } - i += 3; - } - match i { - 5 => return Some(99), - _ => return Some(0), - }; - } - Some(the_field) -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(the_field: u32) -> u3$02 { - if the_field < 5 { - let mut i = 0; - match i { - 5 => return 99, - _ => return 0, - } - } - the_field -} -"#, - r#" -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - match i { - 5 => return Some(99), - _ => return Some(0), - } - } - Some(the_field) -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(the_field: u32) -> u32$0 { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return 99 - } else { - return 0 - } - } - the_field -} -"#, - r#" -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return Some(99) - } else { - return Some(0) - } - } - Some(the_field) -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo(the_field: u32) -> $0u32 { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return 99; - } else { - return 0; - } - } - the_field -} -"#, - r#" -fn foo(the_field: u32) -> Option { - if the_field < 5 { - let mut i = 0; - if i == 5 { - return Some(99); - } else { - return Some(0); - } - } - Some(the_field) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_local_option_type() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -type Option = core::option::Option; - -fn foo() -> i3$02 { - return 42i32; -} -"#, - r#" -type Option = core::option::Option; - -fn foo() -> Option { - return Some(42i32); -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -type Option2 = core::option::Option; - -fn foo() -> i3$02 { - return 42i32; -} -"#, - r#" -type Option2 = core::option::Option; - -fn foo() -> Option { - return Some(42i32); -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_imported_local_option_type() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -mod some_module { - pub type Option = core::option::Option; -} - -use some_module::Option; - -fn foo() -> i3$02 { - return 42i32; -} -"#, - r#" -mod some_module { - pub type Option = core::option::Option; -} - -use some_module::Option; - -fn foo() -> Option { - return Some(42i32); -} -"#, - ); - - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -mod some_module { - pub type Option = core::option::Option; -} - -use some_module::*; - -fn foo() -> i3$02 { - return 42i32; -} -"#, - r#" -mod some_module { - pub type Option = core::option::Option; -} - -use some_module::*; - -fn foo() -> Option { - return Some(42i32); -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_local_option_type_from_function_body() { - check_assist( - wrap_return_type_in_option, - r#" -//- minicore: option -fn foo() -> i3$02 { - type Option = core::option::Option; - 0 -} -"#, - r#" -fn foo() -> Option { - type Option = core::option::Option; - Some(0) -} -"#, - ); - } - - #[test] - fn wrap_return_type_in_local_option_type_already_using_alias() { - check_assist_not_applicable( - wrap_return_type_in_option, - r#" -//- minicore: option -pub type Option = core::option::Option; - -fn foo() -> Option { - return Some(42i32); -} -"#, - ); - } -} diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs index 63a3fec3f41d..8114888d6c3f 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs @@ -223,11 +223,9 @@ mod handlers { mod unnecessary_async; mod unqualify_method_call; mod unwrap_block; - mod unwrap_option_return_type; - mod unwrap_result_return_type; + mod unwrap_return_type; mod unwrap_tuple; - mod wrap_return_type_in_option; - mod wrap_return_type_in_result; + mod wrap_return_type; mod wrap_unwrap_cfg_attr; pub(crate) fn all() -> &'static [Handler] { @@ -357,12 +355,12 @@ mod handlers { unmerge_use::unmerge_use, unnecessary_async::unnecessary_async, unwrap_block::unwrap_block, - unwrap_option_return_type::unwrap_option_return_type, - unwrap_result_return_type::unwrap_result_return_type, + unwrap_return_type::unwrap_option_return_type, + unwrap_return_type::unwrap_result_return_type, unwrap_tuple::unwrap_tuple, unqualify_method_call::unqualify_method_call, - wrap_return_type_in_option::wrap_return_type_in_option, - wrap_return_type_in_result::wrap_return_type_in_result, + wrap_return_type::wrap_return_type_in_option, + wrap_return_type::wrap_return_type_in_result, wrap_unwrap_cfg_attr::wrap_unwrap_cfg_attr, // These are manually sorted for better priorities. By default, From 325d48fe7a9fe70c533f7bbc9553afd0cc0a465e Mon Sep 17 00:00:00 2001 From: David Barsky Date: Thu, 17 Oct 2024 11:53:19 -0400 Subject: [PATCH 023/366] internal: fix lldb-dap unconditionally calling rustc --- .../rust-analyzer/editors/code/src/debug.ts | 43 ++++++++++++------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/src/tools/rust-analyzer/editors/code/src/debug.ts b/src/tools/rust-analyzer/editors/code/src/debug.ts index 77ab44f24ceb..9e2e3d2185bf 100644 --- a/src/tools/rust-analyzer/editors/code/src/debug.ts +++ b/src/tools/rust-analyzer/editors/code/src/debug.ts @@ -6,7 +6,6 @@ import type * as ra from "./lsp_ext"; import { Cargo } from "./toolchain"; import type { Ctx } from "./ctx"; import { createTaskFromRunnable, prepareEnv } from "./run"; -import { execSync } from "node:child_process"; import { execute, isCargoRunnableArgs, unwrapUndefinable } from "./util"; import type { Config } from "./config"; @@ -152,9 +151,24 @@ async function getDebugConfiguration( const env = prepareEnv(inheritEnv, runnable.label, runnableArgs, config.runnablesExtraEnv); const executable = await getDebugExecutable(runnableArgs, env); let sourceFileMap = debugOptions.sourceFileMap; + if (sourceFileMap === "auto") { sourceFileMap = {}; - await discoverSourceFileMap(sourceFileMap, env, wsFolder); + const computedSourceFileMap = await discoverSourceFileMap(env, wsFolder); + + if (computedSourceFileMap) { + // lldb-dap requires passing the source map as an array of two element arrays. + // the two element array contains a source and destination pathname. + // TODO: remove lldb-dap-specific post-processing once + // https://github.com/llvm/llvm-project/pull/106919/ is released in the extension. + if (provider.type === "lldb-dap") { + provider.additional["sourceMap"] = [ + [computedSourceFileMap?.source, computedSourceFileMap?.destination], + ]; + } else { + sourceFileMap[computedSourceFileMap.source] = computedSourceFileMap.destination; + } + } } const debugConfig = getDebugConfig( @@ -189,11 +203,15 @@ async function getDebugConfiguration( return debugConfig; } +type SourceFileMap = { + source: string; + destination: string; +}; + async function discoverSourceFileMap( - sourceFileMap: Record, env: Record, cwd: string, -) { +): Promise { const sysroot = env["RUSTC_TOOLCHAIN"]; if (sysroot) { // let's try to use the default toolchain @@ -203,9 +221,11 @@ async function discoverSourceFileMap( const commitHash = rx.exec(data)?.[1]; if (commitHash) { const rustlib = path.normalize(sysroot + "/lib/rustlib/src/rust"); - sourceFileMap[`/rustc/${commitHash}/`] = rustlib; + return { source: rustlib, destination: rustlib }; } } + + return; } type PropertyFetcher = ( @@ -218,7 +238,7 @@ type DebugConfigProvider; sourceFileMapProperty?: keyof DebugConfig; type: Type; - additional?: Record; + additional: Record; }; type KnownEnginesType = (typeof knownEngines)[keyof typeof knownEngines]; @@ -236,16 +256,7 @@ const knownEngines: { "args", runnableArgs.executableArgs, ], - additional: { - sourceMap: [ - [ - `/rustc/${/commit-hash:\s(.*)$/m.exec( - execSync("rustc -V -v", {}).toString(), - )?.[1]}/library`, - "${config:rust-analyzer.cargo.sysroot}/lib/rustlib/src/rust/library", - ], - ], - }, + additional: {}, }, "vadimcn.vscode-lldb": { type: "lldb", From b3ae64d24fc323365bd09fe6ac8b7438f5713078 Mon Sep 17 00:00:00 2001 From: Andrew Zhogin Date: Mon, 16 Sep 2024 22:14:35 +0700 Subject: [PATCH 024/366] rust_for_linux: -Zregparm= commandline flag for X86 (#116972) --- compiler/rustc_codegen_gcc/src/builder.rs | 8 +- compiler/rustc_codegen_gcc/src/context.rs | 10 +- compiler/rustc_interface/src/tests.rs | 1 + compiler/rustc_middle/src/ty/layout.rs | 16 ++- compiler/rustc_session/messages.ftl | 3 + compiler/rustc_session/src/errors.rs | 10 ++ compiler/rustc_session/src/options.rs | 4 + compiler/rustc_session/src/session.rs | 9 ++ compiler/rustc_target/src/callconv/mod.rs | 44 ++++-- compiler/rustc_target/src/callconv/x86.rs | 106 ++++++++------ compiler/rustc_target/src/spec/mod.rs | 12 ++ compiler/rustc_ty_utils/src/abi.rs | 3 + .../src/compiler-flags/regparm.md | 20 +++ tests/codegen/regparm-inreg-rust-cc.rs | 53 +++++++ tests/codegen/regparm-inreg.rs | 133 ++++++++++++++++++ .../regparm-valid-values.regparm4.stderr | 4 + .../regparm/regparm-valid-values.rs | 24 ++++ .../regparm/requires-x86.aarch64.stderr | 4 + .../regparm/requires-x86.rs | 21 +++ .../regparm/requires-x86.x86_64.stderr | 4 + 20 files changed, 436 insertions(+), 53 deletions(-) create mode 100644 src/doc/unstable-book/src/compiler-flags/regparm.md create mode 100644 tests/codegen/regparm-inreg-rust-cc.rs create mode 100644 tests/codegen/regparm-inreg.rs create mode 100644 tests/ui/invalid-compile-flags/regparm/regparm-valid-values.regparm4.stderr create mode 100644 tests/ui/invalid-compile-flags/regparm/regparm-valid-values.rs create mode 100644 tests/ui/invalid-compile-flags/regparm/requires-x86.aarch64.stderr create mode 100644 tests/ui/invalid-compile-flags/regparm/requires-x86.rs create mode 100644 tests/ui/invalid-compile-flags/regparm/requires-x86.x86_64.stderr diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index b611f9ba8bcb..457380685093 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -30,7 +30,7 @@ use rustc_middle::ty::{Instance, ParamEnv, Ty, TyCtxt}; use rustc_span::Span; use rustc_span::def_id::DefId; use rustc_target::abi::call::FnAbi; -use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, WasmCAbi}; +use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, Target, WasmCAbi, X86Abi}; use crate::common::{SignType, TypeReflection, type_is_pointer}; use crate::context::CodegenCx; @@ -2347,6 +2347,12 @@ impl<'tcx> HasWasmCAbiOpt for Builder<'_, '_, 'tcx> { } } +impl<'tcx> HasX86AbiOpt for Builder<'_, '_, 'tcx> { + fn x86_abi_opt(&self) -> X86Abi { + self.cx.x86_abi_opt() + } +} + pub trait ToGccComp { fn to_gcc_comparison(&self) -> ComparisonOp; } diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 7cb49bf79913..707b35967a6d 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -19,7 +19,9 @@ use rustc_session::Session; use rustc_span::source_map::respan; use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx}; -use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, TlsModel, WasmCAbi}; +use rustc_target::spec::{ + HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, Target, TlsModel, WasmCAbi, X86Abi, +}; use crate::callee::get_fn; use crate::common::SignType; @@ -538,6 +540,12 @@ impl<'gcc, 'tcx> HasWasmCAbiOpt for CodegenCx<'gcc, 'tcx> { } } +impl<'gcc, 'tcx> HasX86AbiOpt for CodegenCx<'gcc, 'tcx> { + fn x86_abi_opt(&self) -> X86Abi { + X86Abi { regparm: self.tcx.sess.opts.unstable_opts.regparm } + } +} + impl<'gcc, 'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'gcc, 'tcx> { #[inline] fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 3189620e969d..d3762e739db8 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -836,6 +836,7 @@ fn test_unstable_options_tracking_hash() { tracked!(profile_emit, Some(PathBuf::from("abc"))); tracked!(profile_sample_use, Some(PathBuf::from("abc"))); tracked!(profiler_runtime, "abc".to_string()); + tracked!(regparm, Some(3)); tracked!(relax_elf_relocations, Some(true)); tracked!(remap_cwd_prefix, Some(PathBuf::from("abc"))); tracked!(sanitizer, SanitizerSet::ADDRESS); diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 6c12b691c26c..99a4cb56dd36 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -21,7 +21,9 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use rustc_target::abi::call::FnAbi; use rustc_target::abi::{FieldIdx, TyAbiInterface, VariantIdx, call}; use rustc_target::spec::abi::Abi as SpecAbi; -use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, PanicStrategy, Target, WasmCAbi}; +use rustc_target::spec::{ + HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, PanicStrategy, Target, WasmCAbi, X86Abi, +}; use tracing::debug; use {rustc_abi as abi, rustc_hir as hir}; @@ -544,6 +546,12 @@ impl<'tcx> HasWasmCAbiOpt for TyCtxt<'tcx> { } } +impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> { + fn x86_abi_opt(&self) -> X86Abi { + X86Abi { regparm: self.sess.opts.unstable_opts.regparm } + } +} + impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { @@ -595,6 +603,12 @@ impl<'tcx> HasWasmCAbiOpt for LayoutCx<'tcx> { } } +impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> { + fn x86_abi_opt(&self) -> X86Abi { + self.calc.cx.x86_abi_opt() + } +} + impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.calc.cx diff --git a/compiler/rustc_session/messages.ftl b/compiler/rustc_session/messages.ftl index 1816d1278fe2..893c532f1fbb 100644 --- a/compiler/rustc_session/messages.ftl +++ b/compiler/rustc_session/messages.ftl @@ -136,3 +136,6 @@ session_unsupported_crate_type_for_target = dropping unsupported crate type `{$crate_type}` for target `{$target_triple}` session_unsupported_dwarf_version = requested DWARF version {$dwarf_version} is greater than 5 + +session_unsupported_regparm = `-Zregparm={$regparm}` is unsupported (valid values 0-3) +session_unsupported_regparm_arch = `-Zregparm=N` is only supported on x86 diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index dbb74d1e2446..20e8fb38b88c 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -485,6 +485,16 @@ pub(crate) struct FunctionReturnRequiresX86OrX8664; #[diag(session_function_return_thunk_extern_requires_non_large_code_model)] pub(crate) struct FunctionReturnThunkExternRequiresNonLargeCodeModel; +#[derive(Diagnostic)] +#[diag(session_unsupported_regparm)] +pub(crate) struct UnsupportedRegparm { + pub(crate) regparm: u32, +} + +#[derive(Diagnostic)] +#[diag(session_unsupported_regparm_arch)] +pub(crate) struct UnsupportedRegparmArch; + #[derive(Diagnostic)] #[diag(session_failed_to_create_profiler)] pub(crate) struct FailedToCreateProfiler { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index f9964b59a941..f4a9d4bf92cb 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2000,6 +2000,10 @@ options! { "enable queries of the dependency graph for regression testing (default: no)"), randomize_layout: bool = (false, parse_bool, [TRACKED], "randomize the layout of types (default: no)"), + regparm: Option = (None, parse_opt_number, [TRACKED], + "On x86-32 targets, setting this to N causes the compiler to pass N arguments \ + in registers EAX, EDX, and ECX instead of on the stack.\ + It is UNSOUND to link together crates that use different values for this flag!"), relax_elf_relocations: Option = (None, parse_opt_bool, [TRACKED], "whether ELF relocations can be relaxed"), remap_cwd_prefix: Option = (None, parse_opt_pathbuf, [TRACKED], diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 27879d817b20..1963cf4eb7c0 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1337,6 +1337,15 @@ fn validate_commandline_args_with_session_available(sess: &Session) { } } + if let Some(regparm) = sess.opts.unstable_opts.regparm { + if regparm > 3 { + sess.dcx().emit_err(errors::UnsupportedRegparm { regparm }); + } + if sess.target.arch != "x86" { + sess.dcx().emit_err(errors::UnsupportedRegparmArch); + } + } + // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is // kept as a `match` to force a change if new ones are added, even if we currently only support // `thunk-extern` like Clang. diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 832246495bc9..07ee3f892b70 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -6,7 +6,7 @@ use rustc_macros::HashStable_Generic; use rustc_span::Symbol; use crate::abi::{self, Abi, Align, HasDataLayout, Size, TyAbiInterface, TyAndLayout}; -use crate::spec::{self, HasTargetSpec, HasWasmCAbiOpt, WasmCAbi}; +use crate::spec::{self, HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, WasmCAbi}; mod aarch64; mod amdgpu; @@ -631,7 +631,7 @@ impl<'a, Ty> FnAbi<'a, Ty> { ) -> Result<(), AdjustForForeignAbiError> where Ty: TyAbiInterface<'a, C> + Copy, - C: HasDataLayout + HasTargetSpec + HasWasmCAbiOpt, + C: HasDataLayout + HasTargetSpec + HasWasmCAbiOpt + HasX86AbiOpt, { if abi == spec::abi::Abi::X86Interrupt { if let Some(arg) = self.args.first_mut() { @@ -643,14 +643,18 @@ impl<'a, Ty> FnAbi<'a, Ty> { let spec = cx.target_spec(); match &spec.arch[..] { "x86" => { - let flavor = if let spec::abi::Abi::Fastcall { .. } - | spec::abi::Abi::Vectorcall { .. } = abi - { - x86::Flavor::FastcallOrVectorcall - } else { - x86::Flavor::General + let (flavor, regparm) = match abi { + spec::abi::Abi::Fastcall { .. } | spec::abi::Abi::Vectorcall { .. } => { + (x86::Flavor::FastcallOrVectorcall, None) + } + spec::abi::Abi::C { .. } + | spec::abi::Abi::Cdecl { .. } + | spec::abi::Abi::Stdcall { .. } => { + (x86::Flavor::General, cx.x86_abi_opt().regparm) + } + _ => (x86::Flavor::General, None), }; - x86::compute_abi_info(cx, self, flavor); + x86::compute_abi_info(cx, self, x86::X86Options { flavor, regparm }); } "x86_64" => match abi { spec::abi::Abi::SysV64 { .. } => x86_64::compute_abi_info(cx, self), @@ -716,6 +720,28 @@ impl<'a, Ty> FnAbi<'a, Ty> { Ok(()) } + + pub fn fill_inregs_for_rust_abi(&mut self, cx: &C) + where + Ty: TyAbiInterface<'a, C> + Copy, + C: HasTargetSpec + HasX86AbiOpt, + { + let spec = cx.target_spec(); + match &spec.arch[..] { + "x86" => { + x86::fill_inregs( + cx, + self, + x86::X86Options { + flavor: x86::Flavor::General, + regparm: cx.x86_abi_opt().regparm, + }, + true, + ); + } + _ => {} + } + } } impl FromStr for Conv { diff --git a/compiler/rustc_target/src/callconv/x86.rs b/compiler/rustc_target/src/callconv/x86.rs index d9af83d3205b..40c3e7a891a0 100644 --- a/compiler/rustc_target/src/callconv/x86.rs +++ b/compiler/rustc_target/src/callconv/x86.rs @@ -8,7 +8,12 @@ pub(crate) enum Flavor { FastcallOrVectorcall, } -pub(crate) fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, flavor: Flavor) +pub(crate) struct X86Options { + pub flavor: Flavor, + pub regparm: Option, +} + +pub(crate) fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, opts: X86Options) where Ty: TyAbiInterface<'a, C> + Copy, C: HasDataLayout + HasTargetSpec, @@ -128,58 +133,77 @@ where } } - if flavor == Flavor::FastcallOrVectorcall { - // Mark arguments as InReg like clang does it, - // so our fastcall/vectorcall is compatible with C/C++ fastcall/vectorcall. + fill_inregs(cx, fn_abi, opts, false); +} - // Clang reference: lib/CodeGen/TargetInfo.cpp - // See X86_32ABIInfo::shouldPrimitiveUseInReg(), X86_32ABIInfo::updateFreeRegs() +pub(crate) fn fill_inregs<'a, Ty, C>( + cx: &C, + fn_abi: &mut FnAbi<'a, Ty>, + opts: X86Options, + rust_abi: bool, +) where + Ty: TyAbiInterface<'a, C> + Copy, +{ + if opts.flavor != Flavor::FastcallOrVectorcall && opts.regparm.is_none_or(|x| x == 0) { + return; + } + // Mark arguments as InReg like clang does it, + // so our fastcall/vectorcall is compatible with C/C++ fastcall/vectorcall. - // IsSoftFloatABI is only set to true on ARM platforms, - // which in turn can't be x86? + // Clang reference: lib/CodeGen/TargetInfo.cpp + // See X86_32ABIInfo::shouldPrimitiveUseInReg(), X86_32ABIInfo::updateFreeRegs() - let mut free_regs = 2; + // IsSoftFloatABI is only set to true on ARM platforms, + // which in turn can't be x86? - for arg in fn_abi.args.iter_mut() { - let attrs = match arg.mode { - PassMode::Ignore - | PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ } => { - continue; - } - PassMode::Direct(ref mut attrs) => attrs, - PassMode::Pair(..) - | PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } - | PassMode::Cast { .. } => { - unreachable!("x86 shouldn't be passing arguments by {:?}", arg.mode) - } - }; + // 2 for fastcall/vectorcall, regparm limited by 3 otherwise + let mut free_regs = opts.regparm.unwrap_or(2).into(); - // At this point we know this must be a primitive of sorts. - let unit = arg.layout.homogeneous_aggregate(cx).unwrap().unit().unwrap(); - assert_eq!(unit.size, arg.layout.size); - if unit.kind == RegKind::Float { + // For types generating PassMode::Cast, InRegs will not be set. + // Maybe, this is a FIXME + let has_casts = fn_abi.args.iter().any(|arg| matches!(arg.mode, PassMode::Cast { .. })); + if has_casts && rust_abi { + return; + } + + for arg in fn_abi.args.iter_mut() { + let attrs = match arg.mode { + PassMode::Ignore | PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ } => { continue; } - - let size_in_regs = (arg.layout.size.bits() + 31) / 32; - - if size_in_regs == 0 { - continue; + PassMode::Direct(ref mut attrs) => attrs, + PassMode::Pair(..) + | PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } + | PassMode::Cast { .. } => { + unreachable!("x86 shouldn't be passing arguments by {:?}", arg.mode) } + }; - if size_in_regs > free_regs { - break; - } + // At this point we know this must be a primitive of sorts. + let unit = arg.layout.homogeneous_aggregate(cx).unwrap().unit().unwrap(); + assert_eq!(unit.size, arg.layout.size); + if matches!(unit.kind, RegKind::Float | RegKind::Vector) { + continue; + } - free_regs -= size_in_regs; + let size_in_regs = (arg.layout.size.bits() + 31) / 32; - if arg.layout.size.bits() <= 32 && unit.kind == RegKind::Integer { - attrs.set(ArgAttribute::InReg); - } + if size_in_regs == 0 { + continue; + } - if free_regs == 0 { - break; - } + if size_in_regs > free_regs { + break; + } + + free_regs -= size_in_regs; + + if arg.layout.size.bits() <= 32 && unit.kind == RegKind::Integer { + attrs.set(ArgAttribute::InReg); + } + + if free_regs == 0 { + break; } } } diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 82e11a3afce3..812edf14070b 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -2096,6 +2096,18 @@ pub trait HasWasmCAbiOpt { fn wasm_c_abi_opt(&self) -> WasmCAbi; } +/// x86 (32-bit) abi options. +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub struct X86Abi { + /// On x86-32 targets, the regparm N causes the compiler to pass arguments + /// in registers EAX, EDX, and ECX instead of on the stack. + pub regparm: Option, +} + +pub trait HasX86AbiOpt { + fn x86_abi_opt(&self) -> X86Abi; +} + type StaticCow = Cow<'static, T>; /// Optional aspects of a target specification. diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index deda16b76b58..661f140e6970 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -797,6 +797,9 @@ fn fn_abi_adjust_for_abi<'tcx>( for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() { fixup(arg, Some(arg_idx)); } + if tcx.sess.target.arch == "x86" { + fn_abi.fill_inregs_for_rust_abi(cx); + } } else { fn_abi .adjust_for_foreign_abi(cx, abi) diff --git a/src/doc/unstable-book/src/compiler-flags/regparm.md b/src/doc/unstable-book/src/compiler-flags/regparm.md new file mode 100644 index 000000000000..a054d55cd8b6 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/regparm.md @@ -0,0 +1,20 @@ +# `regparm` + +The tracking issue for this feature is: https://github.com/rust-lang/rust/issues/131749. + +------------------------ + +Option -Zregparm=N causes the compiler to pass N arguments +in registers EAX, EDX, and ECX instead of on the stack. +It is UNSOUND to link together crates that use different values for this flag. +It is only supported on `x86`. + +It is equivalent to [Clang]'s and [GCC]'s `-mregparm`. + +Supported values for this option are 0-3. + +[Clang]: https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mregparm +[GCC]: https://gcc.gnu.org/onlinedocs/gcc/x86-Function-Attributes.html#index-regparm-function-attribute_002c-x86 + +Implementation details: +For eligible arguments, llvm `inreg` attribute is set. diff --git a/tests/codegen/regparm-inreg-rust-cc.rs b/tests/codegen/regparm-inreg-rust-cc.rs new file mode 100644 index 000000000000..a2d8d5349ea0 --- /dev/null +++ b/tests/codegen/regparm-inreg-rust-cc.rs @@ -0,0 +1,53 @@ +// Checks how `regparm` flag works with Rust calling convention with array types. +// When there is a small array type in signature (casted to combined int type), +// inregs will not be set. PassMode::Cast is unsupported. +// x86 only. + +//@ compile-flags: --target i686-unknown-linux-gnu -O -C no-prepopulate-passes +//@ needs-llvm-components: x86 + +//@ revisions:regparm0 regparm1 regparm2 regparm3 +//@[regparm0] compile-flags: -Zregparm=0 +//@[regparm1] compile-flags: -Zregparm=1 +//@[regparm2] compile-flags: -Zregparm=2 +//@[regparm3] compile-flags: -Zregparm=3 + +#![crate_type = "lib"] +#![no_core] +#![feature(no_core, lang_items)] + +#[lang = "sized"] +trait Sized {} +#[lang = "copy"] +trait Copy {} + +pub mod tests { + // CHECK: @f1(i16 %0, i32 noundef %_2, i32 noundef %_3) + #[no_mangle] + pub extern "Rust" fn f1(_: [u8; 2], _: i32, _: i32) {} + + // CHECK: @f2(i24 %0, i32 noundef %_2, i32 noundef %_3) + #[no_mangle] + pub extern "Rust" fn f2(_: [u8; 3], _: i32, _: i32) {} + + // regparm0: @f3(ptr {{.*}} %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f3(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm2: @f3(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + // regparm3: @f3(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "Rust" fn f3(_: [u8; 7], _: i32, _: i32) {} + + // regparm0: @f4(ptr {{.*}} %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f4(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm2: @f4(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + // regparm3: @f4(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "Rust" fn f4(_: [u8; 11], _: i32, _: i32) {} + + // regparm0: @f5(ptr {{.*}} %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f5(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm2: @f5(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + // regparm3: @f5(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "Rust" fn f5(_: [u8; 33], _: i32, _: i32) {} +} diff --git a/tests/codegen/regparm-inreg.rs b/tests/codegen/regparm-inreg.rs new file mode 100644 index 000000000000..ce87a66d0e91 --- /dev/null +++ b/tests/codegen/regparm-inreg.rs @@ -0,0 +1,133 @@ +// Checks how `regparm` flag works with different calling conventions: +// marks function arguments as "inreg" like the C/C++ compilers for the platforms. +// x86 only. + +//@ compile-flags: --target i686-unknown-linux-gnu -O -C no-prepopulate-passes +//@ needs-llvm-components: x86 +//@ only-x86 + +//@ revisions:regparm0 regparm1 regparm2 regparm3 +//@[regparm0] compile-flags: -Zregparm=0 +//@[regparm1] compile-flags: -Zregparm=1 +//@[regparm2] compile-flags: -Zregparm=2 +//@[regparm3] compile-flags: -Zregparm=3 + +#![crate_type = "lib"] +#![no_core] +#![feature(no_core, lang_items, repr_simd)] +#[lang = "sized"] +trait Sized {} +#[lang = "copy"] +trait Copy {} + +pub mod tests { + // regparm doesn't work for "fastcall" calling conv (only 2 inregs) + // CHECK: @f1(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) + #[no_mangle] + pub extern "fastcall" fn f1(_: i32, _: i32, _: i32) {} + + // regparm0: @f2(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f2(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm2: @f2(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm3: @f2(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "Rust" fn f2(_: i32, _: i32, _: i32) {} + + // regparm0: @f3(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f3(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm2: @f3(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm3: @f3(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "C" fn f3(_: i32, _: i32, _: i32) {} + + // regparm0: @f4(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f4(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm2: @f4(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm3: @f4(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "cdecl" fn f4(_: i32, _: i32, _: i32) {} + + // regparm0: @f5(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm1: @f5(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3) + // regparm2: @f5(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) + // regparm3: @f5(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) + #[no_mangle] + pub extern "stdcall" fn f5(_: i32, _: i32, _: i32) {} + + // regparm doesn't work for thiscall + // CHECK: @f6(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) + #[no_mangle] + pub extern "thiscall" fn f6(_: i32, _: i32, _: i32) {} + + struct S1 { + x1: i32, + } + // regparm0: @f7(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3, i32 noundef %_4) + // regparm1: @f7(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3, i32 noundef %_4) + // regparm2: @f7(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3, i32 noundef %_4) + // regparm3: @f7(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 inreg noundef %_3, + // regparm3-SAME: i32 noundef %_4) + #[no_mangle] + pub extern "C" fn f7(_: i32, _: i32, _: S1, _: i32) {} + + #[repr(C)] + struct S2 { + x1: i32, + x2: i32, + } + // regparm0: @f8(i32 noundef %_1, i32 noundef %_2, ptr {{.*}} %_3, i32 noundef %_4) + // regparm1: @f8(i32 inreg noundef %_1, i32 noundef %_2, ptr {{.*}} %_3, i32 noundef %_4) + // regparm2: @f8(i32 inreg noundef %_1, i32 inreg noundef %_2, ptr {{.*}} %_3, i32 noundef %_4) + // regparm3: @f8(i32 inreg noundef %_1, i32 inreg noundef %_2, ptr {{.*}} %_3, + // regparm3-SAME: i32 inreg noundef %_4) + #[no_mangle] + pub extern "C" fn f8(_: i32, _: i32, _: S2, _: i32) {} + + // regparm0: @f9(i1 noundef zeroext %_1, i16 noundef signext %_2, i64 noundef %_3, + // regparm0-SAME: i128 noundef %_4) + // regparm1: @f9(i1 inreg noundef zeroext %_1, i16 noundef signext %_2, i64 noundef %_3, + // regparm1-SAME: i128 noundef %_4) + // regparm2: @f9(i1 inreg noundef zeroext %_1, i16 inreg noundef signext %_2, i64 noundef %_3, + // regparm2-SAME: i128 noundef %_4) + // regparm3: @f9(i1 inreg noundef zeroext %_1, i16 inreg noundef signext %_2, i64 noundef %_3, + // regparm3-SAME: i128 noundef %_4) + #[no_mangle] + pub extern "C" fn f9(_: bool, _: i16, _: i64, _: u128) {} + + // regparm0: @f10(float noundef %_1, double noundef %_2, i1 noundef zeroext %_3, + // regparm0-SAME: i16 noundef signext %_4) + // regparm1: @f10(float noundef %_1, double noundef %_2, i1 inreg noundef zeroext %_3, + // regparm1-SAME: i16 noundef signext %_4) + // regparm2: @f10(float noundef %_1, double noundef %_2, i1 inreg noundef zeroext %_3, + // regparm2-SAME: i16 inreg noundef signext %_4) + // regparm3: @f10(float noundef %_1, double noundef %_2, i1 inreg noundef zeroext %_3, + // regparm3-SAME: i16 inreg noundef signext %_4) + #[no_mangle] + pub extern "C" fn f10(_: f32, _: f64, _: bool, _: i16) {} + + #[allow(non_camel_case_types)] + #[repr(simd)] + pub struct __m128([f32; 4]); + + // regparm0: @f11(i32 noundef %_1, <4 x float> %_2, i32 noundef %_3, i32 noundef %_4) + // regparm1: @f11(i32 inreg noundef %_1, <4 x float> %_2, i32 noundef %_3, i32 noundef %_4) + // regparm2: @f11(i32 inreg noundef %_1, <4 x float> %_2, i32 inreg noundef %_3, + // regparm2-SAME: i32 noundef %_4) + // regparm3: @f11(i32 inreg noundef %_1, <4 x float> %_2, i32 inreg noundef %_3, + // regparm3-SAME: i32 inreg noundef %_4) + #[no_mangle] + pub extern "C" fn f11(_: i32, _: __m128, _: i32, _: i32) {} + + #[allow(non_camel_case_types)] + #[repr(simd)] + pub struct __m256([f32; 8]); + + // regparm0: @f12(i32 noundef %_1, <8 x float> %_2, i32 noundef %_3, i32 noundef %_4) + // regparm1: @f12(i32 inreg noundef %_1, <8 x float> %_2, i32 noundef %_3, i32 noundef %_4) + // regparm2: @f12(i32 inreg noundef %_1, <8 x float> %_2, i32 inreg noundef %_3, + // regparm2-SAME: i32 noundef %_4) + // regparm3: @f12(i32 inreg noundef %_1, <8 x float> %_2, i32 inreg noundef %_3, + // regparm3-SAME: i32 inreg noundef %_4) + #[no_mangle] + pub extern "C" fn f12(_: i32, _: __m256, _: i32, _: i32) {} +} diff --git a/tests/ui/invalid-compile-flags/regparm/regparm-valid-values.regparm4.stderr b/tests/ui/invalid-compile-flags/regparm/regparm-valid-values.regparm4.stderr new file mode 100644 index 000000000000..8fc04adf57f5 --- /dev/null +++ b/tests/ui/invalid-compile-flags/regparm/regparm-valid-values.regparm4.stderr @@ -0,0 +1,4 @@ +error: `-Zregparm=4` is unsupported (valid values 0-3) + +error: aborting due to 1 previous error + diff --git a/tests/ui/invalid-compile-flags/regparm/regparm-valid-values.rs b/tests/ui/invalid-compile-flags/regparm/regparm-valid-values.rs new file mode 100644 index 000000000000..b548d678520b --- /dev/null +++ b/tests/ui/invalid-compile-flags/regparm/regparm-valid-values.rs @@ -0,0 +1,24 @@ +//@ revisions: regparm0 regparm1 regparm2 regparm3 regparm4 + +//@ needs-llvm-components: x86 +//@ compile-flags: --target i686-unknown-linux-gnu + +//@[regparm0] check-pass +//@[regparm0] compile-flags: -Zregparm=0 + +//@[regparm1] check-pass +//@[regparm1] compile-flags: -Zregparm=1 + +//@[regparm2] check-pass +//@[regparm2] compile-flags: -Zregparm=2 + +//@[regparm3] check-pass +//@[regparm3] compile-flags: -Zregparm=3 + +//@[regparm4] check-fail +//@[regparm4] compile-flags: -Zregparm=4 +//@[regparm4] error-pattern: `-Zregparm=4` is unsupported (valid values 0-3) + +#![feature(no_core)] +#![no_core] +#![no_main] diff --git a/tests/ui/invalid-compile-flags/regparm/requires-x86.aarch64.stderr b/tests/ui/invalid-compile-flags/regparm/requires-x86.aarch64.stderr new file mode 100644 index 000000000000..2433519f803c --- /dev/null +++ b/tests/ui/invalid-compile-flags/regparm/requires-x86.aarch64.stderr @@ -0,0 +1,4 @@ +error: `-Zregparm=N` is only supported on x86 + +error: aborting due to 1 previous error + diff --git a/tests/ui/invalid-compile-flags/regparm/requires-x86.rs b/tests/ui/invalid-compile-flags/regparm/requires-x86.rs new file mode 100644 index 000000000000..ce6e437fb476 --- /dev/null +++ b/tests/ui/invalid-compile-flags/regparm/requires-x86.rs @@ -0,0 +1,21 @@ +//@ revisions: x86 x86_64 aarch64 + +//@ compile-flags: -Zregparm=3 + +//@[x86] check-pass +//@[x86] needs-llvm-components: x86 +//@[x86] compile-flags: --target i686-unknown-linux-gnu + +//@[x86_64] check-fail +//@[x86_64] needs-llvm-components: x86 +//@[x86_64] compile-flags: --target x86_64-unknown-linux-gnu +//@[x86_64] error-pattern: `-Zregparm=N` is only supported on x86 + +//@[aarch64] check-fail +//@[aarch64] needs-llvm-components: aarch64 +//@[aarch64] compile-flags: --target aarch64-unknown-linux-gnu +//@[aarch64] error-pattern: `-Zregparm=N` is only supported on x86 + +#![feature(no_core)] +#![no_core] +#![no_main] diff --git a/tests/ui/invalid-compile-flags/regparm/requires-x86.x86_64.stderr b/tests/ui/invalid-compile-flags/regparm/requires-x86.x86_64.stderr new file mode 100644 index 000000000000..2433519f803c --- /dev/null +++ b/tests/ui/invalid-compile-flags/regparm/requires-x86.x86_64.stderr @@ -0,0 +1,4 @@ +error: `-Zregparm=N` is only supported on x86 + +error: aborting due to 1 previous error + From 67081dbb14dece75707722c28e778ddd7f442a6c Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Thu, 17 Oct 2024 18:18:01 -0700 Subject: [PATCH 025/366] Update triagebot.toml Update the list of reviewers after updating the team. --- triagebot.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/triagebot.toml b/triagebot.toml index 33dcbfa55a4f..a23fc9725396 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1072,7 +1072,7 @@ project-const-traits = [ project-stable-mir = [ "@celinval", "@oli-obk", - "@ouz-a", + "@scottmcm", ] project-exploit-mitigations = [ From a4ffeb026326cf61b24589df742c2b1eb372b7e2 Mon Sep 17 00:00:00 2001 From: Juniper Tyree <50025784+juntyr@users.noreply.github.com> Date: Fri, 18 Oct 2024 10:02:28 +0300 Subject: [PATCH 026/366] Add WASM | WASI | Emscripten groups to triagebot.toml --- triagebot.toml | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index 33dcbfa55a4f..c033fb7f39f6 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -135,6 +135,43 @@ In case it's useful, here are some [instructions] for tackling these sorts of is """ label = "O-rfl" +[ping.wasm] +alias = ["webassembly"] +message = """\ +Hey WASM notification group! This issue or PR could use some WebAssembly-specific +guidance. Could one of you weigh in? Thanks <3 + +(In case it's useful, here are some [instructions] for tackling these sorts of +issues). + +[instructions]: https://rustc-dev-guide.rust-lang.org/notification-groups/wasm.html +""" +label = "O-wasm" + +[ping.wasi] +message = """\ +Hey WASI notification group! This issue or PR could use some WASI-specific guidance. +Could one of you weigh in? Thanks <3 + +(In case it's useful, here are some [instructions] for tackling these sorts of +issues). + +[instructions]: https://rustc-dev-guide.rust-lang.org/notification-groups/wasi.html +""" +label = "O-wasi" + +[ping.emscripten] +message = """\ +Hey Emscripten notification group! This issue or PR could use some Emscripten-specific +guidance. Could one of you weigh in? Thanks <3 + +(In case it's useful, here are some [instructions] for tackling these sorts of +issues). + +[instructions]: https://rustc-dev-guide.rust-lang.org/notification-groups/emscripten.html +""" +label = "O-emscripten" + [prioritize] label = "I-prioritize" From 8df5f37e1c48f950278f1213c475265caa5a0770 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 18 Oct 2024 10:56:23 +0200 Subject: [PATCH 027/366] fix: Fix CI running analysis-stats incorrectly against the standard libraries --- src/tools/rust-analyzer/.github/workflows/ci.yaml | 6 +++--- .../rust-analyzer/crates/project-model/src/tests.rs | 3 --- .../crates/rust-analyzer/src/cli/analysis_stats.rs | 9 +++++++-- .../rust-analyzer/crates/rust-analyzer/src/cli/flags.rs | 3 +++ 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index 6d3e488bb082..5cf4a8fd4393 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -104,11 +104,11 @@ jobs: if: matrix.os == 'ubuntu-latest' run: target/${{ matrix.target }}/debug/rust-analyzer analysis-stats . - - name: Run analysis-stats on rust std library + - name: Run analysis-stats on the rust standard libraries if: matrix.os == 'ubuntu-latest' env: - RUSTC_BOOTSTRAP: 1 - run: target/${{ matrix.target }}/debug/rust-analyzer analysis-stats --with-deps $(rustc --print sysroot)/lib/rustlib/src/rust/library/std + RUSTC_BOOTSTRAP: 1 + run: target/${{ matrix.target }}/debug/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/ - name: clippy if: matrix.os == 'windows-latest' diff --git a/src/tools/rust-analyzer/crates/project-model/src/tests.rs b/src/tools/rust-analyzer/crates/project-model/src/tests.rs index 5099697a6963..ef115494a888 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/tests.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/tests.rs @@ -222,8 +222,6 @@ fn rust_project_is_proc_macro_has_proc_macro_dep() { } #[test] -// FIXME Remove the ignore -#[ignore = "requires nightly until the sysroot ships a cargo workspace for library on stable"] fn smoke_test_real_sysroot_cargo() { let file_map = &mut FxHashMap::::default(); let meta: Metadata = get_test_json_file("hello-world-metadata.json"); @@ -235,7 +233,6 @@ fn smoke_test_real_sysroot_cargo() { &Default::default(), ); assert!(matches!(sysroot.mode(), SysrootMode::Workspace(_))); - let project_workspace = ProjectWorkspace { kind: ProjectWorkspaceKind::Cargo { cargo: cargo_workspace, diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs index c2164614274c..51c81a0d1a64 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -6,6 +6,7 @@ use std::{ time::{SystemTime, UNIX_EPOCH}, }; +use cfg::{CfgAtom, CfgDiff}; use hir::{ db::{DefDatabase, ExpandDatabase, HirDatabase}, Adt, AssocItem, Crate, DefWithBody, HasSource, HirDisplay, HirFileIdExt, ImportPathConfig, @@ -31,7 +32,7 @@ use itertools::Itertools; use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice}; use oorandom::Rand32; use profile::{Bytes, StopWatch}; -use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace, RustLibSource}; +use project_model::{CargoConfig, CfgOverrides, ProjectManifest, ProjectWorkspace, RustLibSource}; use rayon::prelude::*; use rustc_hash::{FxHashMap, FxHashSet}; use syntax::{AstNode, SyntaxNode}; @@ -65,7 +66,11 @@ impl flags::AnalysisStats { false => Some(RustLibSource::Discover), }, all_targets: true, - set_test: true, + set_test: !self.no_test, + cfg_overrides: CfgOverrides { + global: CfgDiff::new(vec![CfgAtom::Flag(hir::sym::miri.clone())], vec![]).unwrap(), + selective: Default::default(), + }, ..Default::default() }; let no_progress = &|_| (); diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/flags.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/flags.rs index 60d621b214ad..ff24602144a9 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/flags.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/flags.rs @@ -71,6 +71,8 @@ xflags::xflags! { optional --with-deps /// Don't load sysroot crates (`std`, `core` & friends). optional --no-sysroot + /// Don't set #[cfg(test)]. + optional --no-test /// Don't run build scripts or load `OUT_DIR` values by running `cargo check` before analysis. optional --disable-build-scripts @@ -233,6 +235,7 @@ pub struct AnalysisStats { pub only: Option, pub with_deps: bool, pub no_sysroot: bool, + pub no_test: bool, pub disable_build_scripts: bool, pub disable_proc_macros: bool, pub proc_macro_srv: Option, From c9f2a0e94bb2bdd5b4dadb6d8de842bd8309670d Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 18 Oct 2024 12:41:14 +0200 Subject: [PATCH 028/366] internal: Add more trivially `Sized` types to `is_sized` check --- .../rust-analyzer/crates/hir-ty/src/infer/unify.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/unify.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/unify.rs index 7300453ff001..e4881d752013 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/unify.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/unify.rs @@ -917,9 +917,19 @@ impl<'a> InferenceTable<'a> { /// Check if given type is `Sized` or not pub(crate) fn is_sized(&mut self, ty: &Ty) -> bool { // Early return for some obvious types - if matches!(ty.kind(Interner), TyKind::Scalar(..) | TyKind::Ref(..) | TyKind::Raw(..)) { + if matches!( + ty.kind(Interner), + TyKind::Scalar(..) + | TyKind::Ref(..) + | TyKind::Raw(..) + | TyKind::Never + | TyKind::FnDef(..) + | TyKind::Array(..) + | TyKind::Function(_) + ) { return true; } + if let Some((AdtId::StructId(id), subst)) = ty.as_adt() { let struct_data = self.db.struct_data(id); if let Some((last_field, _)) = struct_data.variant_data.fields().iter().last() { From db6824a447afdd162dd0791c641a360bb7f3b4d1 Mon Sep 17 00:00:00 2001 From: David Barsky Date: Thu, 17 Oct 2024 11:53:19 -0400 Subject: [PATCH 029/366] internal: fix lldb-dap unconditionally calling rustc From f01ebd6d13f4686817365c4304cacbce8d1e6cf2 Mon Sep 17 00:00:00 2001 From: David Barsky Date: Thu, 17 Oct 2024 13:55:30 -0400 Subject: [PATCH 030/366] vscode: update some dependencies --- src/tools/rust-analyzer/Cargo.lock | 10 +- .../editors/code/package-lock.json | 1539 +++++++++++++++-- .../rust-analyzer/editors/code/package.json | 4 +- 3 files changed, 1408 insertions(+), 145 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index 4a6da47a47df..a99294033b44 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -731,7 +731,7 @@ dependencies = [ "indexmap", "itertools", "limit", - "line-index 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "line-index 0.1.1", "memchr", "nohash-hasher", "parser", @@ -940,19 +940,19 @@ version = "0.0.0" [[package]] name = "line-index" version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67d61795376ae2683928c218fda7d7d7db136fd38c06b7552904667f0d55580a" dependencies = [ "nohash-hasher", - "oorandom", "text-size", ] [[package]] name = "line-index" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67d61795376ae2683928c218fda7d7d7db136fd38c06b7552904667f0d55580a" +version = "0.1.2" dependencies = [ "nohash-hasher", + "oorandom", "text-size", ] diff --git a/src/tools/rust-analyzer/editors/code/package-lock.json b/src/tools/rust-analyzer/editors/code/package-lock.json index 7de757631777..10b633511d3e 100644 --- a/src/tools/rust-analyzer/editors/code/package-lock.json +++ b/src/tools/rust-analyzer/editors/code/package-lock.json @@ -22,14 +22,14 @@ "@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/parser": "^6.0.0", "@vscode/test-electron": "^2.3.8", - "@vscode/vsce": "^2.19.0", + "@vscode/vsce": "^3.0.0", "esbuild": "^0.18.12", "eslint": "^8.44.0", "eslint-config-prettier": "^8.8.0", "ovsx": "^0.8.2", "prettier": "^3.0.0", "tslib": "^2.6.0", - "typescript": "^5.1.6" + "typescript": "^5.6.0" }, "engines": { "vscode": "^1.78.0" @@ -44,6 +44,218 @@ "node": ">=0.10.0" } }, + "node_modules/@azure/abort-controller": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", + "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/core-auth": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.9.0.tgz", + "integrity": "sha512-FPwHpZywuyasDSLMqJ6fhbOK3TqUdviZNF8OqRGA4W5Ewib2lEEZ+pBsYcBa88B2NGO/SEnYPGhyBqNlE8ilSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "@azure/core-util": "^1.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/core-client": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@azure/core-client/-/core-client-1.9.2.tgz", + "integrity": "sha512-kRdry/rav3fUKHl/aDLd/pDLcB+4pOFwPPTVEExuMyaI5r+JBbMWqRbCY1pn5BniDaU3lRxO9eaQ1AmSMehl/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "@azure/core-auth": "^1.4.0", + "@azure/core-rest-pipeline": "^1.9.1", + "@azure/core-tracing": "^1.0.0", + "@azure/core-util": "^1.6.1", + "@azure/logger": "^1.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/core-rest-pipeline": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.17.0.tgz", + "integrity": "sha512-62Vv8nC+uPId3j86XJ0WI+sBf0jlqTqPUFCBNrGtlaUeQUIXWV/D8GE5A1d+Qx8H7OQojn2WguC8kChD6v0shA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "@azure/core-auth": "^1.8.0", + "@azure/core-tracing": "^1.0.1", + "@azure/core-util": "^1.9.0", + "@azure/logger": "^1.0.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/core-rest-pipeline/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@azure/core-rest-pipeline/node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@azure/core-rest-pipeline/node_modules/https-proxy-agent": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", + "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@azure/core-tracing": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz", + "integrity": "sha512-UKTiEJPkWcESPYJz3X5uKRYyOcJD+4nYph+KpfdPRnQJVrZfk0KJgdnaAWKfhsBBtAf/D58Az4AvCJEmWgIBAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/core-util": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.11.0.tgz", + "integrity": "sha512-DxOSLua+NdpWoSqULhjDyAZTXFdP/LKkqtYuxxz1SCN289zk3OG8UOpnCQAz/tygyACBtWp/BoO72ptK7msY8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/identity": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@azure/identity/-/identity-4.5.0.tgz", + "integrity": "sha512-EknvVmtBuSIic47xkOqyNabAme0RYTw52BTMz8eBgU1ysTyMrD1uOoM+JdS0J/4Yfp98IBT3osqq3BfwSaNaGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "@azure/core-auth": "^1.9.0", + "@azure/core-client": "^1.9.2", + "@azure/core-rest-pipeline": "^1.17.0", + "@azure/core-tracing": "^1.0.0", + "@azure/core-util": "^1.11.0", + "@azure/logger": "^1.0.0", + "@azure/msal-browser": "^3.26.1", + "@azure/msal-node": "^2.15.0", + "events": "^3.0.0", + "jws": "^4.0.0", + "open": "^8.0.0", + "stoppable": "^1.1.0", + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/logger": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.4.tgz", + "integrity": "sha512-4IXXzcCdLdlXuCG+8UKEwLA1T1NHqUfanhXYHiQTn+6sfWCZXduqbtXDGceg3Ce5QxTGo7EqmbV6Bi+aqKuClQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@azure/msal-browser": { + "version": "3.26.1", + "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-3.26.1.tgz", + "integrity": "sha512-y78sr9g61aCAH9fcLO1um+oHFXc1/5Ap88RIsUSuzkm0BHzFnN+PXGaQeuM1h5Qf5dTnWNOd6JqkskkMPAhh7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/msal-common": "14.15.0" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-common": { + "version": "14.15.0", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-14.15.0.tgz", + "integrity": "sha512-ImAQHxmpMneJ/4S8BRFhjt1MZ3bppmpRPYYNyzeQPeFN288YKbb8TmmISQEbtfkQ1BPASvYZU5doIZOPBAqENQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-node": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-2.15.0.tgz", + "integrity": "sha512-gVPW8YLz92ZeCibQH2QUw96odJoiM3k/ZPH3f2HxptozmH6+OnyyvKXo/Egg39HAM230akarQKHf0W74UHlh0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/msal-common": "14.15.0", + "jsonwebtoken": "^9.0.0", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/@esbuild/android-arm": { "version": "0.18.12", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.18.12.tgz", @@ -496,6 +708,109 @@ "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", "dev": true }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -778,26 +1093,31 @@ } }, "node_modules/@vscode/vsce": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-2.19.0.tgz", - "integrity": "sha512-dAlILxC5ggOutcvJY24jxz913wimGiUrHaPkk16Gm9/PGFbz1YezWtrXsTKUtJws4fIlpX2UIlVlVESWq8lkfQ==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-3.1.1.tgz", + "integrity": "sha512-N62Ca9ElRPLUUzf7l9CeEBlLrYzFPRQq7huKk4pVW+LjIOSXfFIPudixn5QvZcz+yXDOh15IopI3K2o3y9666Q==", "dev": true, + "license": "MIT", "dependencies": { - "azure-devops-node-api": "^11.0.1", + "@azure/identity": "^4.1.0", + "@vscode/vsce-sign": "^2.0.0", + "azure-devops-node-api": "^12.5.0", "chalk": "^2.4.2", "cheerio": "^1.0.0-rc.9", - "commander": "^6.1.0", - "glob": "^7.0.6", + "cockatiel": "^3.1.2", + "commander": "^6.2.1", + "form-data": "^4.0.0", + "glob": "^11.0.0", "hosted-git-info": "^4.0.2", "jsonc-parser": "^3.2.0", "leven": "^3.1.0", - "markdown-it": "^12.3.2", + "markdown-it": "^14.1.0", "mime": "^1.3.4", "minimatch": "^3.0.3", "parse-semver": "^1.1.1", "read": "^1.0.7", - "semver": "^5.1.0", - "tmp": "^0.2.1", + "semver": "^7.5.2", + "tmp": "^0.2.3", "typed-rest-client": "^1.8.4", "url-join": "^4.0.1", "xml2js": "^0.5.0", @@ -808,12 +1128,157 @@ "vsce": "vsce" }, "engines": { - "node": ">= 14" + "node": ">= 20" }, "optionalDependencies": { "keytar": "^7.7.0" } }, + "node_modules/@vscode/vsce-sign": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign/-/vsce-sign-2.0.4.tgz", + "integrity": "sha512-0uL32egStKYfy60IqnynAChMTbL0oqpqk0Ew0YHiIb+fayuGZWADuIPHWUcY1GCnAA+VgchOPDMxnc2R3XGWEA==", + "dev": true, + "hasInstallScript": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optionalDependencies": { + "@vscode/vsce-sign-alpine-arm64": "2.0.2", + "@vscode/vsce-sign-alpine-x64": "2.0.2", + "@vscode/vsce-sign-darwin-arm64": "2.0.2", + "@vscode/vsce-sign-darwin-x64": "2.0.2", + "@vscode/vsce-sign-linux-arm": "2.0.2", + "@vscode/vsce-sign-linux-arm64": "2.0.2", + "@vscode/vsce-sign-linux-x64": "2.0.2", + "@vscode/vsce-sign-win32-arm64": "2.0.2", + "@vscode/vsce-sign-win32-x64": "2.0.2" + } + }, + "node_modules/@vscode/vsce-sign-alpine-arm64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-alpine-arm64/-/vsce-sign-alpine-arm64-2.0.2.tgz", + "integrity": "sha512-E80YvqhtZCLUv3YAf9+tIbbqoinWLCO/B3j03yQPbjT3ZIHCliKZlsy1peNc4XNZ5uIb87Jn0HWx/ZbPXviuAQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "alpine" + ] + }, + "node_modules/@vscode/vsce-sign-alpine-x64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-alpine-x64/-/vsce-sign-alpine-x64-2.0.2.tgz", + "integrity": "sha512-n1WC15MSMvTaeJ5KjWCzo0nzjydwxLyoHiMJHu1Ov0VWTZiddasmOQHekA47tFRycnt4FsQrlkSCTdgHppn6bw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "alpine" + ] + }, + "node_modules/@vscode/vsce-sign-darwin-arm64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-darwin-arm64/-/vsce-sign-darwin-arm64-2.0.2.tgz", + "integrity": "sha512-rz8F4pMcxPj8fjKAJIfkUT8ycG9CjIp888VY/6pq6cuI2qEzQ0+b5p3xb74CJnBbSC0p2eRVoe+WgNCAxCLtzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@vscode/vsce-sign-darwin-x64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-darwin-x64/-/vsce-sign-darwin-x64-2.0.2.tgz", + "integrity": "sha512-MCjPrQ5MY/QVoZ6n0D92jcRb7eYvxAujG/AH2yM6lI0BspvJQxp0o9s5oiAM9r32r9tkLpiy5s2icsbwefAQIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@vscode/vsce-sign-linux-arm": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-linux-arm/-/vsce-sign-linux-arm-2.0.2.tgz", + "integrity": "sha512-Fkb5jpbfhZKVw3xwR6t7WYfwKZktVGNXdg1m08uEx1anO0oUPUkoQRsNm4QniL3hmfw0ijg00YA6TrxCRkPVOQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/vsce-sign-linux-arm64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-linux-arm64/-/vsce-sign-linux-arm64-2.0.2.tgz", + "integrity": "sha512-Ybeu7cA6+/koxszsORXX0OJk9N0GgfHq70Wqi4vv2iJCZvBrOWwcIrxKjvFtwyDgdeQzgPheH5nhLVl5eQy7WA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/vsce-sign-linux-x64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-linux-x64/-/vsce-sign-linux-x64-2.0.2.tgz", + "integrity": "sha512-NsPPFVtLaTlVJKOiTnO8Cl78LZNWy0Q8iAg+LlBiCDEgC12Gt4WXOSs2pmcIjDYzj2kY4NwdeN1mBTaujYZaPg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/vsce-sign-win32-arm64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-win32-arm64/-/vsce-sign-win32-arm64-2.0.2.tgz", + "integrity": "sha512-wPs848ymZ3Ny+Y1Qlyi7mcT6VSigG89FWQnp2qRYCyMhdJxOpA4lDwxzlpL8fG6xC8GjQjGDkwbkWUcCobvksQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@vscode/vsce-sign-win32-x64": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-win32-x64/-/vsce-sign-win32-x64-2.0.2.tgz", + "integrity": "sha512-pAiRN6qSAhDM5SVOIxgx+2xnoVUePHbRNC7OD2aOR3WltTKxxF25OfpK8h8UQ7A0BuRkSgREbB59DBlFk4iAeg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@vscode/vsce/node_modules/ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", @@ -826,6 +1291,16 @@ "node": ">=4" } }, + "node_modules/@vscode/vsce/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, "node_modules/@vscode/vsce/node_modules/chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -873,6 +1348,46 @@ "node": ">=0.8.0" } }, + "node_modules/@vscode/vsce/node_modules/glob": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.0.tgz", + "integrity": "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g==", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@vscode/vsce/node_modules/glob/node_modules/minimatch": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@vscode/vsce/node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -882,15 +1397,6 @@ "node": ">=4" } }, - "node_modules/@vscode/vsce/node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", - "dev": true, - "bin": { - "semver": "bin/semver" - } - }, "node_modules/@vscode/vsce/node_modules/supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", @@ -903,19 +1409,6 @@ "node": ">=4" } }, - "node_modules/@vscode/vsce/node_modules/xml2js": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", - "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", - "dev": true, - "dependencies": { - "sax": ">=0.6.0", - "xmlbuilder": "~11.0.0" - }, - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/acorn": { "version": "8.10.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", @@ -1007,11 +1500,19 @@ "node": ">=8" } }, - "node_modules/azure-devops-node-api": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/azure-devops-node-api/-/azure-devops-node-api-11.2.0.tgz", - "integrity": "sha512-XdiGPhrpaT5J8wdERRKs5g8E0Zy1pvOYTli7z9E8nmOn3YGp4FhtjhrOyFmX/8veWCwdI69mCHKJw6l+4J/bHA==", + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "dev": true, + "license": "MIT" + }, + "node_modules/azure-devops-node-api": { + "version": "12.5.0", + "resolved": "https://registry.npmjs.org/azure-devops-node-api/-/azure-devops-node-api-12.5.0.tgz", + "integrity": "sha512-R5eFskGvOm3U/GzeAuxRkUsAl0hrAwGgWn6zAd2KrZmrEhWZVqLew4OOupbQlXUuojUzpGtq62SmdhJ06N88og==", + "dev": true, + "license": "MIT", "dependencies": { "tunnel": "0.0.6", "typed-rest-client": "^1.8.4" @@ -1132,14 +1633,28 @@ "node": "*" } }, - "node_modules/call-bind": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dev": true, + "license": "MIT", "dependencies": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -1234,6 +1749,16 @@ "node": ">=12" } }, + "node_modules/cockatiel": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/cockatiel/-/cockatiel-3.2.1.tgz", + "integrity": "sha512-gfrHV6ZPkquExvMh9IOkKsBzNDk6sDuZ6DdBGUBkvFnTCqCxzpuq48RySgP0AnaqQkw2zynOFj9yly6T1Q2G5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -1250,6 +1775,19 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", @@ -1780,6 +2318,34 @@ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/delaunator": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.0.tgz", @@ -1788,6 +2354,16 @@ "robust-predicates": "^3.0.0" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/detect-libc": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz", @@ -1877,6 +2453,23 @@ "url": "https://github.com/fb55/domutils?sponsor=1" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -1904,6 +2497,29 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.18.12", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.18.12.tgz", @@ -2156,6 +2772,16 @@ "node": ">=0.10.0" } }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, "node_modules/expand-template": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", @@ -2309,6 +2935,38 @@ } } }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/form-data": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", @@ -2323,10 +2981,14 @@ "dev": true }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/get-caller-file": { "version": "2.0.5", @@ -2337,14 +2999,20 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.0.tgz", - "integrity": "sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", "dev": true, + "license": "MIT", "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.3" + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -2424,6 +3092,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/grapheme-splitter": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", @@ -2436,18 +3117,6 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, - "node_modules/has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -2457,11 +3126,25 @@ "node": ">=8" } }, - "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "dev": true, + "license": "MIT", "engines": { "node": ">= 0.4" }, @@ -2469,6 +3152,32 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hosted-git-info": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", @@ -2642,6 +3351,22 @@ "is-ci": "bin.js" } }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2689,6 +3414,19 @@ "node": ">=8" } }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", @@ -2701,6 +3439,22 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "dev": true }, + "node_modules/jackspeak": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.0.2.tgz", + "integrity": "sha512-bZsjR/iRjl1Nk1UkjGpAzLNfQtzuijhn2g+pbZb98HQ1Gk8vM9hfbxeMBP+M2/UUdwj0RqGG3mlvk2MsAqwvEw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", @@ -2731,6 +3485,52 @@ "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", "dev": true }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jsonwebtoken/node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jsonwebtoken/node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/jszip": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", @@ -2743,6 +3543,29 @@ "setimmediate": "^1.0.5" } }, + "node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, "node_modules/keytar": { "version": "7.9.0", "resolved": "https://registry.npmjs.org/keytar/-/keytar-7.9.0.tgz", @@ -2787,12 +3610,13 @@ } }, "node_modules/linkify-it": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", - "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", "dev": true, + "license": "MIT", "dependencies": { - "uc.micro": "^1.0.1" + "uc.micro": "^2.0.0" } }, "node_modules/locate-path": { @@ -2810,12 +3634,61 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "dev": true, + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "dev": true, + "license": "MIT" + }, "node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -2828,35 +3701,29 @@ } }, "node_modules/markdown-it": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", - "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", + "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^2.0.1", - "entities": "~2.1.0", - "linkify-it": "^3.0.1", - "mdurl": "^1.0.1", - "uc.micro": "^1.0.5" + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" }, "bin": { - "markdown-it": "bin/markdown-it.js" - } - }, - "node_modules/markdown-it/node_modules/entities": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", - "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==", - "dev": true, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" + "markdown-it": "bin/markdown-it.mjs" } }, "node_modules/mdurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", - "integrity": "sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==", - "dev": true + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", + "dev": true, + "license": "MIT" }, "node_modules/merge2": { "version": "1.4.1", @@ -2868,12 +3735,13 @@ } }, "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dev": true, + "license": "MIT", "dependencies": { - "braces": "^3.0.2", + "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { @@ -2892,6 +3760,29 @@ "node": ">=4" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/mimic-response": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", @@ -2927,6 +3818,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/mkdirp-classic": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", @@ -2998,10 +3899,14 @@ } }, "node_modules/object-inspect": { - "version": "1.12.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", - "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -3015,6 +3920,24 @@ "wrappy": "1" } }, + "node_modules/open": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", + "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/optionator": { "version": "0.9.3", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", @@ -3053,6 +3976,93 @@ "node": ">= 14" } }, + "node_modules/ovsx/node_modules/@vscode/vsce": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-2.32.0.tgz", + "integrity": "sha512-3EFJfsgrSftIqt3EtdRcAygy/OJ3hstyI1cDmIgkU9CFZW5C+3djr6mfosndCUqcVYuyjmxOK1xmFp/Bq7+NIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/identity": "^4.1.0", + "@vscode/vsce-sign": "^2.0.0", + "azure-devops-node-api": "^12.5.0", + "chalk": "^2.4.2", + "cheerio": "^1.0.0-rc.9", + "cockatiel": "^3.1.2", + "commander": "^6.2.1", + "form-data": "^4.0.0", + "glob": "^7.0.6", + "hosted-git-info": "^4.0.2", + "jsonc-parser": "^3.2.0", + "leven": "^3.1.0", + "markdown-it": "^12.3.2", + "mime": "^1.3.4", + "minimatch": "^3.0.3", + "parse-semver": "^1.1.1", + "read": "^1.0.7", + "semver": "^7.5.2", + "tmp": "^0.2.1", + "typed-rest-client": "^1.8.4", + "url-join": "^4.0.1", + "xml2js": "^0.5.0", + "yauzl": "^2.3.1", + "yazl": "^2.2.2" + }, + "bin": { + "vsce": "vsce" + }, + "engines": { + "node": ">= 16" + }, + "optionalDependencies": { + "keytar": "^7.7.0" + } + }, + "node_modules/ovsx/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/ovsx/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/ovsx/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/ovsx/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "license": "MIT" + }, "node_modules/ovsx/node_modules/commander": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", @@ -3062,6 +4072,90 @@ "node": ">= 6" } }, + "node_modules/ovsx/node_modules/entities": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==", + "dev": true, + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/ovsx/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/ovsx/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/ovsx/node_modules/linkify-it": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", + "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "uc.micro": "^1.0.1" + } + }, + "node_modules/ovsx/node_modules/markdown-it": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", + "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1", + "entities": "~2.1.0", + "linkify-it": "^3.0.1", + "mdurl": "^1.0.1", + "uc.micro": "^1.0.5" + }, + "bin": { + "markdown-it": "bin/markdown-it.js" + } + }, + "node_modules/ovsx/node_modules/mdurl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", + "integrity": "sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/ovsx/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/ovsx/node_modules/uc.micro": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", + "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", + "dev": true, + "license": "MIT" + }, "node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", @@ -3092,6 +4186,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/pako": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", @@ -3180,6 +4281,33 @@ "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.1.tgz", + "integrity": "sha512-CgeuL5uom6j/ZVrg7G/+1IXqRY8JXX4Hghfy5YE0EhoYQWvndP1kufu58cmZLNIDKnRhZrXfdS9urVWx98AipQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/path-type": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", @@ -3284,13 +4412,24 @@ "node": ">=6" } }, - "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dev": true, + "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" @@ -3478,6 +4617,24 @@ "node": ">=10" } }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/setimmediate": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", @@ -3506,19 +4663,37 @@ } }, "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", "dev": true, + "license": "MIT", "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/simple-concat": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", @@ -3575,6 +4750,17 @@ "node": ">=8" } }, + "node_modules/stoppable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", + "integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4", + "npm": ">=6" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -3597,6 +4783,22 @@ "node": ">=8" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -3608,6 +4810,20 @@ "node": ">=8" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", @@ -3684,15 +4900,13 @@ "dev": true }, "node_modules/tmp": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz", - "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz", + "integrity": "sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==", "dev": true, - "dependencies": { - "rimraf": "^3.0.0" - }, + "license": "MIT", "engines": { - "node": ">=8.17.0" + "node": ">=14.14" } }, "node_modules/to-regex-range": { @@ -3720,16 +4934,18 @@ } }, "node_modules/tslib": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.0.tgz", - "integrity": "sha512-7At1WUettjcSRHXCyYtTselblcHl9PJFFVKiCAy/bY97+BPZXSQ2wbq0P9s8tK2G7dFQfNnlJnPAiArVBVBsfA==", - "dev": true + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.0.tgz", + "integrity": "sha512-jWVzBLplnCmoaTr13V9dYbiQ99wvZRd0vNWaDRg+aVYRcjDF3nDksxFDE/+fkXnKhpnUUkmx5pK/v8mCtLVqZA==", + "dev": true, + "license": "0BSD" }, "node_modules/tunnel": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.6.11 <=0.7.0 || >=0.7.3" } @@ -3772,10 +4988,11 @@ } }, "node_modules/typed-rest-client": { - "version": "1.8.9", - "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.9.tgz", - "integrity": "sha512-uSmjE38B80wjL85UFX3sTYEUlvZ1JgCRhsWj/fJ4rZ0FqDUFoIuodtiVeE+cUqiVTOKPdKrp/sdftD15MDek6g==", + "version": "1.8.11", + "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.11.tgz", + "integrity": "sha512-5UvfMpd1oelmUPRbbaVnq+rHP7ng2cE4qoQkQeAqxRL6PklkxsM0g32/HL0yfvruK6ojQ5x8EE+HF4YV6DtuCA==", "dev": true, + "license": "MIT", "dependencies": { "qs": "^6.9.1", "tunnel": "0.0.6", @@ -3783,10 +5000,11 @@ } }, "node_modules/typescript": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz", - "integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==", + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", + "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", "dev": true, + "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -3796,16 +5014,18 @@ } }, "node_modules/uc.micro": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", - "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", - "dev": true + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "dev": true, + "license": "MIT" }, "node_modules/underscore": { - "version": "1.13.6", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz", - "integrity": "sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==", - "dev": true + "version": "1.13.7", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz", + "integrity": "sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==", + "dev": true, + "license": "MIT" }, "node_modules/uri-js": { "version": "4.4.1", @@ -3828,6 +5048,16 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "dev": true }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/vscode-jsonrpc": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.1.0.tgz", @@ -3913,12 +5143,45 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true }, + "node_modules/xml2js": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", + "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/xmlbuilder": { "version": "11.0.1", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index a52b3d1ec5cc..6c7f402dc5f9 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -58,14 +58,14 @@ "@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/parser": "^6.0.0", "@vscode/test-electron": "^2.3.8", - "@vscode/vsce": "^2.19.0", + "@vscode/vsce": "^3.0.0", "esbuild": "^0.18.12", "eslint": "^8.44.0", "eslint-config-prettier": "^8.8.0", "ovsx": "^0.8.2", "prettier": "^3.0.0", "tslib": "^2.6.0", - "typescript": "^5.1.6" + "typescript": "^5.6.0" }, "activationEvents": [ "workspaceContains:Cargo.toml", From 00318bacbac315c39e4902d13c0bf73ec3519220 Mon Sep 17 00:00:00 2001 From: Johannes Altmanninger Date: Sat, 5 Oct 2024 08:44:26 +0200 Subject: [PATCH 031/366] Clamp Position::character to line length LSP says about Position::character > If the character value is greater than the line length it defaults back to the line length. but from_proto::offset() doesn't implement this. A client might for example request code actions for a whole line by sending Position::character=99999. I don't think there is ever a reason (besides laziness) why the client can't specify the line length instead but I guess we should not crash but follow protocol. Technically it should be a warning, not an error but warning is not shown by default so keep it at error I guess. Fixes #18240 --- src/tools/rust-analyzer/Cargo.toml | 2 +- .../crates/rust-analyzer/src/lsp/from_proto.rs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.toml b/src/tools/rust-analyzer/Cargo.toml index 8c099f324b46..17cefe941e57 100644 --- a/src/tools/rust-analyzer/Cargo.toml +++ b/src/tools/rust-analyzer/Cargo.toml @@ -96,7 +96,7 @@ test-fixture = { path = "./crates/test-fixture" } test-utils = { path = "./crates/test-utils" } # In-tree crates that are published separately and follow semver. See lib/README.md -line-index = { version = "0.1.1" } +line-index = { version = "0.1.2" } la-arena = { version = "0.3.1" } lsp-server = { version = "0.7.6" } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/from_proto.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/from_proto.rs index 1f4544887f06..47e9961cf13f 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/from_proto.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/from_proto.rs @@ -35,10 +35,18 @@ pub(crate) fn offset( .ok_or_else(|| format_err!("Invalid wide col offset"))? } }; - let text_size = line_index.index.offset(line_col).ok_or_else(|| { + let line_range = line_index.index.line(line_col.line).ok_or_else(|| { format_err!("Invalid offset {line_col:?} (line index length: {:?})", line_index.index.len()) })?; - Ok(text_size) + let col = TextSize::from(line_col.col); + let clamped_len = col.min(line_range.len()); + if clamped_len < col { + tracing::error!( + "Position {line_col:?} column exceeds line length {}, clamping it", + u32::from(line_range.len()), + ); + } + Ok(line_range.start() + clamped_len) } pub(crate) fn text_range( From b89751b8f42d9c627ea65a0c2ea2d6f89eb9b461 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Fri, 18 Oct 2024 16:06:57 +0200 Subject: [PATCH 032/366] clean up `*dyn` casts (with principals) - remove a redundant check, because we always emit the "better diagnostic" now - clean up the comments a bit --- compiler/rustc_hir_typeck/src/cast.rs | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 8fa6ab8503d0..7341d3fa3c4e 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -876,20 +876,14 @@ impl<'a, 'tcx> CastCheck<'tcx> { // A + SrcAuto> -> B + DstAuto>. need to make sure // - `Src` and `Dst` traits are the same // - traits have the same generic arguments - // - `SrcAuto` is a superset of `DstAuto` - (Some(src_principal), Some(dst_principal)) => { + // - projections are the same + // - `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto` + // + // Note that trait upcasting goes through a different mechanism (`coerce_unsized`) + // and is unaffected by this check. + (Some(src_principal), Some(_)) => { let tcx = fcx.tcx; - // Check that the traits are actually the same. - // The `dyn Src = dyn Dst` check below would suffice, - // but this may produce a better diagnostic. - // - // Note that trait upcasting goes through a different mechanism (`coerce_unsized`) - // and is unaffected by this check. - if src_principal.def_id() != dst_principal.def_id() { - return Err(CastError::DifferingKinds { src_kind, dst_kind }); - } - // We need to reconstruct trait object types. // `m_src` and `m_dst` won't work for us here because they will potentially // contain wrappers, which we do not care about. @@ -912,8 +906,8 @@ impl<'a, 'tcx> CastCheck<'tcx> { ty::Dyn, )); - // `dyn Src = dyn Dst`, this checks for matching traits/generics - // This is `demand_eqtype`, but inlined to give a better error. + // `dyn Src = dyn Dst`, this checks for matching traits/generics/projections + // This is `fcx.demand_eqtype`, but inlined to give a better error. let cause = fcx.misc(self.span); if fcx .at(&cause, fcx.param_env) From d6f5b437e598074a612fc72c053b00f70c38e607 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Fri, 18 Oct 2024 11:57:12 -0700 Subject: [PATCH 033/366] compiler: Enable test for regparm on different hosts --- tests/codegen/regparm-inreg.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/codegen/regparm-inreg.rs b/tests/codegen/regparm-inreg.rs index ce87a66d0e91..188cad9271ef 100644 --- a/tests/codegen/regparm-inreg.rs +++ b/tests/codegen/regparm-inreg.rs @@ -4,7 +4,6 @@ //@ compile-flags: --target i686-unknown-linux-gnu -O -C no-prepopulate-passes //@ needs-llvm-components: x86 -//@ only-x86 //@ revisions:regparm0 regparm1 regparm2 regparm3 //@[regparm0] compile-flags: -Zregparm=0 From b9c96780b47b0ac3710202df884dfb3580fc4b76 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Fri, 18 Oct 2024 11:54:07 -0700 Subject: [PATCH 034/366] compiler: Revert -Zregparm handling for extern Rust --- compiler/rustc_target/src/callconv/mod.rs | 22 ---------- compiler/rustc_ty_utils/src/abi.rs | 3 -- tests/codegen/regparm-inreg-rust-cc.rs | 53 ----------------------- tests/codegen/regparm-inreg.rs | 7 --- 4 files changed, 85 deletions(-) delete mode 100644 tests/codegen/regparm-inreg-rust-cc.rs diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 07ee3f892b70..5d120a68059a 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -720,28 +720,6 @@ impl<'a, Ty> FnAbi<'a, Ty> { Ok(()) } - - pub fn fill_inregs_for_rust_abi(&mut self, cx: &C) - where - Ty: TyAbiInterface<'a, C> + Copy, - C: HasTargetSpec + HasX86AbiOpt, - { - let spec = cx.target_spec(); - match &spec.arch[..] { - "x86" => { - x86::fill_inregs( - cx, - self, - x86::X86Options { - flavor: x86::Flavor::General, - regparm: cx.x86_abi_opt().regparm, - }, - true, - ); - } - _ => {} - } - } } impl FromStr for Conv { diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 661f140e6970..deda16b76b58 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -797,9 +797,6 @@ fn fn_abi_adjust_for_abi<'tcx>( for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() { fixup(arg, Some(arg_idx)); } - if tcx.sess.target.arch == "x86" { - fn_abi.fill_inregs_for_rust_abi(cx); - } } else { fn_abi .adjust_for_foreign_abi(cx, abi) diff --git a/tests/codegen/regparm-inreg-rust-cc.rs b/tests/codegen/regparm-inreg-rust-cc.rs deleted file mode 100644 index a2d8d5349ea0..000000000000 --- a/tests/codegen/regparm-inreg-rust-cc.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Checks how `regparm` flag works with Rust calling convention with array types. -// When there is a small array type in signature (casted to combined int type), -// inregs will not be set. PassMode::Cast is unsupported. -// x86 only. - -//@ compile-flags: --target i686-unknown-linux-gnu -O -C no-prepopulate-passes -//@ needs-llvm-components: x86 - -//@ revisions:regparm0 regparm1 regparm2 regparm3 -//@[regparm0] compile-flags: -Zregparm=0 -//@[regparm1] compile-flags: -Zregparm=1 -//@[regparm2] compile-flags: -Zregparm=2 -//@[regparm3] compile-flags: -Zregparm=3 - -#![crate_type = "lib"] -#![no_core] -#![feature(no_core, lang_items)] - -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} - -pub mod tests { - // CHECK: @f1(i16 %0, i32 noundef %_2, i32 noundef %_3) - #[no_mangle] - pub extern "Rust" fn f1(_: [u8; 2], _: i32, _: i32) {} - - // CHECK: @f2(i24 %0, i32 noundef %_2, i32 noundef %_3) - #[no_mangle] - pub extern "Rust" fn f2(_: [u8; 3], _: i32, _: i32) {} - - // regparm0: @f3(ptr {{.*}} %_1, i32 noundef %_2, i32 noundef %_3) - // regparm1: @f3(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 noundef %_3) - // regparm2: @f3(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - // regparm3: @f3(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - #[no_mangle] - pub extern "Rust" fn f3(_: [u8; 7], _: i32, _: i32) {} - - // regparm0: @f4(ptr {{.*}} %_1, i32 noundef %_2, i32 noundef %_3) - // regparm1: @f4(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 noundef %_3) - // regparm2: @f4(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - // regparm3: @f4(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - #[no_mangle] - pub extern "Rust" fn f4(_: [u8; 11], _: i32, _: i32) {} - - // regparm0: @f5(ptr {{.*}} %_1, i32 noundef %_2, i32 noundef %_3) - // regparm1: @f5(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 noundef %_3) - // regparm2: @f5(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - // regparm3: @f5(ptr {{.*}} %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - #[no_mangle] - pub extern "Rust" fn f5(_: [u8; 33], _: i32, _: i32) {} -} diff --git a/tests/codegen/regparm-inreg.rs b/tests/codegen/regparm-inreg.rs index 188cad9271ef..c8c647bcc87c 100644 --- a/tests/codegen/regparm-inreg.rs +++ b/tests/codegen/regparm-inreg.rs @@ -25,13 +25,6 @@ pub mod tests { #[no_mangle] pub extern "fastcall" fn f1(_: i32, _: i32, _: i32) {} - // regparm0: @f2(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) - // regparm1: @f2(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3) - // regparm2: @f2(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) - // regparm3: @f2(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 inreg noundef %_3) - #[no_mangle] - pub extern "Rust" fn f2(_: i32, _: i32, _: i32) {} - // regparm0: @f3(i32 noundef %_1, i32 noundef %_2, i32 noundef %_3) // regparm1: @f3(i32 inreg noundef %_1, i32 noundef %_2, i32 noundef %_3) // regparm2: @f3(i32 inreg noundef %_1, i32 inreg noundef %_2, i32 noundef %_3) From 1a93651b8c59031dc110420ab1b2f1935308771b Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Sat, 19 Oct 2024 01:10:31 +0300 Subject: [PATCH 035/366] Fix editorconfig glob --- src/tools/rust-analyzer/.editorconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.editorconfig b/src/tools/rust-analyzer/.editorconfig index e337066f7eac..6bb743a6736e 100644 --- a/src/tools/rust-analyzer/.editorconfig +++ b/src/tools/rust-analyzer/.editorconfig @@ -13,5 +13,5 @@ max_line_length = 100 [*.md] indent_size = 2 -[*.{yml, yaml}] +[*.{yml,yaml}] indent_size = 2 From 0590422812c4c02b4292ee5043583f189d7f3647 Mon Sep 17 00:00:00 2001 From: Wei Xu <1222863+xuwaters@users.noreply.github.com> Date: Fri, 18 Oct 2024 17:36:24 -0700 Subject: [PATCH 036/366] Increase TOKEN_LIMIT for hir-expand --- src/tools/rust-analyzer/crates/hir-expand/src/db.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/db.rs b/src/tools/rust-analyzer/crates/hir-expand/src/db.rs index d412bf4eee52..0d19ae202ce0 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/db.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/db.rs @@ -35,7 +35,7 @@ type MacroArgResult = (Arc, SyntaxFixupUndoInfo, Span); /// an error will be emitted. /// /// Actual max for `analysis-stats .` at some point: 30672. -static TOKEN_LIMIT: Limit = Limit::new(1_048_576); +static TOKEN_LIMIT: Limit = Limit::new(2_097_152); #[derive(Debug, Clone, Eq, PartialEq)] pub enum TokenExpander { From a400d7fb76dd30d30367d0262b0ffb3b64a79cc6 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 5 Oct 2024 18:18:47 +1000 Subject: [PATCH 037/366] coverage: Make counter creation handle nodes/edges more uniformly --- .../src/coverage/counters.rs | 102 +++++++++--------- 1 file changed, 54 insertions(+), 48 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs index 940881567569..c78a4924ee68 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters.rs @@ -104,24 +104,18 @@ impl CoverageCounters { BcbCounter::Counter { id } } - /// Creates a new physical counter attached a BCB node. - /// The node must not already have a counter. + /// Creates a new physical counter for a BCB node. fn make_phys_node_counter(&mut self, bcb: BasicCoverageBlock) -> BcbCounter { - let counter = self.make_counter_inner(CounterIncrementSite::Node { bcb }); - debug!(?bcb, ?counter, "node gets a physical counter"); - self.set_bcb_counter(bcb, counter) + self.make_counter_inner(CounterIncrementSite::Node { bcb }) } - /// Creates a new physical counter attached to a BCB edge. - /// The edge must not already have a counter. + /// Creates a new physical counter for a BCB edge. fn make_phys_edge_counter( &mut self, from_bcb: BasicCoverageBlock, to_bcb: BasicCoverageBlock, ) -> BcbCounter { - let counter = self.make_counter_inner(CounterIncrementSite::Edge { from_bcb, to_bcb }); - debug!(?from_bcb, ?to_bcb, ?counter, "edge gets a physical counter"); - self.set_bcb_edge_counter(from_bcb, to_bcb, counter) + self.make_counter_inner(CounterIncrementSite::Edge { from_bcb, to_bcb }) } fn make_expression(&mut self, lhs: BcbCounter, op: Op, rhs: BcbCounter) -> BcbCounter { @@ -330,11 +324,21 @@ impl<'a> MakeBcbCounters<'a> { return; } - // Determine the set of out-edges that don't yet have edge counters. + // When choosing which out-edge should be given a counter expression, ignore edges that + // already have counters, or could use the existing counter of their target node. + let out_edge_has_counter = |to_bcb| { + if self.coverage_counters.bcb_edge_counters.contains_key(&(from_bcb, to_bcb)) { + return true; + } + self.basic_coverage_blocks.sole_predecessor(to_bcb) == Some(from_bcb) + && self.coverage_counters.bcb_counters[to_bcb].is_some() + }; + + // Determine the set of out-edges that could benefit from being given an expression. let candidate_successors = self.basic_coverage_blocks.successors[from_bcb] .iter() .copied() - .filter(|&to_bcb| self.edge_has_no_counter(from_bcb, to_bcb)) + .filter(|&to_bcb| !out_edge_has_counter(to_bcb)) .collect::>(); debug!(?candidate_successors); @@ -371,14 +375,7 @@ impl<'a> MakeBcbCounters<'a> { ); debug!("{expression_to_bcb:?} gets an expression: {expression:?}"); - if let Some(sole_pred) = self.basic_coverage_blocks.sole_predecessor(expression_to_bcb) { - // This edge normally wouldn't get its own counter, so attach the expression - // to its target node instead, so that `edge_has_no_counter` can see it. - assert_eq!(sole_pred, from_bcb); - self.coverage_counters.set_bcb_counter(expression_to_bcb, expression); - } else { - self.coverage_counters.set_bcb_edge_counter(from_bcb, expression_to_bcb, expression); - } + self.coverage_counters.set_bcb_edge_counter(from_bcb, expression_to_bcb, expression); } #[instrument(level = "debug", skip(self))] @@ -389,6 +386,19 @@ impl<'a> MakeBcbCounters<'a> { return counter_kind; } + let counter = self.make_node_counter_inner(bcb); + self.coverage_counters.set_bcb_counter(bcb, counter) + } + + fn make_node_counter_inner(&mut self, bcb: BasicCoverageBlock) -> BcbCounter { + // If the node's sole in-edge already has a counter, use that. + if let Some(sole_pred) = self.basic_coverage_blocks.sole_predecessor(bcb) + && let Some(&edge_counter) = + self.coverage_counters.bcb_edge_counters.get(&(sole_pred, bcb)) + { + return edge_counter; + } + let predecessors = self.basic_coverage_blocks.predecessors[bcb].as_slice(); // Handle cases where we can't compute a node's count from its in-edges: @@ -398,7 +408,9 @@ impl<'a> MakeBcbCounters<'a> { // leading to infinite recursion. if predecessors.len() <= 1 || predecessors.contains(&bcb) { debug!(?bcb, ?predecessors, "node has <=1 predecessors or is its own predecessor"); - return self.coverage_counters.make_phys_node_counter(bcb); + let counter = self.coverage_counters.make_phys_node_counter(bcb); + debug!(?bcb, ?counter, "node gets a physical counter"); + return counter; } // A BCB with multiple incoming edges can compute its count by ensuring that counters @@ -414,7 +426,7 @@ impl<'a> MakeBcbCounters<'a> { .expect("there must be at least one in-edge"); debug!("{bcb:?} gets a new counter (sum of predecessor counters): {sum_of_in_edges:?}"); - self.coverage_counters.set_bcb_counter(bcb, sum_of_in_edges) + sum_of_in_edges } #[instrument(level = "debug", skip(self))] @@ -422,6 +434,23 @@ impl<'a> MakeBcbCounters<'a> { &mut self, from_bcb: BasicCoverageBlock, to_bcb: BasicCoverageBlock, + ) -> BcbCounter { + // If the edge already has a counter, return it. + if let Some(&counter_kind) = + self.coverage_counters.bcb_edge_counters.get(&(from_bcb, to_bcb)) + { + debug!("Edge {from_bcb:?}->{to_bcb:?} already has a counter: {counter_kind:?}"); + return counter_kind; + } + + let counter = self.make_edge_counter_inner(from_bcb, to_bcb); + self.coverage_counters.set_bcb_edge_counter(from_bcb, to_bcb, counter) + } + + fn make_edge_counter_inner( + &mut self, + from_bcb: BasicCoverageBlock, + to_bcb: BasicCoverageBlock, ) -> BcbCounter { // If the target node has exactly one in-edge (i.e. this one), then just // use the node's counter, since it will have the same value. @@ -439,16 +468,10 @@ impl<'a> MakeBcbCounters<'a> { return self.get_or_make_node_counter(from_bcb); } - // If the edge already has a counter, return it. - if let Some(&counter_kind) = - self.coverage_counters.bcb_edge_counters.get(&(from_bcb, to_bcb)) - { - debug!("Edge {from_bcb:?}->{to_bcb:?} already has a counter: {counter_kind:?}"); - return counter_kind; - } - // Make a new counter to count this edge. - self.coverage_counters.make_phys_edge_counter(from_bcb, to_bcb) + let counter = self.coverage_counters.make_phys_edge_counter(from_bcb, to_bcb); + debug!(?from_bcb, ?to_bcb, ?counter, "edge gets a physical counter"); + counter } /// Given a set of candidate out-edges (represented by their successor node), @@ -508,21 +531,4 @@ impl<'a> MakeBcbCounters<'a> { None } - - #[inline] - fn edge_has_no_counter( - &self, - from_bcb: BasicCoverageBlock, - to_bcb: BasicCoverageBlock, - ) -> bool { - let edge_counter = - if let Some(sole_pred) = self.basic_coverage_blocks.sole_predecessor(to_bcb) { - assert_eq!(sole_pred, from_bcb); - self.coverage_counters.bcb_counters[to_bcb] - } else { - self.coverage_counters.bcb_edge_counters.get(&(from_bcb, to_bcb)).copied() - }; - - edge_counter.is_none() - } } From 4b8f7f547aba0df1afe61b5bb4a3591e22b3cc43 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 19 Oct 2024 18:02:03 +1100 Subject: [PATCH 038/366] coverage: Streamline several names of things in counter creation --- .../src/coverage/counters.rs | 154 ++++++++---------- 1 file changed, 69 insertions(+), 85 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs index c78a4924ee68..9a533ea024d7 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters.rs @@ -5,7 +5,6 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::graph::DirectedGraph; use rustc_index::IndexVec; use rustc_index::bit_set::BitSet; -use rustc_middle::bug; use rustc_middle::mir::coverage::{CounterId, CovTerm, Expression, ExpressionId, Op}; use tracing::{debug, debug_span, instrument}; @@ -58,13 +57,13 @@ pub(super) struct CoverageCounters { counter_increment_sites: IndexVec, /// Coverage counters/expressions that are associated with individual BCBs. - bcb_counters: IndexVec>, + node_counters: IndexVec>, /// Coverage counters/expressions that are associated with the control-flow /// edge between two BCBs. /// /// We currently don't iterate over this map, but if we do in the future, /// switch it back to `FxIndexMap` to avoid query stability hazards. - bcb_edge_counters: FxHashMap<(BasicCoverageBlock, BasicCoverageBlock), BcbCounter>, + edge_counters: FxHashMap<(BasicCoverageBlock, BasicCoverageBlock), BcbCounter>, /// Table of expression data, associating each expression ID with its /// corresponding operator (+ or -) and its LHS/RHS operands. @@ -78,20 +77,20 @@ impl CoverageCounters { /// Ensures that each BCB node needing a counter has one, by creating physical /// counters or counter expressions for nodes and edges as required. pub(super) fn make_bcb_counters( - basic_coverage_blocks: &CoverageGraph, + graph: &CoverageGraph, bcb_needs_counter: &BitSet, ) -> Self { - let mut counters = MakeBcbCounters::new(basic_coverage_blocks, bcb_needs_counter); - counters.make_bcb_counters(); + let mut builder = CountersBuilder::new(graph, bcb_needs_counter); + builder.make_bcb_counters(); - counters.coverage_counters + builder.counters } fn with_num_bcbs(num_bcbs: usize) -> Self { Self { counter_increment_sites: IndexVec::new(), - bcb_counters: IndexVec::from_elem_n(None, num_bcbs), - bcb_edge_counters: FxHashMap::default(), + node_counters: IndexVec::from_elem_n(None, num_bcbs), + edge_counters: FxHashMap::default(), expressions: IndexVec::new(), expressions_memo: FxHashMap::default(), } @@ -187,35 +186,31 @@ impl CoverageCounters { self.counter_increment_sites.len() } - fn set_bcb_counter(&mut self, bcb: BasicCoverageBlock, counter_kind: BcbCounter) -> BcbCounter { - if let Some(replaced) = self.bcb_counters[bcb].replace(counter_kind) { - bug!( - "attempt to set a BasicCoverageBlock coverage counter more than once; \ - {bcb:?} already had counter {replaced:?}", - ); - } else { - counter_kind - } + fn set_node_counter(&mut self, bcb: BasicCoverageBlock, counter: BcbCounter) -> BcbCounter { + let existing = self.node_counters[bcb].replace(counter); + assert!( + existing.is_none(), + "node {bcb:?} already has a counter: {existing:?} => {counter:?}" + ); + counter } - fn set_bcb_edge_counter( + fn set_edge_counter( &mut self, from_bcb: BasicCoverageBlock, to_bcb: BasicCoverageBlock, - counter_kind: BcbCounter, + counter: BcbCounter, ) -> BcbCounter { - if let Some(replaced) = self.bcb_edge_counters.insert((from_bcb, to_bcb), counter_kind) { - bug!( - "attempt to set an edge counter more than once; from_bcb: \ - {from_bcb:?} already had counter {replaced:?}", - ); - } else { - counter_kind - } + let existing = self.edge_counters.insert((from_bcb, to_bcb), counter); + assert!( + existing.is_none(), + "edge ({from_bcb:?} -> {to_bcb:?}) already has a counter: {existing:?} => {counter:?}" + ); + counter } pub(super) fn term_for_bcb(&self, bcb: BasicCoverageBlock) -> Option { - self.bcb_counters[bcb].map(|counter| counter.as_term()) + self.node_counters[bcb].map(|counter| counter.as_term()) } /// Returns an iterator over all the nodes/edges in the coverage graph that @@ -232,7 +227,7 @@ impl CoverageCounters { pub(super) fn bcb_nodes_with_coverage_expressions( &self, ) -> impl Iterator + Captures<'_> { - self.bcb_counters.iter_enumerated().filter_map(|(bcb, &counter_kind)| match counter_kind { + self.node_counters.iter_enumerated().filter_map(|(bcb, &counter)| match counter { // Yield the BCB along with its associated expression ID. Some(BcbCounter::Expression { id }) => Some((bcb, id)), // This BCB is associated with a counter or nothing, so skip it. @@ -259,22 +254,20 @@ impl CoverageCounters { } } -/// Helper struct that allows counter creation to inspect the BCB graph. -struct MakeBcbCounters<'a> { - coverage_counters: CoverageCounters, - basic_coverage_blocks: &'a CoverageGraph, +/// Helper struct that allows counter creation to inspect the BCB graph, and +/// the set of nodes that need counters. +struct CountersBuilder<'a> { + counters: CoverageCounters, + graph: &'a CoverageGraph, bcb_needs_counter: &'a BitSet, } -impl<'a> MakeBcbCounters<'a> { - fn new( - basic_coverage_blocks: &'a CoverageGraph, - bcb_needs_counter: &'a BitSet, - ) -> Self { - assert_eq!(basic_coverage_blocks.num_nodes(), bcb_needs_counter.domain_size()); +impl<'a> CountersBuilder<'a> { + fn new(graph: &'a CoverageGraph, bcb_needs_counter: &'a BitSet) -> Self { + assert_eq!(graph.num_nodes(), bcb_needs_counter.domain_size()); Self { - coverage_counters: CoverageCounters::with_num_bcbs(basic_coverage_blocks.num_nodes()), - basic_coverage_blocks, + counters: CoverageCounters::with_num_bcbs(graph.num_nodes()), + graph, bcb_needs_counter, } } @@ -289,7 +282,7 @@ impl<'a> MakeBcbCounters<'a> { // nodes within the loop are visited before visiting any nodes outside // the loop. It also keeps track of which loop(s) the traversal is // currently inside. - let mut traversal = TraverseCoverageGraphWithLoops::new(self.basic_coverage_blocks); + let mut traversal = TraverseCoverageGraphWithLoops::new(self.graph); while let Some(bcb) = traversal.next() { let _span = debug_span!("traversal", ?bcb).entered(); if self.bcb_needs_counter.contains(bcb) { @@ -316,26 +309,26 @@ impl<'a> MakeBcbCounters<'a> { // We might also use that counter to compute one of the out-edge counters. let node_counter = self.get_or_make_node_counter(from_bcb); - let successors = self.basic_coverage_blocks.successors[from_bcb].as_slice(); + let successors = self.graph.successors[from_bcb].as_slice(); // If this node's out-edges won't sum to the node's counter, // then there's no reason to create edge counters here. - if !self.basic_coverage_blocks[from_bcb].is_out_summable { + if !self.graph[from_bcb].is_out_summable { return; } // When choosing which out-edge should be given a counter expression, ignore edges that // already have counters, or could use the existing counter of their target node. let out_edge_has_counter = |to_bcb| { - if self.coverage_counters.bcb_edge_counters.contains_key(&(from_bcb, to_bcb)) { + if self.counters.edge_counters.contains_key(&(from_bcb, to_bcb)) { return true; } - self.basic_coverage_blocks.sole_predecessor(to_bcb) == Some(from_bcb) - && self.coverage_counters.bcb_counters[to_bcb].is_some() + self.graph.sole_predecessor(to_bcb) == Some(from_bcb) + && self.counters.node_counters[to_bcb].is_some() }; // Determine the set of out-edges that could benefit from being given an expression. - let candidate_successors = self.basic_coverage_blocks.successors[from_bcb] + let candidate_successors = self.graph.successors[from_bcb] .iter() .copied() .filter(|&to_bcb| !out_edge_has_counter(to_bcb)) @@ -344,7 +337,7 @@ impl<'a> MakeBcbCounters<'a> { // If there are out-edges without counters, choose one to be given an expression // (computed from this node and the other out-edges) instead of a physical counter. - let Some(expression_to_bcb) = + let Some(target_bcb) = self.choose_out_edge_for_expression(traversal, &candidate_successors) else { return; @@ -357,49 +350,44 @@ impl<'a> MakeBcbCounters<'a> { .iter() .copied() // Skip the chosen edge, since we'll calculate its count from this sum. - .filter(|&to_bcb| to_bcb != expression_to_bcb) + .filter(|&edge_target_bcb| edge_target_bcb != target_bcb) .map(|to_bcb| self.get_or_make_edge_counter(from_bcb, to_bcb)) .collect::>(); - let Some(sum_of_all_other_out_edges) = - self.coverage_counters.make_sum(&other_out_edge_counters) + let Some(sum_of_all_other_out_edges) = self.counters.make_sum(&other_out_edge_counters) else { return; }; // Now create an expression for the chosen edge, by taking the counter // for its source node and subtracting the sum of its sibling out-edges. - let expression = self.coverage_counters.make_expression( - node_counter, - Op::Subtract, - sum_of_all_other_out_edges, - ); + let expression = + self.counters.make_expression(node_counter, Op::Subtract, sum_of_all_other_out_edges); - debug!("{expression_to_bcb:?} gets an expression: {expression:?}"); - self.coverage_counters.set_bcb_edge_counter(from_bcb, expression_to_bcb, expression); + debug!("{target_bcb:?} gets an expression: {expression:?}"); + self.counters.set_edge_counter(from_bcb, target_bcb, expression); } #[instrument(level = "debug", skip(self))] fn get_or_make_node_counter(&mut self, bcb: BasicCoverageBlock) -> BcbCounter { // If the BCB already has a counter, return it. - if let Some(counter_kind) = self.coverage_counters.bcb_counters[bcb] { - debug!("{bcb:?} already has a counter: {counter_kind:?}"); - return counter_kind; + if let Some(counter) = self.counters.node_counters[bcb] { + debug!("{bcb:?} already has a counter: {counter:?}"); + return counter; } let counter = self.make_node_counter_inner(bcb); - self.coverage_counters.set_bcb_counter(bcb, counter) + self.counters.set_node_counter(bcb, counter) } fn make_node_counter_inner(&mut self, bcb: BasicCoverageBlock) -> BcbCounter { // If the node's sole in-edge already has a counter, use that. - if let Some(sole_pred) = self.basic_coverage_blocks.sole_predecessor(bcb) - && let Some(&edge_counter) = - self.coverage_counters.bcb_edge_counters.get(&(sole_pred, bcb)) + if let Some(sole_pred) = self.graph.sole_predecessor(bcb) + && let Some(&edge_counter) = self.counters.edge_counters.get(&(sole_pred, bcb)) { return edge_counter; } - let predecessors = self.basic_coverage_blocks.predecessors[bcb].as_slice(); + let predecessors = self.graph.predecessors[bcb].as_slice(); // Handle cases where we can't compute a node's count from its in-edges: // - START_BCB has no in-edges, so taking the sum would panic (or be wrong). @@ -408,7 +396,7 @@ impl<'a> MakeBcbCounters<'a> { // leading to infinite recursion. if predecessors.len() <= 1 || predecessors.contains(&bcb) { debug!(?bcb, ?predecessors, "node has <=1 predecessors or is its own predecessor"); - let counter = self.coverage_counters.make_phys_node_counter(bcb); + let counter = self.counters.make_phys_node_counter(bcb); debug!(?bcb, ?counter, "node gets a physical counter"); return counter; } @@ -420,10 +408,8 @@ impl<'a> MakeBcbCounters<'a> { .copied() .map(|from_bcb| self.get_or_make_edge_counter(from_bcb, bcb)) .collect::>(); - let sum_of_in_edges: BcbCounter = self - .coverage_counters - .make_sum(&in_edge_counters) - .expect("there must be at least one in-edge"); + let sum_of_in_edges: BcbCounter = + self.counters.make_sum(&in_edge_counters).expect("there must be at least one in-edge"); debug!("{bcb:?} gets a new counter (sum of predecessor counters): {sum_of_in_edges:?}"); sum_of_in_edges @@ -436,15 +422,13 @@ impl<'a> MakeBcbCounters<'a> { to_bcb: BasicCoverageBlock, ) -> BcbCounter { // If the edge already has a counter, return it. - if let Some(&counter_kind) = - self.coverage_counters.bcb_edge_counters.get(&(from_bcb, to_bcb)) - { - debug!("Edge {from_bcb:?}->{to_bcb:?} already has a counter: {counter_kind:?}"); - return counter_kind; + if let Some(&counter) = self.counters.edge_counters.get(&(from_bcb, to_bcb)) { + debug!("Edge {from_bcb:?}->{to_bcb:?} already has a counter: {counter:?}"); + return counter; } let counter = self.make_edge_counter_inner(from_bcb, to_bcb); - self.coverage_counters.set_bcb_edge_counter(from_bcb, to_bcb, counter) + self.counters.set_edge_counter(from_bcb, to_bcb, counter) } fn make_edge_counter_inner( @@ -454,7 +438,7 @@ impl<'a> MakeBcbCounters<'a> { ) -> BcbCounter { // If the target node has exactly one in-edge (i.e. this one), then just // use the node's counter, since it will have the same value. - if let Some(sole_pred) = self.basic_coverage_blocks.sole_predecessor(to_bcb) { + if let Some(sole_pred) = self.graph.sole_predecessor(to_bcb) { assert_eq!(sole_pred, from_bcb); // This call must take care not to invoke `get_or_make_edge` for // this edge, since that would result in infinite recursion! @@ -463,13 +447,13 @@ impl<'a> MakeBcbCounters<'a> { // If the source node has exactly one out-edge (i.e. this one) and would have // the same execution count as that edge, then just use the node's counter. - if let Some(simple_succ) = self.basic_coverage_blocks.simple_successor(from_bcb) { + if let Some(simple_succ) = self.graph.simple_successor(from_bcb) { assert_eq!(simple_succ, to_bcb); return self.get_or_make_node_counter(from_bcb); } // Make a new counter to count this edge. - let counter = self.coverage_counters.make_phys_edge_counter(from_bcb, to_bcb); + let counter = self.counters.make_phys_edge_counter(from_bcb, to_bcb); debug!(?from_bcb, ?to_bcb, ?counter, "edge gets a physical counter"); counter } @@ -516,9 +500,9 @@ impl<'a> MakeBcbCounters<'a> { for &target_bcb in candidate_successors { // An edge is a reloop edge if its target dominates any BCB that has // an edge back to the loop header. (Otherwise it's an exit edge.) - let is_reloop_edge = reloop_bcbs.iter().any(|&reloop_bcb| { - self.basic_coverage_blocks.dominates(target_bcb, reloop_bcb) - }); + let is_reloop_edge = reloop_bcbs + .iter() + .any(|&reloop_bcb| self.graph.dominates(target_bcb, reloop_bcb)); if is_reloop_edge { // We found a good out-edge to be given an expression. return Some(target_bcb); From ab4222ad97808dc00ee0476dcbffba3ea584e0aa Mon Sep 17 00:00:00 2001 From: clubby789 Date: Fri, 18 Oct 2024 22:05:31 +0000 Subject: [PATCH 039/366] Prevent overflowing enum cast from ICEing --- compiler/rustc_mir_build/src/thir/cx/expr.rs | 9 +++- tests/ui/error-codes/E0081.rs | 44 +++++++++++++++++++- tests/ui/error-codes/E0081.stderr | 28 ++++++++++++- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 5995d60e7e07..50ad53387076 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -281,7 +281,14 @@ impl<'tcx> Cx<'tcx> { .unwrap_or_else(|e| panic!("could not compute layout for {param_env_ty:?}: {e:?}")) .size; - let lit = ScalarInt::try_from_uint(discr_offset as u128, size).unwrap(); + let (lit, overflowing) = ScalarInt::truncate_from_uint(discr_offset as u128, size); + if overflowing { + // An erroneous enum with too many variants for its repr will emit E0081 and E0370 + self.tcx.dcx().span_delayed_bug( + source.span, + "overflowing enum wasn't rejected by hir analysis", + ); + } let kind = ExprKind::NonHirLiteral { lit, user_ty: None }; let offset = self.thir.exprs.push(Expr { temp_lifetime, ty: discr_ty, span, kind }); diff --git a/tests/ui/error-codes/E0081.rs b/tests/ui/error-codes/E0081.rs index f53fda864d65..8fdb27c36e35 100644 --- a/tests/ui/error-codes/E0081.rs +++ b/tests/ui/error-codes/E0081.rs @@ -50,5 +50,47 @@ enum MultipleDuplicates { //~^ NOTE `-2` assigned here } -fn main() { +// Test for #131902 +// Ensure that casting an enum with too many variants for its repr +// does not ICE +#[repr(u8)] +enum TooManyVariants { + //~^ ERROR discriminant value `0` assigned more than once + X000, X001, X002, X003, X004, X005, X006, X007, X008, X009, + //~^ NOTE `0` assigned here + //~| NOTE discriminant for `X256` incremented from this startpoint + X010, X011, X012, X013, X014, X015, X016, X017, X018, X019, + X020, X021, X022, X023, X024, X025, X026, X027, X028, X029, + X030, X031, X032, X033, X034, X035, X036, X037, X038, X039, + X040, X041, X042, X043, X044, X045, X046, X047, X048, X049, + X050, X051, X052, X053, X054, X055, X056, X057, X058, X059, + X060, X061, X062, X063, X064, X065, X066, X067, X068, X069, + X070, X071, X072, X073, X074, X075, X076, X077, X078, X079, + X080, X081, X082, X083, X084, X085, X086, X087, X088, X089, + X090, X091, X092, X093, X094, X095, X096, X097, X098, X099, + X100, X101, X102, X103, X104, X105, X106, X107, X108, X109, + X110, X111, X112, X113, X114, X115, X116, X117, X118, X119, + X120, X121, X122, X123, X124, X125, X126, X127, X128, X129, + X130, X131, X132, X133, X134, X135, X136, X137, X138, X139, + X140, X141, X142, X143, X144, X145, X146, X147, X148, X149, + X150, X151, X152, X153, X154, X155, X156, X157, X158, X159, + X160, X161, X162, X163, X164, X165, X166, X167, X168, X169, + X170, X171, X172, X173, X174, X175, X176, X177, X178, X179, + X180, X181, X182, X183, X184, X185, X186, X187, X188, X189, + X190, X191, X192, X193, X194, X195, X196, X197, X198, X199, + X200, X201, X202, X203, X204, X205, X206, X207, X208, X209, + X210, X211, X212, X213, X214, X215, X216, X217, X218, X219, + X220, X221, X222, X223, X224, X225, X226, X227, X228, X229, + X230, X231, X232, X233, X234, X235, X236, X237, X238, X239, + X240, X241, X242, X243, X244, X245, X246, X247, X248, X249, + X250, X251, X252, X253, X254, X255, + X256, + //~^ ERROR enum discriminant overflowed + //~| NOTE overflowed on value after 255 + //~| NOTE explicitly set `X256 = 0` + //~| NOTE `0` assigned here +} + +fn main() { + TooManyVariants::X256 as u8; } diff --git a/tests/ui/error-codes/E0081.stderr b/tests/ui/error-codes/E0081.stderr index d4b21f6893b4..91445eedf4da 100644 --- a/tests/ui/error-codes/E0081.stderr +++ b/tests/ui/error-codes/E0081.stderr @@ -73,6 +73,30 @@ LL | LL | V9, | -- `-2` assigned here -error: aborting due to 5 previous errors +error[E0370]: enum discriminant overflowed + --> $DIR/E0081.rs:87:5 + | +LL | X256, + | ^^^^ overflowed on value after 255 + | + = note: explicitly set `X256 = 0` if that is desired outcome -For more information about this error, try `rustc --explain E0081`. +error[E0081]: discriminant value `0` assigned more than once + --> $DIR/E0081.rs:57:1 + | +LL | enum TooManyVariants { + | ^^^^^^^^^^^^^^^^^^^^ +LL | +LL | X000, X001, X002, X003, X004, X005, X006, X007, X008, X009, + | ---- + | | + | `0` assigned here + | discriminant for `X256` incremented from this startpoint (`X000` + 256 variants later => `X256` = 0) +... +LL | X256, + | ---- `0` assigned here + +error: aborting due to 7 previous errors + +Some errors have detailed explanations: E0081, E0370. +For more information about an error, try `rustc --explain E0081`. From 3b789565a19b77fd414f304f24ec21d6e1042000 Mon Sep 17 00:00:00 2001 From: Alona Enraght-Moony Date: Sat, 19 Oct 2024 13:37:40 +0000 Subject: [PATCH 040/366] rustdoc: Document `markdown` module. Rustdoc markdown handling is currently split between: - html::markdown, which contains all the meaty login - markdown, which is only used for when rustdoc renders a standalone markdown file Adds module-level doc-comment to markdown, and rename the function so it's clear that it's doing IO (instead of just rendering to a string). --- src/librustdoc/html/render/write_shared.rs | 2 +- src/librustdoc/lib.rs | 2 +- src/librustdoc/markdown.rs | 12 +++++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index 12b634600569..c82f7e9aaf92 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -112,7 +112,7 @@ pub(crate) fn write_shared( md_opts.output = cx.dst.clone(); md_opts.external_html = cx.shared.layout.external_html.clone(); try_err!( - crate::markdown::render(&index_page, md_opts, cx.shared.edition()), + crate::markdown::render_and_write(&index_page, md_opts, cx.shared.edition()), &index_page ); } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 10fc0ea99901..cb9b3985bf67 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -817,7 +817,7 @@ fn main_args( return wrap_return( dcx, interface::run_compiler(config, |_compiler| { - markdown::render(&md_input, render_options, edition) + markdown::render_and_write(&md_input, render_options, edition) }), ); } diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 978f96f38bed..76eac084907d 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -1,3 +1,13 @@ +//! Standalone markdown rendering. +//! +//! For the (much more common) case of rendering markdown in doc-comments, see +//! [crate::html::markdown]. +//! +//! This is used when [rendering a markdown file to an html file][docs], without processing +//! rust source code. +//! +//! [docs]: https://doc.rust-lang.org/stable/rustdoc/#using-standalone-markdown-files + use std::fmt::Write as _; use std::fs::{File, create_dir_all, read_to_string}; use std::io::prelude::*; @@ -33,7 +43,7 @@ fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) { /// (e.g., output = "bar" => "bar/foo.html"). /// /// Requires session globals to be available, for symbol interning. -pub(crate) fn render>( +pub(crate) fn render_and_write>( input: P, options: RenderOptions, edition: Edition, From 0747f2898e83df7e601189c0f31762e84328becb Mon Sep 17 00:00:00 2001 From: GnomedDev Date: Wed, 16 Oct 2024 21:10:24 +0100 Subject: [PATCH 041/366] Remove the Arc rt::init allocation for thread info --- library/std/src/lib.rs | 1 + library/std/src/rt.rs | 2 +- library/std/src/thread/mod.rs | 170 ++++++++++++++++++-------- tests/debuginfo/thread.rs | 8 +- tests/rustdoc/demo-allocator-54478.rs | 1 + 5 files changed, 124 insertions(+), 58 deletions(-) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 3ab652383689..ef1bc7dbc188 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -364,6 +364,7 @@ #![feature(str_internals)] #![feature(strict_provenance)] #![feature(strict_provenance_atomic_ptr)] +#![feature(sync_unsafe_cell)] #![feature(ub_checks)] // tidy-alphabetical-end // diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index 80e7c3c026bd..b2492238bd37 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -110,7 +110,7 @@ unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { // handle does not match the current ID, we should attempt to use the // current thread ID here instead of unconditionally creating a new // one. Also see #130210. - let thread = Thread::new_main(thread::current_id()); + let thread = unsafe { Thread::new_main(thread::current_id()) }; if let Err(_thread) = thread::set_current(thread) { // `thread::current` will create a new handle if none has been set yet. // Thus, if someone uses it before main, this call will fail. That's a diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 397538885099..70aa3170c6eb 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -158,9 +158,12 @@ #[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] mod tests; +use core::cell::SyncUnsafeCell; +use core::ffi::CStr; +use core::mem::MaybeUninit; + use crate::any::Any; use crate::cell::UnsafeCell; -use crate::ffi::CStr; use crate::marker::PhantomData; use crate::mem::{self, ManuallyDrop, forget}; use crate::num::NonZero; @@ -1125,7 +1128,7 @@ pub fn park_timeout(dur: Duration) { let guard = PanicGuard; // SAFETY: park_timeout is called on the parker owned by this thread. unsafe { - current().inner.as_ref().parker().park_timeout(dur); + current().0.parker().park_timeout(dur); } // No panic occurred, do not abort. forget(guard); @@ -1232,30 +1235,31 @@ impl ThreadId { // Thread //////////////////////////////////////////////////////////////////////////////// -/// The internal representation of a `Thread`'s name. -enum ThreadName { - Main, - Other(ThreadNameString), - Unnamed, -} - // This module ensures private fields are kept private, which is necessary to enforce the safety requirements. mod thread_name_string { use core::str; - use super::ThreadName; use crate::ffi::{CStr, CString}; /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated. pub(crate) struct ThreadNameString { inner: CString, } + + impl ThreadNameString { + pub fn as_str(&self) -> &str { + // SAFETY: `self.inner` is only initialised via `String`, which upholds the validity invariant of `str`. + unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) } + } + } + impl core::ops::Deref for ThreadNameString { type Target = CStr; fn deref(&self) -> &CStr { &self.inner } } + impl From for ThreadNameString { fn from(s: String) -> Self { Self { @@ -1263,34 +1267,82 @@ mod thread_name_string { } } } - impl ThreadName { - pub fn as_cstr(&self) -> Option<&CStr> { - match self { - ThreadName::Main => Some(c"main"), - ThreadName::Other(other) => Some(other), - ThreadName::Unnamed => None, - } - } - - pub fn as_str(&self) -> Option<&str> { - // SAFETY: `as_cstr` can only return `Some` for a fixed CStr or a `ThreadNameString`, - // which is guaranteed to be UTF-8. - self.as_cstr().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) }) - } - } } pub(crate) use thread_name_string::ThreadNameString; -/// The internal representation of a `Thread` handle -struct Inner { - name: ThreadName, // Guaranteed to be UTF-8 +static MAIN_THREAD_INFO: SyncUnsafeCell<(MaybeUninit, MaybeUninit)> = + SyncUnsafeCell::new((MaybeUninit::uninit(), MaybeUninit::uninit())); + +/// The internal representation of a `Thread` that is not the main thread. +struct OtherInner { + name: Option, id: ThreadId, parker: Parker, } +/// The internal representation of a `Thread` handle. +#[derive(Clone)] +enum Inner { + /// Represents the main thread. May only be constructed by Thread::new_main. + Main(&'static (ThreadId, Parker)), + /// Represents any other thread. + Other(Pin>), +} + impl Inner { - fn parker(self: Pin<&Self>) -> Pin<&Parker> { - unsafe { Pin::map_unchecked(self, |inner| &inner.parker) } + fn id(&self) -> ThreadId { + match self { + Self::Main((thread_id, _)) => *thread_id, + Self::Other(other) => other.id, + } + } + + fn cname(&self) -> Option<&CStr> { + match self { + Self::Main(_) => Some(c"main"), + Self::Other(other) => other.name.as_deref(), + } + } + + fn name(&self) -> Option<&str> { + match self { + Self::Main(_) => Some("main"), + Self::Other(other) => other.name.as_ref().map(ThreadNameString::as_str), + } + } + + fn into_raw(self) -> *const () { + match self { + // Just return the pointer to `MAIN_THREAD_INFO`. + Self::Main(ptr) => crate::ptr::from_ref(ptr).cast(), + Self::Other(arc) => { + // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant. + let inner = unsafe { Pin::into_inner_unchecked(arc) }; + Arc::into_raw(inner) as *const () + } + } + } + + /// # Safety + /// + /// See [`Thread::from_raw`]. + unsafe fn from_raw(ptr: *const ()) -> Self { + // If the pointer is to `MAIN_THREAD_INFO`, we know it is the `Main` variant. + if crate::ptr::eq(ptr.cast(), &MAIN_THREAD_INFO) { + Self::Main(unsafe { &*ptr.cast() }) + } else { + // Safety: Upheld by caller + Self::Other(unsafe { Pin::new_unchecked(Arc::from_raw(ptr as *const OtherInner)) }) + } + } + + fn parker(&self) -> Pin<&Parker> { + match self { + Self::Main((_, parker_ref)) => Pin::static_ref(parker_ref), + Self::Other(inner) => unsafe { + Pin::map_unchecked(inner.as_ref(), |inner| &inner.parker) + }, + } } } @@ -1314,33 +1366,47 @@ impl Inner { /// docs of [`Builder`] and [`spawn`] for more details. /// /// [`thread::current`]: current::current -pub struct Thread { - inner: Pin>, -} +pub struct Thread(Inner); impl Thread { /// Used only internally to construct a thread object without spawning. pub(crate) fn new(id: ThreadId, name: String) -> Thread { - Self::new_inner(id, ThreadName::Other(name.into())) + Self::new_inner(id, Some(ThreadNameString::from(name))) } pub(crate) fn new_unnamed(id: ThreadId) -> Thread { - Self::new_inner(id, ThreadName::Unnamed) + Self::new_inner(id, None) } - /// Constructs the thread handle for the main thread. - pub(crate) fn new_main(id: ThreadId) -> Thread { - Self::new_inner(id, ThreadName::Main) + /// Used in runtime to construct main thread + /// + /// # Safety + /// + /// This must only ever be called once, and must be called on the main thread. + pub(crate) unsafe fn new_main(thread_id: ThreadId) -> Thread { + // Safety: As this is only called once and on the main thread, nothing else is accessing MAIN_THREAD_INFO + // as the only other read occurs in `main_thread_info` *after* the main thread has been constructed, + // and this function is the only one that constructs the main thread. + // + // Pre-main thread spawning cannot hit this either, as the caller promises that this is only called on the main thread. + let main_thread_info = unsafe { &mut *MAIN_THREAD_INFO.get() }; + + unsafe { Parker::new_in_place((&raw mut main_thread_info.1).cast()) }; + main_thread_info.0.write(thread_id); + + // Store a `'static` ref to the initialised ThreadId and Parker, + // to avoid having to repeatedly prove initialisation. + Self(Inner::Main(unsafe { &*MAIN_THREAD_INFO.get().cast() })) } - fn new_inner(id: ThreadId, name: ThreadName) -> Thread { + fn new_inner(id: ThreadId, name: Option) -> Thread { // We have to use `unsafe` here to construct the `Parker` in-place, // which is required for the UNIX implementation. // // SAFETY: We pin the Arc immediately after creation, so its address never // changes. let inner = unsafe { - let mut arc = Arc::::new_uninit(); + let mut arc = Arc::::new_uninit(); let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr(); (&raw mut (*ptr).name).write(name); (&raw mut (*ptr).id).write(id); @@ -1348,7 +1414,7 @@ impl Thread { Pin::new_unchecked(arc.assume_init()) }; - Thread { inner } + Self(Inner::Other(inner)) } /// Like the public [`park`], but callable on any handle. This is used to @@ -1357,7 +1423,7 @@ impl Thread { /// # Safety /// May only be called from the thread to which this handle belongs. pub(crate) unsafe fn park(&self) { - unsafe { self.inner.as_ref().parker().park() } + unsafe { self.0.parker().park() } } /// Atomically makes the handle's token available if it is not already. @@ -1393,7 +1459,7 @@ impl Thread { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn unpark(&self) { - self.inner.as_ref().parker().unpark(); + self.0.parker().unpark(); } /// Gets the thread's unique identifier. @@ -1413,7 +1479,7 @@ impl Thread { #[stable(feature = "thread_id", since = "1.19.0")] #[must_use] pub fn id(&self) -> ThreadId { - self.inner.id + self.0.id() } /// Gets the thread's name. @@ -1456,7 +1522,11 @@ impl Thread { #[stable(feature = "rust1", since = "1.0.0")] #[must_use] pub fn name(&self) -> Option<&str> { - self.inner.name.as_str() + self.0.name() + } + + fn cname(&self) -> Option<&CStr> { + self.0.cname() } /// Consumes the `Thread`, returning a raw pointer. @@ -1480,9 +1550,7 @@ impl Thread { /// ``` #[unstable(feature = "thread_raw", issue = "97523")] pub fn into_raw(self) -> *const () { - // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant. - let inner = unsafe { Pin::into_inner_unchecked(self.inner) }; - Arc::into_raw(inner) as *const () + self.0.into_raw() } /// Constructs a `Thread` from a raw pointer. @@ -1504,11 +1572,7 @@ impl Thread { #[unstable(feature = "thread_raw", issue = "97523")] pub unsafe fn from_raw(ptr: *const ()) -> Thread { // Safety: Upheld by caller. - unsafe { Thread { inner: Pin::new_unchecked(Arc::from_raw(ptr as *const Inner)) } } - } - - fn cname(&self) -> Option<&CStr> { - self.inner.name.as_cstr() + unsafe { Thread(Inner::from_raw(ptr)) } } } diff --git a/tests/debuginfo/thread.rs b/tests/debuginfo/thread.rs index 0415f586f5d9..dc8cb0832192 100644 --- a/tests/debuginfo/thread.rs +++ b/tests/debuginfo/thread.rs @@ -12,15 +12,15 @@ // cdb-check:join_handle,d [Type: std::thread::JoinHandle >] // cdb-check: [...] __0 [Type: std::thread::JoinInner >] // -// cdb-command:dx t,d +// cdb-command:dx -r3 t,d // cdb-check:t,d : [...] [Type: std::thread::Thread *] -// cdb-check:[...] inner [...][Type: core::pin::Pin >] +// cdb-check: [...] __0 : Other [Type: enum2$] +// cdb-check: [...] __0 [Type: core::pin::Pin >] use std::thread; #[allow(unused_variables)] -fn main() -{ +fn main() { let join_handle = thread::spawn(|| { println!("Initialize a thread"); }); diff --git a/tests/rustdoc/demo-allocator-54478.rs b/tests/rustdoc/demo-allocator-54478.rs index dd98e80f03ad..80acfc0ff58a 100644 --- a/tests/rustdoc/demo-allocator-54478.rs +++ b/tests/rustdoc/demo-allocator-54478.rs @@ -40,6 +40,7 @@ //! } //! //! fn main() { +//! drop(String::from("An allocation")); //! assert!(unsafe { HIT }); //! } //! ``` From b4da0585959ec8b2c111bc9f8fd0e34e78c7f260 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Mon, 13 Nov 2023 14:35:37 +0100 Subject: [PATCH 042/366] Do not run lints that cannot emit Before this change, adding a lint was a difficult matter because it always had some overhead involved. This was because all lints would run, no matter their default level, or if the user had #![allow]ed them. This PR changes that --- Cargo.lock | 1 + compiler/rustc_ast/src/attr/mod.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 14 +- compiler/rustc_lint/src/early.rs | 3 + compiler/rustc_lint/src/internal.rs | 6 +- compiler/rustc_lint/src/late.rs | 45 ++++++- compiler/rustc_lint/src/levels.rs | 121 +++++++++++++++++- compiler/rustc_lint/src/lib.rs | 24 ++-- compiler/rustc_lint/src/passes.rs | 10 +- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_lint/src/unused.rs | 4 +- compiler/rustc_lint_defs/src/builtin.rs | 6 +- compiler/rustc_lint_defs/src/lib.rs | 30 ++++- compiler/rustc_middle/Cargo.toml | 1 + compiler/rustc_middle/src/lint.rs | 2 +- compiler/rustc_middle/src/query/mod.rs | 5 + src/librustdoc/lint.rs | 7 +- .../clippy/clippy_lints/src/asm_syntax.rs | 2 +- .../src/utils/{ => internal_lints}/author.rs | 11 +- .../clippy/clippy_lints/src/utils/mod.rs | 1 - .../tests/{ui => ui-internal}/author.rs | 2 + .../tests/{ui => ui-internal}/author.stdout | 0 .../{ui => ui-internal}/author/blocks.rs | 0 .../{ui => ui-internal}/author/blocks.stdout | 0 .../tests/{ui => ui-internal}/author/call.rs | 0 .../{ui => ui-internal}/author/call.stdout | 0 .../tests/{ui => ui-internal}/author/if.rs | 0 .../{ui => ui-internal}/author/if.stdout | 0 .../{ui => ui-internal}/author/issue_3849.rs | 0 .../author/issue_3849.stdout | 0 .../tests/{ui => ui-internal}/author/loop.rs | 0 .../{ui => ui-internal}/author/loop.stdout | 0 .../author/macro_in_closure.rs | 0 .../author/macro_in_closure.stdout | 0 .../author/macro_in_loop.rs | 0 .../author/macro_in_loop.stdout | 0 .../{ui => ui-internal}/author/matches.rs | 0 .../{ui => ui-internal}/author/matches.stdout | 0 .../{ui => ui-internal}/author/repeat.rs | 0 .../{ui => ui-internal}/author/repeat.stdout | 0 .../{ui => ui-internal}/author/struct.rs | 0 .../{ui => ui-internal}/author/struct.stdout | 0 src/tools/clippy/tests/ui/no_lints.rs | 3 + .../lint_pass_impl_without_macro.rs | 10 +- .../lint_pass_impl_without_macro.stderr | 2 +- 45 files changed, 264 insertions(+), 50 deletions(-) rename src/tools/clippy/clippy_lints/src/utils/{ => internal_lints}/author.rs (99%) rename src/tools/clippy/tests/{ui => ui-internal}/author.rs (72%) rename src/tools/clippy/tests/{ui => ui-internal}/author.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/blocks.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/blocks.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/call.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/call.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/if.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/if.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/issue_3849.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/issue_3849.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/loop.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/loop.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/macro_in_closure.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/macro_in_closure.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/macro_in_loop.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/macro_in_loop.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/matches.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/matches.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/repeat.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/repeat.stdout (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/struct.rs (100%) rename src/tools/clippy/tests/{ui => ui-internal}/author/struct.stdout (100%) create mode 100644 src/tools/clippy/tests/ui/no_lints.rs diff --git a/Cargo.lock b/Cargo.lock index 60f2f17c3ee3..8f6946e062e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4029,6 +4029,7 @@ dependencies = [ "rustc_hir", "rustc_hir_pretty", "rustc_index", + "rustc_lint_defs", "rustc_macros", "rustc_query_system", "rustc_serialize", diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index b73412a4b1de..9311af28f545 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -223,7 +223,7 @@ impl AttrItem { self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span)) } - fn meta_item_list(&self) -> Option> { + pub fn meta_item_list(&self) -> Option> { match &self.args { AttrArgs::Delimited(args) if args.delim == Delimiter::Parenthesis => { MetaItemKind::list_from_tokens(args.tokens.clone()) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 8bd9c899a628..acd12f7f20df 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -74,6 +74,12 @@ use crate::{ fluent_generated as fluent, }; +use std::default::Default; +use std::fmt::Write; + +// hardwired lints from rustc_lint_defs +pub use rustc_session::lint::builtin::*; + declare_lint! { /// The `while_true` lint detects `while true { }`. /// @@ -241,7 +247,8 @@ declare_lint! { /// behavior. UNSAFE_CODE, Allow, - "usage of `unsafe` code and other potentially unsound constructs" + "usage of `unsafe` code and other potentially unsound constructs", + [loadbearing: true] } declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]); @@ -389,6 +396,7 @@ declare_lint! { report_in_external_macro } +#[derive(Default)] pub struct MissingDoc; impl_lint_pass!(MissingDoc => [MISSING_DOCS]); @@ -819,8 +827,8 @@ pub struct DeprecatedAttr { impl_lint_pass!(DeprecatedAttr => []); -impl DeprecatedAttr { - pub fn new() -> DeprecatedAttr { +impl Default for DeprecatedAttr { + fn default() -> Self { DeprecatedAttr { depr_attrs: deprecated_attributes() } } } diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 2285877c9ef2..a63a0833541f 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -312,6 +312,9 @@ impl LintPass for RuntimeCombinedEarlyLintPass<'_> { fn name(&self) -> &'static str { panic!() } + fn get_lints(&self) -> crate::LintVec { + panic!() + } } macro_rules! impl_early_lint_pass { diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 94cc58e49568..0f4f58efd8e6 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -429,7 +429,8 @@ declare_tool_lint! { pub rustc::UNTRANSLATABLE_DIAGNOSTIC, Deny, "prevent creation of diagnostics which cannot be translated", - report_in_external_macro: true + report_in_external_macro: true, + [loadbearing: true] } declare_tool_lint! { @@ -442,7 +443,8 @@ declare_tool_lint! { pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL, Deny, "prevent diagnostic creation outside of `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls", - report_in_external_macro: true + report_in_external_macro: true, + [loadbearing: true] } declare_lint_pass!(Diagnostics => [UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL]); diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 6d5903ac4674..ccd06ba612bc 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -326,6 +326,9 @@ impl LintPass for RuntimeCombinedLateLintPass<'_, '_> { fn name(&self) -> &'static str { panic!() } + fn get_lints(&self) -> crate::LintVec { + panic!() + } } macro_rules! impl_late_lint_pass { @@ -361,13 +364,38 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( // Note: `passes` is often empty. In that case, it's faster to run // `builtin_lints` directly rather than bundling it up into the // `RuntimeCombinedLateLintPass`. - let late_module_passes = &unerased_lint_store(tcx.sess).late_module_passes; - if late_module_passes.is_empty() { + let store = unerased_lint_store(tcx.sess); + + if store.late_module_passes.is_empty() { late_lint_mod_inner(tcx, module_def_id, context, builtin_lints); } else { - let mut passes: Vec<_> = late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); - passes.push(Box::new(builtin_lints)); - let pass = RuntimeCombinedLateLintPass { passes: &mut passes[..] }; + let passes: Vec<_> = + store.late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); + + // Filter unused lints + let (lints_to_emit, lints_allowed) = &**tcx.lints_that_can_emit(()); + // let lints_to_emit = &lints_that_can_emit.0; + // let lints_allowed = &lints_that_can_emit.1; + + // Now, we'll filtered passes in a way that discards any lint that won't trigger. + // If any lint is a given pass is detected to be emitted, we will keep that pass. + // Otherwise, we don't + let mut filtered_passes: Vec>> = passes + .into_iter() + .filter(|pass| { + let pass = LintPass::get_lints(pass); + pass.iter().any(|&lint| { + let lint_name = name_without_tool(&lint.name.to_lowercase()).to_string(); + lints_to_emit.contains(&lint_name) + || (!lints_allowed.contains(&lint_name) + && lint.default_level != crate::Level::Allow) + }) + }) + .collect(); + + filtered_passes.push(Box::new(builtin_lints)); + + let pass = RuntimeCombinedLateLintPass { passes: &mut filtered_passes[..] }; late_lint_mod_inner(tcx, module_def_id, context, pass); } } @@ -454,3 +482,10 @@ pub fn check_crate<'tcx>(tcx: TyCtxt<'tcx>) { }, ); } + +/// Format name ignoring the name, useful for filtering non-used lints. +/// For example, 'clippy::my_lint' will turn into 'my_lint' +pub(crate) fn name_without_tool(name: &str) -> &str { + // Doing some calculations here to account for those separators + name.rsplit("::").next().unwrap_or(name) +} diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 89a67fc0d898..7ee8618bc553 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -1,6 +1,6 @@ use rustc_ast_pretty::pprust; -use rustc_data_structures::fx::FxIndexMap; -use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; +use rustc_data_structures::{fx::FxIndexMap, sync::Lrc}; +use rustc_errors::{Diag, DiagMessage, LintDiagnostic, MultiSpan}; use rustc_feature::{Features, GateIssue}; use rustc_hir::HirId; use rustc_hir::intravisit::{self, Visitor}; @@ -31,7 +31,7 @@ use crate::errors::{ OverruledAttributeSub, RequestedLevel, UnknownToolInScopedLint, UnsupportedGroup, }; use crate::fluent_generated as fluent; -use crate::late::unerased_lint_store; +use crate::late::{unerased_lint_store, name_without_tool}; use crate::lints::{ DeprecatedLintName, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified, OverruledAttributeLint, RemovedLint, RemovedLintFromCommandLine, RenamedLint, @@ -115,6 +115,36 @@ impl LintLevelSets { } } +/// Walk the whole crate collecting nodes where lint levels change +/// (e.g. `#[allow]` attributes), and joins that list with the warn-by-default +/// (and not allowed in the crate) and CLI lints. The returned value is a tuple +/// of 1. The lints that will emit (or at least, should run), and 2. +/// The lints that are allowed at the crate level and will not emit. +pub fn lints_that_can_emit(tcx: TyCtxt<'_>, (): ()) -> Lrc<(Vec, Vec)> { + let mut visitor = LintLevelMinimum::new(tcx); + visitor.process_opts(); + tcx.hir().walk_attributes(&mut visitor); + + let store = unerased_lint_store(&tcx.sess); + + let lint_groups = store.get_lint_groups(); + for group in lint_groups { + let binding = group.0.to_lowercase(); + let group_name = name_without_tool(&binding).to_string(); + if visitor.lints_to_emit.contains(&group_name) { + for lint in group.1 { + visitor.lints_to_emit.push(name_without_tool(&lint.to_string()).to_string()); + } + } else if visitor.lints_allowed.contains(&group_name) { + for lint in &group.1 { + visitor.lints_allowed.push(name_without_tool(&lint.to_string()).to_string()); + } + } + } + + Lrc::new((visitor.lints_to_emit, visitor.lints_allowed)) +} + #[instrument(level = "trace", skip(tcx), ret)] fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLevelMap { let store = unerased_lint_store(tcx.sess); @@ -301,6 +331,88 @@ impl<'tcx> Visitor<'tcx> for LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> { } } +/// Visitor with the only function of visiting every item-like in a crate and +/// computing the highest level that every lint gets put to. +/// +/// E.g., if a crate has a global #![allow(lint)] attribute, but a single item +/// uses #[warn(lint)], this visitor will set that lint level as `Warn` +struct LintLevelMinimum<'tcx> { + tcx: TyCtxt<'tcx>, + /// The actual list of detected lints. + lints_to_emit: Vec, + lints_allowed: Vec, +} + +impl<'tcx> LintLevelMinimum<'tcx> { + pub fn new(tcx: TyCtxt<'tcx>) -> Self { + Self { + tcx, + // That magic number is the current number of lints + some more for possible future lints + lints_to_emit: Vec::with_capacity(230), + lints_allowed: Vec::with_capacity(100), + } + } + + fn process_opts(&mut self) { + for (lint, level) in &self.tcx.sess.opts.lint_opts { + if *level == Level::Allow { + self.lints_allowed.push(lint.clone()); + } else { + self.lints_to_emit.push(lint.to_string()); + } + } + } +} + +impl<'tcx> Visitor<'tcx> for LintLevelMinimum<'tcx> { + type NestedFilter = nested_filter::All; + + fn nested_visit_map(&mut self) -> Self::Map { + self.tcx.hir() + } + + fn visit_attribute(&mut self, attribute: &'tcx ast::Attribute) { + if let Some(meta) = attribute.meta() { + if [sym::warn, sym::deny, sym::forbid, sym::expect] + .iter() + .any(|kind| meta.has_name(*kind)) + { + // SAFETY: Lint attributes are always a metalist inside a + // metalist (even with just one lint). + for meta_list in meta.meta_item_list().unwrap() { + // If it's a tool lint (e.g. clippy::my_clippy_lint) + if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { + if meta_item.path.segments.len() == 1 { + self.lints_to_emit.push( + // SAFETY: Lint attributes can only have literals + meta_list.ident().unwrap().name.as_str().to_string(), + ); + } else { + self.lints_to_emit + .push(meta_item.path.segments[1].ident.name.as_str().to_string()); + } + } + } + // We handle #![allow]s differently, as these remove checking rather than adding. + } else if meta.has_name(sym::allow) + && let ast::AttrStyle::Inner = attribute.style + { + for meta_list in meta.meta_item_list().unwrap() { + // If it's a tool lint (e.g. clippy::my_clippy_lint) + if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { + if meta_item.path.segments.len() == 1 { + self.lints_allowed.push(meta_list.name_or_empty().as_str().to_string()) + } else { + self.lints_allowed + .push(meta_item.path.segments[1].ident.name.as_str().to_string()); + } + } + } + } + } + } +} + pub struct LintLevelsBuilder<'s, P> { sess: &'s Session, features: &'s Features, @@ -931,7 +1043,8 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { } pub(crate) fn provide(providers: &mut Providers) { - *providers = Providers { shallow_lint_levels_on, ..*providers }; + *providers = + Providers { shallow_lint_levels_on, lints_that_can_emit, ..*providers }; } pub(crate) fn parse_lint_and_tool_name(lint_name: &str) -> (Option, &str) { diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 81352af3d48f..5984810961ff 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -170,7 +170,7 @@ early_lint_methods!( [ pub BuiltinCombinedEarlyLintPass, [ - UnusedParens: UnusedParens::new(), + UnusedParens: UnusedParens::default(), UnusedBraces: UnusedBraces, UnusedImportBraces: UnusedImportBraces, UnsafeCode: UnsafeCode, @@ -178,7 +178,7 @@ early_lint_methods!( AnonymousParameters: AnonymousParameters, EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(), NonCamelCaseTypes: NonCamelCaseTypes, - DeprecatedAttr: DeprecatedAttr::new(), + DeprecatedAttr: DeprecatedAttr::default(), WhileTrue: WhileTrue, NonAsciiIdents: NonAsciiIdents, HiddenUnicodeCodepoints: HiddenUnicodeCodepoints, @@ -601,25 +601,25 @@ fn register_builtins(store: &mut LintStore) { } fn register_internals(store: &mut LintStore) { - store.register_lints(&LintPassImpl::get_lints()); + store.register_lints(&LintPassImpl::default().get_lints()); store.register_early_pass(|| Box::new(LintPassImpl)); - store.register_lints(&DefaultHashTypes::get_lints()); + store.register_lints(&DefaultHashTypes::default().get_lints()); store.register_late_mod_pass(|_| Box::new(DefaultHashTypes)); - store.register_lints(&QueryStability::get_lints()); + store.register_lints(&QueryStability::default().get_lints()); store.register_late_mod_pass(|_| Box::new(QueryStability)); - store.register_lints(&ExistingDocKeyword::get_lints()); + store.register_lints(&ExistingDocKeyword::default().get_lints()); store.register_late_mod_pass(|_| Box::new(ExistingDocKeyword)); - store.register_lints(&TyTyKind::get_lints()); + store.register_lints(&TyTyKind::default().get_lints()); store.register_late_mod_pass(|_| Box::new(TyTyKind)); - store.register_lints(&TypeIr::get_lints()); + store.register_lints(&TypeIr::default().get_lints()); store.register_late_mod_pass(|_| Box::new(TypeIr)); - store.register_lints(&Diagnostics::get_lints()); + store.register_lints(&Diagnostics::default().get_lints()); store.register_late_mod_pass(|_| Box::new(Diagnostics)); - store.register_lints(&BadOptAccess::get_lints()); + store.register_lints(&BadOptAccess::default().get_lints()); store.register_late_mod_pass(|_| Box::new(BadOptAccess)); - store.register_lints(&PassByValue::get_lints()); + store.register_lints(&PassByValue::default().get_lints()); store.register_late_mod_pass(|_| Box::new(PassByValue)); - store.register_lints(&SpanUseEqCtxt::get_lints()); + store.register_lints(&SpanUseEqCtxt::default().get_lints()); store.register_late_mod_pass(|_| Box::new(SpanUseEqCtxt)); // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index a1d436e0d3db..3750f90a0448 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -110,7 +110,7 @@ macro_rules! declare_combined_late_lint_pass { $v fn get_lints() -> $crate::LintVec { let mut lints = Vec::new(); - $(lints.extend_from_slice(&$pass::get_lints());)* + $(lints.extend_from_slice(&$pass::default().get_lints());)* lints } } @@ -124,6 +124,9 @@ macro_rules! declare_combined_late_lint_pass { fn name(&self) -> &'static str { panic!() } + fn get_lints(&self) -> LintVec { + panic!() + } } ) } @@ -222,7 +225,7 @@ macro_rules! declare_combined_early_lint_pass { $v fn get_lints() -> $crate::LintVec { let mut lints = Vec::new(); - $(lints.extend_from_slice(&$pass::get_lints());)* + $(lints.extend_from_slice(&$pass::default().get_lints());)* lints } } @@ -236,6 +239,9 @@ macro_rules! declare_combined_early_lint_pass { fn name(&self) -> &'static str { panic!() } + fn get_lints(&self) -> LintVec { + panic!() + } } ) } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index db4413149a49..1fafa7d6bde0 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -165,7 +165,7 @@ declare_lint! { "detects ambiguous wide pointer comparisons" } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Default)] pub(crate) struct TypeLimits { /// Id of the last visited negated expression negated_expr_id: Option, diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 1a0072509614..a05616bf4866 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1025,8 +1025,8 @@ pub(crate) struct UnusedParens { parens_in_cast_in_lt: Vec, } -impl UnusedParens { - pub(crate) fn new() -> Self { +impl Default for UnusedParens { + fpub(crate) fn default() -> Self { Self { with_self_ty_parens: false, parens_in_cast_in_lt: Vec::new() } } } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 45a5ce0ca20e..5c3b1bb71f30 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -378,7 +378,8 @@ declare_lint! { /// will not overflow. pub ARITHMETIC_OVERFLOW, Deny, - "arithmetic operation overflows" + "arithmetic operation overflows", + [loadbearing: true] } declare_lint! { @@ -633,7 +634,8 @@ declare_lint! { /// is only available in a newer version. pub UNKNOWN_LINTS, Warn, - "unrecognized lint attribute" + "unrecognized lint attribute", + [loadbearing: true] } declare_lint! { diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index c01fa5c54d65..691f37f0977b 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -312,6 +312,10 @@ pub struct Lint { pub feature_gate: Option, pub crate_level_only: bool, + + /// `true` if this lint should not be filtered out under any circustamces + /// (e.g. the unknown_attributes lint) + pub loadbearing: bool, } /// Extra information for a future incompatibility lint. @@ -456,6 +460,7 @@ impl Lint { future_incompatible: None, feature_gate: None, crate_level_only: false, + loadbearing: false, } } @@ -863,7 +868,7 @@ macro_rules! declare_lint { $(#[$attr])* $vis $NAME, $Level, $desc, ); ); - ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr, + ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr, $([loadbearing: $loadbearing: literal])? $(@feature_gate = $gate:ident;)? $(@future_incompatible = FutureIncompatibleInfo { reason: $reason:expr, @@ -885,6 +890,7 @@ macro_rules! declare_lint { ..$crate::FutureIncompatibleInfo::default_fields_for_macro() }),)? $(edition_lint_opts: Some(($crate::Edition::$lint_edition, $crate::$edition_level)),)? + $(loadbearing: $loadbearing,)? ..$crate::Lint::default_fields_for_macro() }; ); @@ -895,6 +901,7 @@ macro_rules! declare_tool_lint { ( $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr $(, @feature_gate = $gate:ident;)? + $(, [loadbearing: $loadbearing: literal])? ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?} ); @@ -902,6 +909,7 @@ macro_rules! declare_tool_lint { $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, report_in_external_macro: $rep:expr $(, @feature_gate = $gate:ident;)? + $(, [loadbearing: $loadbearing: literal])? ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?} ); @@ -909,6 +917,7 @@ macro_rules! declare_tool_lint { $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, $external:expr $(, @feature_gate = $gate:ident;)? + $(, [loadbearing: $loadbearing: literal])? ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { @@ -921,6 +930,7 @@ macro_rules! declare_tool_lint { is_externally_loaded: true, $(feature_gate: Some(rustc_span::symbol::sym::$gate),)? crate_level_only: false, + $(loadbearing: $loadbearing,)? ..$crate::Lint::default_fields_for_macro() }; ); @@ -930,6 +940,7 @@ pub type LintVec = Vec<&'static Lint>; pub trait LintPass { fn name(&self) -> &'static str; + fn get_lints(&self) -> LintVec; } /// Implements `LintPass for $ty` with the given list of `Lint` statics. @@ -938,9 +949,7 @@ macro_rules! impl_lint_pass { ($ty:ty => [$($lint:expr),* $(,)?]) => { impl $crate::LintPass for $ty { fn name(&self) -> &'static str { stringify!($ty) } - } - impl $ty { - pub fn get_lints() -> $crate::LintVec { vec![$($lint),*] } + fn get_lints(&self) -> $crate::LintVec { vec![$($lint),*] } } }; } @@ -950,7 +959,18 @@ macro_rules! impl_lint_pass { #[macro_export] macro_rules! declare_lint_pass { ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => { - $(#[$m])* #[derive(Copy, Clone)] pub struct $name; + $(#[$m])* #[derive(Copy, Clone, Default)] pub struct $name; $crate::impl_lint_pass!($name => [$($lint),*]); }; } + +#[allow(rustc::lint_pass_impl_without_macro)] +impl LintPass for Box

{ + fn name(&self) -> &'static str { + (**self).name() + } + + fn get_lints(&self) -> LintVec { + (**self).get_lints() + } +} diff --git a/compiler/rustc_middle/Cargo.toml b/compiler/rustc_middle/Cargo.toml index 8cb602d9ea84..485d1c14df3c 100644 --- a/compiler/rustc_middle/Cargo.toml +++ b/compiler/rustc_middle/Cargo.toml @@ -27,6 +27,7 @@ rustc_graphviz = { path = "../rustc_graphviz" } rustc_hir = { path = "../rustc_hir" } rustc_hir_pretty = { path = "../rustc_hir_pretty" } rustc_index = { path = "../rustc_index" } +rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } rustc_query_system = { path = "../rustc_query_system" } rustc_serialize = { path = "../rustc_serialize" } diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index b5862565e8e8..eaec19700c84 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -117,7 +117,7 @@ impl ShallowLintLevelMap { /// This lint level is not usable for diagnostics, it needs to be corrected by /// `reveal_actual_level` beforehand. #[instrument(level = "trace", skip(self, tcx), ret)] - fn probe_for_lint_level( + pub fn probe_for_lint_level( &self, tcx: TyCtxt<'_>, id: LintId, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index f8ba606e087c..e90c3a4c23d3 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -422,6 +422,11 @@ rustc_queries! { desc { "computing `#[expect]`ed lints in this crate" } } + query lints_that_can_emit(_: ()) -> &'tcx Lrc<(Vec, Vec)> { + arena_cache + desc { "Computing all lints that are explicitly enabled or with a default level greater than Allow" } + } + query expn_that_defined(key: DefId) -> rustc_span::ExpnId { desc { |tcx| "getting the expansion that defined `{}`", tcx.def_path_str(key) } separate_provide_extern diff --git a/src/librustdoc/lint.rs b/src/librustdoc/lint.rs index bdfdeeabc5a3..679fc45df76b 100644 --- a/src/librustdoc/lint.rs +++ b/src/librustdoc/lint.rs @@ -2,7 +2,7 @@ use std::sync::LazyLock as Lazy; use rustc_data_structures::fx::FxHashMap; use rustc_lint::LintStore; -use rustc_lint_defs::{Lint, LintId, declare_tool_lint}; +use rustc_lint_defs::{Lint, LintId, LintPass, declare_tool_lint}; use rustc_session::{Session, lint}; /// This function is used to setup the lint initialization. By default, in rustdoc, everything @@ -31,9 +31,10 @@ where allowed_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned()); let lints = || { - lint::builtin::HardwiredLints::get_lints() + lint::builtin::HardwiredLints::default() + .get_lints() .into_iter() - .chain(rustc_lint::SoftLints::get_lints()) + .chain(rustc_lint::SoftLints::default().get_lints()) }; let lint_opts = lints() diff --git a/src/tools/clippy/clippy_lints/src/asm_syntax.rs b/src/tools/clippy/clippy_lints/src/asm_syntax.rs index 69a8eb7d94e7..9f3c24a9e806 100644 --- a/src/tools/clippy/clippy_lints/src/asm_syntax.rs +++ b/src/tools/clippy/clippy_lints/src/asm_syntax.rs @@ -3,7 +3,7 @@ use std::fmt; use clippy_utils::diagnostics::span_lint_and_then; use rustc_ast::ast::{Expr, ExprKind, InlineAsmOptions}; use rustc_ast::{InlineAsm, Item, ItemKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintPass, LintContext}; use rustc_session::declare_lint_pass; use rustc_span::Span; use rustc_target::asm::InlineAsmArch; diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/author.rs similarity index 99% rename from src/tools/clippy/clippy_lints/src/utils/author.rs rename to src/tools/clippy/clippy_lints/src/utils/internal_lints/author.rs index 31f9d84f5e46..0ed606a836e6 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/author.rs @@ -12,7 +12,7 @@ use rustc_span::symbol::{Ident, Symbol}; use std::cell::Cell; use std::fmt::{Display, Formatter, Write as _}; -declare_lint_pass!( +declare_clippy_lint!{ /// ### What it does /// Generates clippy code that detects the offending pattern /// @@ -44,8 +44,13 @@ declare_lint_pass!( /// // report your lint here /// } /// ``` - Author => [] -); + #[clippy::version = "1.0.0"] + pub AUTHOR, + internal, + "The author lint, see documentation at " +}; + +declare_lint_pass! { Author => [AUTHOR] } /// Writes a line of output with indentation added macro_rules! out { diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 13e9ead9a57f..abd10ac024c7 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -1,4 +1,3 @@ -pub mod author; pub mod dump_hir; pub mod format_args_collector; #[cfg(feature = "internal")] diff --git a/src/tools/clippy/tests/ui/author.rs b/src/tools/clippy/tests/ui-internal/author.rs similarity index 72% rename from src/tools/clippy/tests/ui/author.rs rename to src/tools/clippy/tests/ui-internal/author.rs index 0a1be3568967..eb1f3e3f8704 100644 --- a/src/tools/clippy/tests/ui/author.rs +++ b/src/tools/clippy/tests/ui-internal/author.rs @@ -1,3 +1,5 @@ +#![warn(clippy::author)] + fn main() { #[clippy::author] let x: char = 0x45 as char; diff --git a/src/tools/clippy/tests/ui/author.stdout b/src/tools/clippy/tests/ui-internal/author.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author.stdout rename to src/tools/clippy/tests/ui-internal/author.stdout diff --git a/src/tools/clippy/tests/ui/author/blocks.rs b/src/tools/clippy/tests/ui-internal/author/blocks.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/blocks.rs rename to src/tools/clippy/tests/ui-internal/author/blocks.rs diff --git a/src/tools/clippy/tests/ui/author/blocks.stdout b/src/tools/clippy/tests/ui-internal/author/blocks.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/blocks.stdout rename to src/tools/clippy/tests/ui-internal/author/blocks.stdout diff --git a/src/tools/clippy/tests/ui/author/call.rs b/src/tools/clippy/tests/ui-internal/author/call.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/call.rs rename to src/tools/clippy/tests/ui-internal/author/call.rs diff --git a/src/tools/clippy/tests/ui/author/call.stdout b/src/tools/clippy/tests/ui-internal/author/call.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/call.stdout rename to src/tools/clippy/tests/ui-internal/author/call.stdout diff --git a/src/tools/clippy/tests/ui/author/if.rs b/src/tools/clippy/tests/ui-internal/author/if.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/if.rs rename to src/tools/clippy/tests/ui-internal/author/if.rs diff --git a/src/tools/clippy/tests/ui/author/if.stdout b/src/tools/clippy/tests/ui-internal/author/if.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/if.stdout rename to src/tools/clippy/tests/ui-internal/author/if.stdout diff --git a/src/tools/clippy/tests/ui/author/issue_3849.rs b/src/tools/clippy/tests/ui-internal/author/issue_3849.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/issue_3849.rs rename to src/tools/clippy/tests/ui-internal/author/issue_3849.rs diff --git a/src/tools/clippy/tests/ui/author/issue_3849.stdout b/src/tools/clippy/tests/ui-internal/author/issue_3849.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/issue_3849.stdout rename to src/tools/clippy/tests/ui-internal/author/issue_3849.stdout diff --git a/src/tools/clippy/tests/ui/author/loop.rs b/src/tools/clippy/tests/ui-internal/author/loop.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/loop.rs rename to src/tools/clippy/tests/ui-internal/author/loop.rs diff --git a/src/tools/clippy/tests/ui/author/loop.stdout b/src/tools/clippy/tests/ui-internal/author/loop.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/loop.stdout rename to src/tools/clippy/tests/ui-internal/author/loop.stdout diff --git a/src/tools/clippy/tests/ui/author/macro_in_closure.rs b/src/tools/clippy/tests/ui-internal/author/macro_in_closure.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/macro_in_closure.rs rename to src/tools/clippy/tests/ui-internal/author/macro_in_closure.rs diff --git a/src/tools/clippy/tests/ui/author/macro_in_closure.stdout b/src/tools/clippy/tests/ui-internal/author/macro_in_closure.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/macro_in_closure.stdout rename to src/tools/clippy/tests/ui-internal/author/macro_in_closure.stdout diff --git a/src/tools/clippy/tests/ui/author/macro_in_loop.rs b/src/tools/clippy/tests/ui-internal/author/macro_in_loop.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/macro_in_loop.rs rename to src/tools/clippy/tests/ui-internal/author/macro_in_loop.rs diff --git a/src/tools/clippy/tests/ui/author/macro_in_loop.stdout b/src/tools/clippy/tests/ui-internal/author/macro_in_loop.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/macro_in_loop.stdout rename to src/tools/clippy/tests/ui-internal/author/macro_in_loop.stdout diff --git a/src/tools/clippy/tests/ui/author/matches.rs b/src/tools/clippy/tests/ui-internal/author/matches.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/matches.rs rename to src/tools/clippy/tests/ui-internal/author/matches.rs diff --git a/src/tools/clippy/tests/ui/author/matches.stdout b/src/tools/clippy/tests/ui-internal/author/matches.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/matches.stdout rename to src/tools/clippy/tests/ui-internal/author/matches.stdout diff --git a/src/tools/clippy/tests/ui/author/repeat.rs b/src/tools/clippy/tests/ui-internal/author/repeat.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/repeat.rs rename to src/tools/clippy/tests/ui-internal/author/repeat.rs diff --git a/src/tools/clippy/tests/ui/author/repeat.stdout b/src/tools/clippy/tests/ui-internal/author/repeat.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/repeat.stdout rename to src/tools/clippy/tests/ui-internal/author/repeat.stdout diff --git a/src/tools/clippy/tests/ui/author/struct.rs b/src/tools/clippy/tests/ui-internal/author/struct.rs similarity index 100% rename from src/tools/clippy/tests/ui/author/struct.rs rename to src/tools/clippy/tests/ui-internal/author/struct.rs diff --git a/src/tools/clippy/tests/ui/author/struct.stdout b/src/tools/clippy/tests/ui-internal/author/struct.stdout similarity index 100% rename from src/tools/clippy/tests/ui/author/struct.stdout rename to src/tools/clippy/tests/ui-internal/author/struct.stdout diff --git a/src/tools/clippy/tests/ui/no_lints.rs b/src/tools/clippy/tests/ui/no_lints.rs new file mode 100644 index 000000000000..a8467bb6ef78 --- /dev/null +++ b/src/tools/clippy/tests/ui/no_lints.rs @@ -0,0 +1,3 @@ +#![deny(clippy::all)] + +fn main() {} \ No newline at end of file diff --git a/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.rs b/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.rs index c3df917ed12d..6eb698c96f67 100644 --- a/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.rs +++ b/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.rs @@ -6,7 +6,7 @@ extern crate rustc_middle; extern crate rustc_session; -use rustc_session::lint::{LintPass, LintVec}; +use rustc_session::lint::{LintPass, LintVec, Lint}; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; declare_lint! { @@ -21,6 +21,10 @@ impl LintPass for Foo { //~ERROR implementing `LintPass` by hand fn name(&self) -> &'static str { "Foo" } + + fn get_lints(&self) -> Vec<&'static Lint> { + vec![TEST_LINT] + } } macro_rules! custom_lint_pass_macro { @@ -31,6 +35,10 @@ macro_rules! custom_lint_pass_macro { fn name(&self) -> &'static str { "Custom" } + + fn get_lints(&self) -> Vec<&'static Lint> { + vec![TEST_LINT] + } } }; } diff --git a/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.stderr b/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.stderr index ad6e93334cdc..824eb35424d9 100644 --- a/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.stderr +++ b/tests/ui-fulldeps/internal-lints/lint_pass_impl_without_macro.stderr @@ -12,7 +12,7 @@ LL | #![deny(rustc::lint_pass_impl_without_macro)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: implementing `LintPass` by hand - --> $DIR/lint_pass_impl_without_macro.rs:30:14 + --> $DIR/lint_pass_impl_without_macro.rs:34:14 | LL | impl LintPass for Custom { | ^^^^^^^^ From edc65776274d14fc7f7f93de66ac3b2d15bbbc37 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Mon, 27 May 2024 13:58:33 +0200 Subject: [PATCH 043/366] Change lints_to_emit to lints_that_actually_run --- compiler/rustc_lint/src/late.rs | 6 +-- compiler/rustc_lint/src/levels.rs | 40 ++++++++++--------- compiler/rustc_lint/src/shadowed_into_iter.rs | 2 +- compiler/rustc_middle/src/query/mod.rs | 2 +- 4 files changed, 27 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index ccd06ba612bc..c7187ee1b30e 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -373,8 +373,8 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( store.late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); // Filter unused lints - let (lints_to_emit, lints_allowed) = &**tcx.lints_that_can_emit(()); - // let lints_to_emit = &lints_that_can_emit.0; + let (lints_that_actually_run, lints_allowed) = &**tcx.lints_that_can_emit(()); + // let lints_that_actually_run = &lints_that_can_emit.0; // let lints_allowed = &lints_that_can_emit.1; // Now, we'll filtered passes in a way that discards any lint that won't trigger. @@ -386,7 +386,7 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( let pass = LintPass::get_lints(pass); pass.iter().any(|&lint| { let lint_name = name_without_tool(&lint.name.to_lowercase()).to_string(); - lints_to_emit.contains(&lint_name) + lints_that_actually_run.contains(&lint_name) || (!lints_allowed.contains(&lint_name) && lint.default_level != crate::Level::Allow) }) diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 7ee8618bc553..527fc1173512 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -1,6 +1,6 @@ use rustc_ast_pretty::pprust; -use rustc_data_structures::{fx::FxIndexMap, sync::Lrc}; -use rustc_errors::{Diag, DiagMessage, LintDiagnostic, MultiSpan}; +use rustc_data_structures::{fx::FxIndexMap, fx::FxIndexSet, sync::Lrc}; +use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; use rustc_feature::{Features, GateIssue}; use rustc_hir::HirId; use rustc_hir::intravisit::{self, Visitor}; @@ -120,7 +120,7 @@ impl LintLevelSets { /// (and not allowed in the crate) and CLI lints. The returned value is a tuple /// of 1. The lints that will emit (or at least, should run), and 2. /// The lints that are allowed at the crate level and will not emit. -pub fn lints_that_can_emit(tcx: TyCtxt<'_>, (): ()) -> Lrc<(Vec, Vec)> { +pub fn lints_that_can_emit(tcx: TyCtxt<'_>, (): ()) -> Lrc<(FxIndexSet, FxIndexSet)> { let mut visitor = LintLevelMinimum::new(tcx); visitor.process_opts(); tcx.hir().walk_attributes(&mut visitor); @@ -131,18 +131,18 @@ pub fn lints_that_can_emit(tcx: TyCtxt<'_>, (): ()) -> Lrc<(Vec, Vec Visitor<'tcx> for LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> { struct LintLevelMinimum<'tcx> { tcx: TyCtxt<'tcx>, /// The actual list of detected lints. - lints_to_emit: Vec, - lints_allowed: Vec, + lints_that_actually_run: FxIndexSet, + lints_allowed: FxIndexSet, } impl<'tcx> LintLevelMinimum<'tcx> { pub fn new(tcx: TyCtxt<'tcx>) -> Self { + let mut lints_that_actually_run = FxIndexSet::default(); + lints_that_actually_run.reserve(230); + let mut lints_allowed = FxIndexSet::default(); + lints_allowed.reserve(100); Self { tcx, // That magic number is the current number of lints + some more for possible future lints - lints_to_emit: Vec::with_capacity(230), - lints_allowed: Vec::with_capacity(100), + lints_that_actually_run, + lints_allowed, } } fn process_opts(&mut self) { for (lint, level) in &self.tcx.sess.opts.lint_opts { if *level == Level::Allow { - self.lints_allowed.push(lint.clone()); + self.lints_allowed.insert(lint.clone()); } else { - self.lints_to_emit.push(lint.to_string()); + self.lints_that_actually_run.insert(lint.to_string()); } } } @@ -383,13 +387,13 @@ impl<'tcx> Visitor<'tcx> for LintLevelMinimum<'tcx> { // If it's a tool lint (e.g. clippy::my_clippy_lint) if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { if meta_item.path.segments.len() == 1 { - self.lints_to_emit.push( + self.lints_that_actually_run.insert( // SAFETY: Lint attributes can only have literals meta_list.ident().unwrap().name.as_str().to_string(), ); } else { - self.lints_to_emit - .push(meta_item.path.segments[1].ident.name.as_str().to_string()); + self.lints_that_actually_run + .insert(meta_item.path.segments[1].ident.name.as_str().to_string()); } } } @@ -401,10 +405,10 @@ impl<'tcx> Visitor<'tcx> for LintLevelMinimum<'tcx> { // If it's a tool lint (e.g. clippy::my_clippy_lint) if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { if meta_item.path.segments.len() == 1 { - self.lints_allowed.push(meta_list.name_or_empty().as_str().to_string()) + self.lints_allowed.insert(meta_list.name_or_empty().as_str().to_string()); } else { self.lints_allowed - .push(meta_item.path.segments[1].ident.name.as_str().to_string()); + .insert(meta_item.path.segments[1].ident.name.as_str().to_string()); } } } diff --git a/compiler/rustc_lint/src/shadowed_into_iter.rs b/compiler/rustc_lint/src/shadowed_into_iter.rs index a73904cd7769..33a4ae606632 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -64,7 +64,7 @@ declare_lint! { }; } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Default)] pub(crate) struct ShadowedIntoIter; impl_lint_pass!(ShadowedIntoIter => [ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER]); diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index e90c3a4c23d3..b6cb11a2a2c6 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -422,7 +422,7 @@ rustc_queries! { desc { "computing `#[expect]`ed lints in this crate" } } - query lints_that_can_emit(_: ()) -> &'tcx Lrc<(Vec, Vec)> { + query lints_that_can_emit(_: ()) -> &'tcx Lrc<(FxIndexSet, FxIndexSet)> { arena_cache desc { "Computing all lints that are explicitly enabled or with a default level greater than Allow" } } From 71b4d108c7e71c15c0f61d737ebdc0e1cf559d3c Mon Sep 17 00:00:00 2001 From: blyxyas Date: Tue, 18 Jun 2024 22:44:28 +0200 Subject: [PATCH 044/366] Follow review comments (optimize the filtering) --- compiler/rustc_interface/src/passes.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 7 +- compiler/rustc_lint/src/late.rs | 64 +++--- compiler/rustc_lint/src/levels.rs | 202 +++++++++++------- compiler/rustc_lint/src/lib.rs | 2 +- compiler/rustc_lint/src/passes.rs | 13 +- compiler/rustc_lint/src/unused.rs | 2 +- compiler/rustc_lint_defs/src/builtin.rs | 5 +- compiler/rustc_middle/src/query/mod.rs | 3 +- compiler/rustc_session/src/session.rs | 1 + .../clippy/clippy_lints/src/asm_syntax.rs | 2 +- .../clippy_lints/src/cognitive_complexity.rs | 54 +++-- src/tools/clippy/clippy_lints/src/ctfe.rs | 54 +++++ src/tools/clippy/clippy_lints/src/lib.rs | 3 + .../src/utils/{internal_lints => }/author.rs | 12 +- .../clippy/clippy_lints/src/utils/mod.rs | 1 + 16 files changed, 276 insertions(+), 151 deletions(-) create mode 100644 src/tools/clippy/clippy_lints/src/ctfe.rs rename src/tools/clippy/clippy_lints/src/utils/{internal_lints => }/author.rs (99%) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index fd850d2f39a5..608d66184f0a 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -972,7 +972,7 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> { tcx.ensure().check_mod_privacy(module); }); }); - } + } // { sess.time("mir_checking", || { tcx.hir().mir_for }) } ); // This check has to be run after all lints are done processing. We don't diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index acd12f7f20df..33c87bbfb707 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -20,6 +20,7 @@ //! If you define a new `LateLintPass`, you will also need to add it to the //! `late_lint_methods!` invocation in `lib.rs`. +use std::default::Default; use std::fmt::Write; use ast::token::TokenKind; @@ -73,12 +74,10 @@ use crate::{ EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext, fluent_generated as fluent, }; - -use std::default::Default; -use std::fmt::Write; +// use std::fmt::Write; // hardwired lints from rustc_lint_defs -pub use rustc_session::lint::builtin::*; +// pub use rustc_session::lint::builtin::*; declare_lint! { /// The `while_true` lint detects `while true { }`. diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index c7187ee1b30e..f8bd873cdf58 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -24,13 +24,12 @@ use rustc_hir::def_id::{LocalDefId, LocalModDefId}; use rustc_hir::{HirId, intravisit as hir_visit}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::Session; -use rustc_session::lint::LintPass; +use rustc_session::{Session, lint::{LintPass, builtin::HardwiredLints}}; use rustc_span::Span; use tracing::debug; use crate::passes::LateLintPassObject; -use crate::{LateContext, LateLintPass, LintStore}; +use crate::{LateContext, LateLintPass, LintId, LintStore}; /// Extract the [`LintStore`] from [`Session`]. /// @@ -371,29 +370,24 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( } else { let passes: Vec<_> = store.late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); - // Filter unused lints - let (lints_that_actually_run, lints_allowed) = &**tcx.lints_that_can_emit(()); - // let lints_that_actually_run = &lints_that_can_emit.0; - // let lints_allowed = &lints_that_can_emit.1; - - // Now, we'll filtered passes in a way that discards any lint that won't trigger. - // If any lint is a given pass is detected to be emitted, we will keep that pass. - // Otherwise, we don't + let lints_that_dont_need_to_run = tcx.lints_that_dont_need_to_run(()); let mut filtered_passes: Vec>> = passes .into_iter() .filter(|pass| { - let pass = LintPass::get_lints(pass); - pass.iter().any(|&lint| { - let lint_name = name_without_tool(&lint.name.to_lowercase()).to_string(); - lints_that_actually_run.contains(&lint_name) - || (!lints_allowed.contains(&lint_name) - && lint.default_level != crate::Level::Allow) - }) + let lints = LintPass::get_lints(pass); + if lints.is_empty() { + true + } else { + lints + .iter() + .any(|lint| !lints_that_dont_need_to_run.contains(&LintId::of(lint))) + } }) .collect(); filtered_passes.push(Box::new(builtin_lints)); + filtered_passes.push(Box::new(HardwiredLints)); let pass = RuntimeCombinedLateLintPass { passes: &mut filtered_passes[..] }; late_lint_mod_inner(tcx, module_def_id, context, pass); @@ -426,7 +420,7 @@ fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>( fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { // Note: `passes` is often empty. - let mut passes: Vec<_> = + let passes: Vec<_> = unerased_lint_store(tcx.sess).late_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); if passes.is_empty() { @@ -444,7 +438,30 @@ fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { only_module: false, }; - let pass = RuntimeCombinedLateLintPass { passes: &mut passes[..] }; + let lints_that_dont_need_to_run = tcx.lints_that_dont_need_to_run(()); + + // dbg!(&lints_that_dont_need_to_run); + let mut filtered_passes: Vec>> = passes + .into_iter() + .filter(|pass| { + let lints = LintPass::get_lints(pass); + !lints.iter().all(|lint| lints_that_dont_need_to_run.contains(&LintId::of(lint))) + }) + .collect(); + + filtered_passes.push(Box::new(HardwiredLints)); + + // let mut filtered_passes: Vec>> = passes + // .into_iter() + // .filter(|pass| { + // let lints = LintPass::get_lints(pass); + // lints.iter() + // .any(|lint| + // !lints_that_dont_need_to_run.contains(&LintId::of(lint))) + // }).collect(); + // + + let pass = RuntimeCombinedLateLintPass { passes: &mut filtered_passes[..] }; late_lint_crate_inner(tcx, context, pass); } @@ -482,10 +499,3 @@ pub fn check_crate<'tcx>(tcx: TyCtxt<'tcx>) { }, ); } - -/// Format name ignoring the name, useful for filtering non-used lints. -/// For example, 'clippy::my_lint' will turn into 'my_lint' -pub(crate) fn name_without_tool(name: &str) -> &str { - // Doing some calculations here to account for those separators - name.rsplit("::").next().unwrap_or(name) -} diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 527fc1173512..f5323c295d0e 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -1,5 +1,5 @@ use rustc_ast_pretty::pprust; -use rustc_data_structures::{fx::FxIndexMap, fx::FxIndexSet, sync::Lrc}; +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; use rustc_feature::{Features, GateIssue}; use rustc_hir::HirId; @@ -31,7 +31,7 @@ use crate::errors::{ OverruledAttributeSub, RequestedLevel, UnknownToolInScopedLint, UnsupportedGroup, }; use crate::fluent_generated as fluent; -use crate::late::{unerased_lint_store, name_without_tool}; +use crate::late::{unerased_lint_store /*name_without_tool*/}; use crate::lints::{ DeprecatedLintName, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified, OverruledAttributeLint, RemovedLint, RemovedLintFromCommandLine, RenamedLint, @@ -115,34 +115,41 @@ impl LintLevelSets { } } -/// Walk the whole crate collecting nodes where lint levels change -/// (e.g. `#[allow]` attributes), and joins that list with the warn-by-default -/// (and not allowed in the crate) and CLI lints. The returned value is a tuple -/// of 1. The lints that will emit (or at least, should run), and 2. -/// The lints that are allowed at the crate level and will not emit. -pub fn lints_that_can_emit(tcx: TyCtxt<'_>, (): ()) -> Lrc<(FxIndexSet, FxIndexSet)> { - let mut visitor = LintLevelMinimum::new(tcx); +fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet { + let store = unerased_lint_store(&tcx.sess); + + let dont_need_to_run: FxIndexSet = store + .get_lints() + .into_iter() + .filter_map(|lint| { + if !lint.loadbearing && lint.default_level(tcx.sess.edition()) == Level::Allow { + Some(LintId::of(lint)) + } else { + None + } + }) + .collect(); + + let mut visitor = LintLevelMaximum { tcx, dont_need_to_run }; visitor.process_opts(); tcx.hir().walk_attributes(&mut visitor); - let store = unerased_lint_store(&tcx.sess); + // let lint_groups = store.get_lint_groups(); + // for group in lint_groups { + // let binding = group.0.to_lowercase(); + // let group_name = name_without_tool(&binding).to_string(); + // if visitor.lints_that_actually_run.contains(&group_name) { + // for lint in group.1 { + // visitor.lints_that_actually_run.insert(name_without_tool(&lint.to_string()).to_string()); + // } + // } else if visitor.lints_allowed.contains(&group_name) { + // for lint in &group.1 { + // visitor.lints_allowed.insert(name_without_tool(&lint.to_string()).to_string()); + // } + // } + // } - let lint_groups = store.get_lint_groups(); - for group in lint_groups { - let binding = group.0.to_lowercase(); - let group_name = name_without_tool(&binding).to_string(); - if visitor.lints_that_actually_run.contains(&group_name) { - for lint in group.1 { - visitor.lints_that_actually_run.insert(name_without_tool(&lint.to_string()).to_string()); - } - } else if visitor.lints_allowed.contains(&group_name) { - for lint in &group.1 { - visitor.lints_allowed.insert(name_without_tool(&lint.to_string()).to_string()); - } - } - } - - Lrc::new((visitor.lints_that_actually_run, visitor.lints_allowed)) + visitor.dont_need_to_run } #[instrument(level = "trace", skip(tcx), ret)] @@ -336,39 +343,29 @@ impl<'tcx> Visitor<'tcx> for LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> { /// /// E.g., if a crate has a global #![allow(lint)] attribute, but a single item /// uses #[warn(lint)], this visitor will set that lint level as `Warn` -struct LintLevelMinimum<'tcx> { +struct LintLevelMaximum<'tcx> { tcx: TyCtxt<'tcx>, /// The actual list of detected lints. - lints_that_actually_run: FxIndexSet, - lints_allowed: FxIndexSet, + dont_need_to_run: FxIndexSet, } -impl<'tcx> LintLevelMinimum<'tcx> { - pub fn new(tcx: TyCtxt<'tcx>) -> Self { - let mut lints_that_actually_run = FxIndexSet::default(); - lints_that_actually_run.reserve(230); - let mut lints_allowed = FxIndexSet::default(); - lints_allowed.reserve(100); - Self { - tcx, - // That magic number is the current number of lints + some more for possible future lints - lints_that_actually_run, - lints_allowed, - } - } - +impl<'tcx> LintLevelMaximum<'tcx> { fn process_opts(&mut self) { - for (lint, level) in &self.tcx.sess.opts.lint_opts { - if *level == Level::Allow { - self.lints_allowed.insert(lint.clone()); - } else { - self.lints_that_actually_run.insert(lint.to_string()); + let store = unerased_lint_store(self.tcx.sess); + for (lint_group, level) in &self.tcx.sess.opts.lint_opts { + if *level != Level::Allow { + let Ok(lints) = store.find_lints(lint_group) else { + return; + }; + for lint in lints { + self.dont_need_to_run.swap_remove(&lint); + } } } } } -impl<'tcx> Visitor<'tcx> for LintLevelMinimum<'tcx> { +impl<'tcx> Visitor<'tcx> for LintLevelMaximum<'tcx> { type NestedFilter = nested_filter::All; fn nested_visit_map(&mut self) -> Self::Map { @@ -376,42 +373,82 @@ impl<'tcx> Visitor<'tcx> for LintLevelMinimum<'tcx> { } fn visit_attribute(&mut self, attribute: &'tcx ast::Attribute) { - if let Some(meta) = attribute.meta() { - if [sym::warn, sym::deny, sym::forbid, sym::expect] - .iter() - .any(|kind| meta.has_name(*kind)) - { + match Level::from_attr(attribute) { + Some( + Level::Warn + | Level::Deny + | Level::Forbid + | Level::Expect(..) + | Level::ForceWarn(..), + ) => { + let store = unerased_lint_store(self.tcx.sess); + let Some(meta) = attribute.meta() else { return }; // SAFETY: Lint attributes are always a metalist inside a // metalist (even with just one lint). - for meta_list in meta.meta_item_list().unwrap() { - // If it's a tool lint (e.g. clippy::my_clippy_lint) - if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { - if meta_item.path.segments.len() == 1 { - self.lints_that_actually_run.insert( - // SAFETY: Lint attributes can only have literals - meta_list.ident().unwrap().name.as_str().to_string(), - ); - } else { - self.lints_that_actually_run - .insert(meta_item.path.segments[1].ident.name.as_str().to_string()); - } - } - } - // We handle #![allow]s differently, as these remove checking rather than adding. - } else if meta.has_name(sym::allow) - && let ast::AttrStyle::Inner = attribute.style - { - for meta_list in meta.meta_item_list().unwrap() { - // If it's a tool lint (e.g. clippy::my_clippy_lint) - if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { - if meta_item.path.segments.len() == 1 { - self.lints_allowed.insert(meta_list.name_or_empty().as_str().to_string()); - } else { - self.lints_allowed - .insert(meta_item.path.segments[1].ident.name.as_str().to_string()); - } + let Some(meta_item_list) = meta.meta_item_list() else { return }; + + for meta_list in meta_item_list { + // Convert Path to String + let Some(meta_item) = meta_list.meta_item() else { return }; + let ident: &str = &meta_item + .path + .segments + .iter() + .map(|segment| segment.ident.as_str()) + .collect::>() + .join("::"); + let Ok(lints) = store.find_lints( + // SAFETY: Lint attributes can only have literals + ident, + ) else { + return; + }; + for lint in lints { + self.dont_need_to_run.swap_remove(&lint); } + // // If it's a tool lint (e.g. clippy::my_clippy_lint) + // if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { + // if meta_item.path.segments.len() == 1 { + // let Ok(lints) = store.find_lints( + // // SAFETY: Lint attributes can only have literals + // meta_list.ident().unwrap().name.as_str(), + // ) else { + // return; + // }; + // for lint in lints { + // dbg!("LINT REMOVED", &lint); + // self.dont_need_to_run.swap_remove(&lint); + // } + // } else { + // let Ok(lints) = store.find_lints( + // // SAFETY: Lint attributes can only have literals + // meta_item.path.segments[1].ident.name.as_str(), + // ) else { + // return; + // }; + // for lint in lints { + // dbg!("LINT REMOVED", &lint); + // self.dont_need_to_run.swap_remove(&lint); + // } + // } } + // We handle #![allow]s differently, as these remove checking rather than adding. + } // Some(Level::Allow) if ast::AttrStyle::Inner == attribute.style => { + // for meta_list in meta.meta_item_list().unwrap() { + // // If it's a tool lint (e.g. clippy::my_clippy_lint) + // if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { + // if meta_item.path.segments.len() == 1 { + // self.lints_allowed + // .insert(meta_list.name_or_empty().as_str().to_string()); + // } else { + // self.lints_allowed + // .insert(meta_item.path.segments[1].ident.name.as_str().to_string()); + // } + // } + // } + // } + _ => { + return; } } } @@ -1047,8 +1084,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { } pub(crate) fn provide(providers: &mut Providers) { - *providers = - Providers { shallow_lint_levels_on, lints_that_can_emit, ..*providers }; + *providers = Providers { shallow_lint_levels_on, lints_that_dont_need_to_run, ..*providers }; } pub(crate) fn parse_lint_and_tool_name(lint_name: &str) -> (Option, &str) { diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 5984810961ff..11dd17bcd4ae 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -199,7 +199,6 @@ late_lint_methods!( ForLoopsOverFallibles: ForLoopsOverFallibles, DerefIntoDynSupertrait: DerefIntoDynSupertrait, DropForgetUseless: DropForgetUseless, - HardwiredLints: HardwiredLints, ImproperCTypesDeclarations: ImproperCTypesDeclarations, ImproperCTypesDefinitions: ImproperCTypesDefinitions, InvalidFromUtf8: InvalidFromUtf8, @@ -280,6 +279,7 @@ fn register_builtins(store: &mut LintStore) { store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints()); store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints()); store.register_lints(&foreign_modules::get_lints()); + store.register_lints(&HardwiredLints::default().get_lints()); add_lint_group!( "nonstandard_style", diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index 3750f90a0448..6dbcdefe08d4 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -70,7 +70,18 @@ macro_rules! declare_late_lint_pass { // for all the `check_*` methods. late_lint_methods!(declare_late_lint_pass, []); -impl LateLintPass<'_> for HardwiredLints {} +impl LateLintPass<'_> for HardwiredLints { + fn check_fn( + &mut self, + _: &LateContext<'_>, + _: rustc_hir::intravisit::FnKind<'_>, + _: &'_ rustc_hir::FnDecl<'_>, + _: &'_ rustc_hir::Body<'_>, + _: rustc_span::Span, + _: rustc_span::def_id::LocalDefId, + ) { + } +} #[macro_export] macro_rules! expand_combined_late_lint_pass_method { diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index a05616bf4866..a7ac847c0180 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1026,7 +1026,7 @@ pub(crate) struct UnusedParens { } impl Default for UnusedParens { - fpub(crate) fn default() -> Self { + fn default() -> Self { Self { with_self_ty_parens: false, parens_in_cast_in_lt: Vec::new() } } } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 5c3b1bb71f30..df86e9de22e4 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -12,8 +12,6 @@ use rustc_span::edition::Edition; use crate::{FutureIncompatibilityReason, declare_lint, declare_lint_pass}; declare_lint_pass! { - /// Does nothing as a lint pass, but registers some `Lint`s - /// that are used by other parts of the compiler. HardwiredLints => [ // tidy-alphabetical-start ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, @@ -403,7 +401,8 @@ declare_lint! { /// `panic!` or `unreachable!` macro instead in case the panic is intended. pub UNCONDITIONAL_PANIC, Deny, - "operation will cause a panic at runtime" + "operation will cause a panic at runtime", + [loadbearing: true] } declare_lint! { diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b6cb11a2a2c6..99e166286d26 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -29,6 +29,7 @@ use rustc_hir::def_id::{ use rustc_hir::lang_items::{LangItem, LanguageItems}; use rustc_hir::{Crate, ItemLocalId, ItemLocalMap, TraitCandidate}; use rustc_index::IndexVec; +use rustc_lint_defs::LintId; use rustc_macros::rustc_queries; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{QueryCache, QueryMode, QueryState, try_get_cached}; @@ -422,7 +423,7 @@ rustc_queries! { desc { "computing `#[expect]`ed lints in this crate" } } - query lints_that_can_emit(_: ()) -> &'tcx Lrc<(FxIndexSet, FxIndexSet)> { + query lints_that_dont_need_to_run(_: ()) -> &'tcx FxIndexSet { arena_cache desc { "Computing all lints that are explicitly enabled or with a default level greater than Allow" } } diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 27879d817b20..c8f46226a3e9 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -187,6 +187,7 @@ pub struct Session { /// errors. pub ctfe_backtrace: Lock, + // pub force_ctfe: bool, /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a /// const check, optionally with the relevant feature gate. We use this to /// warn about unleashing, but with a single diagnostic instead of dozens that diff --git a/src/tools/clippy/clippy_lints/src/asm_syntax.rs b/src/tools/clippy/clippy_lints/src/asm_syntax.rs index 9f3c24a9e806..69a8eb7d94e7 100644 --- a/src/tools/clippy/clippy_lints/src/asm_syntax.rs +++ b/src/tools/clippy/clippy_lints/src/asm_syntax.rs @@ -3,7 +3,7 @@ use std::fmt; use clippy_utils::diagnostics::span_lint_and_then; use rustc_ast::ast::{Expr, ExprKind, InlineAsmOptions}; use rustc_ast::{InlineAsm, Item, ItemKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext}; use rustc_session::declare_lint_pass; use rustc_span::Span; use rustc_target::asm::InlineAsmArch; diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index 495d8ce3fa70..b027c289a7fc 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -8,30 +8,44 @@ use core::ops::ControlFlow; use rustc_ast::ast::Attribute; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, Expr, ExprKind, FnDecl}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::Level::Allow; +use rustc_lint::{LateContext, LateLintPass, Lint, LintContext}; use rustc_session::impl_lint_pass; use rustc_span::def_id::LocalDefId; use rustc_span::{Span, sym}; -declare_clippy_lint! { - /// ### What it does - /// Checks for methods with high cognitive complexity. - /// - /// ### Why is this bad? - /// Methods of high cognitive complexity tend to be hard to - /// both read and maintain. Also LLVM will tend to optimize small methods better. - /// - /// ### Known problems - /// Sometimes it's hard to find a way to reduce the - /// complexity. - /// - /// ### Example - /// You'll see it when you get the warning. - #[clippy::version = "1.35.0"] - pub COGNITIVE_COMPLEXITY, - nursery, - "functions that should be split up into multiple functions" -} +use crate::LintInfo; + +pub static COGNITIVE_COMPLEXITY: &Lint = &Lint { + name: &"clippy::COGNITIVE_COMPLEXITY", + default_level: Allow, + desc: "functions that should be split up into multiple functions", + edition_lint_opts: None, + report_in_external_macro: true, + future_incompatible: None, + is_externally_loaded: true, + crate_level_only: false, + loadbearing: true, + ..Lint::default_fields_for_macro() +}; +pub(crate) static COGNITIVE_COMPLEXITY_INFO: &'static LintInfo = &LintInfo { + lint: &COGNITIVE_COMPLEXITY, + category: crate::LintCategory::Nursery, + explanation: r"### What it does +Checks for methods with high cognitive complexity. + +### Why is this bad? +Methods of high cognitive complexity tend to be hard to both read and maintain. +Also LLVM will tend to optimize small methods better. + +### Known problems +Sometimes it's hard to find a way to reduce the complexity. + +### Example +You'll see it when you get the warning.", + version: Some("1.35.0"), + location: "#L0", +}; pub struct CognitiveComplexity { limit: LimitStack, diff --git a/src/tools/clippy/clippy_lints/src/ctfe.rs b/src/tools/clippy/clippy_lints/src/ctfe.rs new file mode 100644 index 000000000000..7b9f71810a99 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/ctfe.rs @@ -0,0 +1,54 @@ +use rustc_hir::def_id::LocalDefId; +use rustc_hir::intravisit::FnKind; +use rustc_hir::{Body, FnDecl}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_session::declare_lint_pass; +use rustc_span::Span; + +declare_clippy_lint! { + /// ### What it does + /// Checks for comparisons where one side of the relation is + /// either the minimum or maximum value for its type and warns if it involves a + /// case that is always true or always false. Only integer and boolean types are + /// checked. + /// + /// ### Why is this bad? + /// An expression like `min <= x` may misleadingly imply + /// that it is possible for `x` to be less than the minimum. Expressions like + /// `max < x` are probably mistakes. + /// + /// ### Known problems + /// For `usize` the size of the current compile target will + /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such + /// a comparison to detect target pointer width will trigger this lint. One can + /// use `mem::sizeof` and compare its value or conditional compilation + /// attributes + /// like `#[cfg(target_pointer_width = "64")] ..` instead. + /// + /// ### Example + /// ```no_run + /// let vec: Vec = Vec::new(); + /// if vec.len() <= 0 {} + /// if 100 > i32::MAX {} + /// ``` + #[clippy::version = "1.82.0"] + pub CLIPPY_CTFE, + correctness, + "a comparison with a maximum or minimum value that is always true or false" +} + +declare_lint_pass! { ClippyCtfe => [CLIPPY_CTFE] } + +impl<'tcx> LateLintPass<'tcx> for ClippyCtfe { + fn check_fn( + &mut self, + cx: &LateContext<'_>, + _: FnKind<'tcx>, + _: &'tcx FnDecl<'tcx>, + _: &'tcx Body<'tcx>, + _: Span, + defid: LocalDefId, + ) { + cx.tcx.ensure().mir_drops_elaborated_and_const_checked(defid); // Lint + } +} diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index 6e29dde2211f..a5d2f6a4122a 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -65,6 +65,7 @@ extern crate clippy_utils; #[cfg_attr(feature = "internal", allow(clippy::missing_clippy_version_attribute))] mod utils; +pub mod ctfe; // VERY important lint (rust#125116) pub mod declared_lints; pub mod deprecated_lints; @@ -605,6 +606,8 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) { }); } + store.register_late_pass(|_| Box::new(ctfe::ClippyCtfe)); + store.register_late_pass(move |_| Box::new(operators::arithmetic_side_effects::ArithmeticSideEffects::new(conf))); store.register_late_pass(|_| Box::new(utils::dump_hir::DumpHir)); store.register_late_pass(|_| Box::new(utils::author::Author)); diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs similarity index 99% rename from src/tools/clippy/clippy_lints/src/utils/internal_lints/author.rs rename to src/tools/clippy/clippy_lints/src/utils/author.rs index 0ed606a836e6..f4e166327afc 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -12,7 +12,7 @@ use rustc_span::symbol::{Ident, Symbol}; use std::cell::Cell; use std::fmt::{Display, Formatter, Write as _}; -declare_clippy_lint!{ +declare_lint_pass!( /// ### What it does /// Generates clippy code that detects the offending pattern /// @@ -44,13 +44,8 @@ declare_clippy_lint!{ /// // report your lint here /// } /// ``` - #[clippy::version = "1.0.0"] - pub AUTHOR, - internal, - "The author lint, see documentation at " -}; - -declare_lint_pass! { Author => [AUTHOR] } + Author => [] +); /// Writes a line of output with indentation added macro_rules! out { @@ -803,3 +798,4 @@ fn path_to_string(path: &QPath<'_>) -> Result { inner(&mut s, path)?; Ok(s) } + diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index abd10ac024c7..13e9ead9a57f 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -1,3 +1,4 @@ +pub mod author; pub mod dump_hir; pub mod format_args_collector; #[cfg(feature = "internal")] From 637d5cc56fcc11afadd4ffaefa237c11f47cdfee Mon Sep 17 00:00:00 2001 From: blyxyas Date: Sat, 7 Sep 2024 12:13:03 +0200 Subject: [PATCH 045/366] Remove module passes filtering --- compiler/rustc_interface/src/passes.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 8 +- compiler/rustc_lint/src/internal.rs | 4 +- compiler/rustc_lint/src/late.rs | 45 ++----- compiler/rustc_lint/src/levels.rs | 124 +++++------------- compiler/rustc_lint/src/lib.rs | 22 ++-- compiler/rustc_lint/src/passes.rs | 17 +-- compiler/rustc_lint_defs/src/builtin.rs | 8 +- compiler/rustc_lint_defs/src/lib.rs | 23 ++-- compiler/rustc_middle/src/lint.rs | 2 +- compiler/rustc_session/src/session.rs | 1 - src/librustdoc/lint.rs | 7 +- .../clippy_lints/src/cognitive_complexity.rs | 4 +- src/tools/clippy/clippy_lints/src/ctfe.rs | 51 +++---- src/tools/clippy/clippy_lints/src/lib.rs | 2 +- .../clippy/clippy_lints/src/utils/author.rs | 1 - 16 files changed, 109 insertions(+), 212 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 608d66184f0a..fd850d2f39a5 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -972,7 +972,7 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> { tcx.ensure().check_mod_privacy(module); }); }); - } // { sess.time("mir_checking", || { tcx.hir().mir_for }) } + } ); // This check has to be run after all lints are done processing. We don't diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 33c87bbfb707..b2c7f1d3cec0 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -20,7 +20,6 @@ //! If you define a new `LateLintPass`, you will also need to add it to the //! `late_lint_methods!` invocation in `lib.rs`. -use std::default::Default; use std::fmt::Write; use ast::token::TokenKind; @@ -74,11 +73,6 @@ use crate::{ EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext, fluent_generated as fluent, }; -// use std::fmt::Write; - -// hardwired lints from rustc_lint_defs -// pub use rustc_session::lint::builtin::*; - declare_lint! { /// The `while_true` lint detects `while true { }`. /// @@ -247,7 +241,7 @@ declare_lint! { UNSAFE_CODE, Allow, "usage of `unsafe` code and other potentially unsound constructs", - [loadbearing: true] + @eval_always = true } declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]); diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 0f4f58efd8e6..11e9e933dd9c 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -430,7 +430,7 @@ declare_tool_lint! { Deny, "prevent creation of diagnostics which cannot be translated", report_in_external_macro: true, - [loadbearing: true] + eval_always: true } declare_tool_lint! { @@ -444,7 +444,7 @@ declare_tool_lint! { Deny, "prevent diagnostic creation outside of `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls", report_in_external_macro: true, - [loadbearing: true] + eval_always: true } declare_lint_pass!(Diagnostics => [UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL]); diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index f8bd873cdf58..ea7a44dd1235 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -24,7 +24,9 @@ use rustc_hir::def_id::{LocalDefId, LocalModDefId}; use rustc_hir::{HirId, intravisit as hir_visit}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::{Session, lint::{LintPass, builtin::HardwiredLints}}; +use rustc_session::Session; +use rustc_session::lint::LintPass; +use rustc_session::lint::builtin::HardwiredLints; use rustc_span::Span; use tracing::debug; @@ -368,28 +370,15 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( if store.late_module_passes.is_empty() { late_lint_mod_inner(tcx, module_def_id, context, builtin_lints); } else { - let passes: Vec<_> = - store.late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); - // Filter unused lints - let lints_that_dont_need_to_run = tcx.lints_that_dont_need_to_run(()); - let mut filtered_passes: Vec>> = passes - .into_iter() - .filter(|pass| { - let lints = LintPass::get_lints(pass); - if lints.is_empty() { - true - } else { - lints - .iter() - .any(|lint| !lints_that_dont_need_to_run.contains(&LintId::of(lint))) - } - }) - .collect(); + let builtin_lints = Box::new(builtin_lints) as Box>; + let mut binding = store + .late_module_passes + .iter() + .map(|mk_pass| (mk_pass)(tcx)) + .chain(std::iter::once(builtin_lints)) + .collect::>(); - filtered_passes.push(Box::new(builtin_lints)); - filtered_passes.push(Box::new(HardwiredLints)); - - let pass = RuntimeCombinedLateLintPass { passes: &mut filtered_passes[..] }; + let pass = RuntimeCombinedLateLintPass { passes: binding.as_mut_slice() }; late_lint_mod_inner(tcx, module_def_id, context, pass); } } @@ -440,7 +429,6 @@ fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { let lints_that_dont_need_to_run = tcx.lints_that_dont_need_to_run(()); - // dbg!(&lints_that_dont_need_to_run); let mut filtered_passes: Vec>> = passes .into_iter() .filter(|pass| { @@ -450,17 +438,6 @@ fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { .collect(); filtered_passes.push(Box::new(HardwiredLints)); - - // let mut filtered_passes: Vec>> = passes - // .into_iter() - // .filter(|pass| { - // let lints = LintPass::get_lints(pass); - // lints.iter() - // .any(|lint| - // !lints_that_dont_need_to_run.contains(&LintId::of(lint))) - // }).collect(); - // - let pass = RuntimeCombinedLateLintPass { passes: &mut filtered_passes[..] }; late_lint_crate_inner(tcx, context, pass); } diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index f5323c295d0e..64e1cddf2484 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -31,7 +31,7 @@ use crate::errors::{ OverruledAttributeSub, RequestedLevel, UnknownToolInScopedLint, UnsupportedGroup, }; use crate::fluent_generated as fluent; -use crate::late::{unerased_lint_store /*name_without_tool*/}; +use crate::late::unerased_lint_store; use crate::lints::{ DeprecatedLintName, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified, OverruledAttributeLint, RemovedLint, RemovedLintFromCommandLine, RenamedLint, @@ -122,7 +122,7 @@ fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet { .get_lints() .into_iter() .filter_map(|lint| { - if !lint.loadbearing && lint.default_level(tcx.sess.edition()) == Level::Allow { + if !lint.eval_always && lint.default_level(tcx.sess.edition()) == Level::Allow { Some(LintId::of(lint)) } else { None @@ -134,21 +134,6 @@ fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet { visitor.process_opts(); tcx.hir().walk_attributes(&mut visitor); - // let lint_groups = store.get_lint_groups(); - // for group in lint_groups { - // let binding = group.0.to_lowercase(); - // let group_name = name_without_tool(&binding).to_string(); - // if visitor.lints_that_actually_run.contains(&group_name) { - // for lint in group.1 { - // visitor.lints_that_actually_run.insert(name_without_tool(&lint.to_string()).to_string()); - // } - // } else if visitor.lints_allowed.contains(&group_name) { - // for lint in &group.1 { - // visitor.lints_allowed.insert(name_without_tool(&lint.to_string()).to_string()); - // } - // } - // } - visitor.dont_need_to_run } @@ -372,83 +357,44 @@ impl<'tcx> Visitor<'tcx> for LintLevelMaximum<'tcx> { self.tcx.hir() } + /// FIXME(blyxyas): In a future revision, we should also graph #![allow]s, + /// but that is handled with more care fn visit_attribute(&mut self, attribute: &'tcx ast::Attribute) { - match Level::from_attr(attribute) { + if matches!( + Level::from_attr(attribute), Some( Level::Warn - | Level::Deny - | Level::Forbid - | Level::Expect(..) - | Level::ForceWarn(..), - ) => { - let store = unerased_lint_store(self.tcx.sess); - let Some(meta) = attribute.meta() else { return }; - // SAFETY: Lint attributes are always a metalist inside a - // metalist (even with just one lint). - let Some(meta_item_list) = meta.meta_item_list() else { return }; + | Level::Deny + | Level::Forbid + | Level::Expect(..) + | Level::ForceWarn(..), + ) + ) { + let store = unerased_lint_store(self.tcx.sess); + let Some(meta) = attribute.meta() else { return }; + // SAFETY: Lint attributes are always a metalist inside a + // metalist (even with just one lint). + let Some(meta_item_list) = meta.meta_item_list() else { return }; - for meta_list in meta_item_list { - // Convert Path to String - let Some(meta_item) = meta_list.meta_item() else { return }; - let ident: &str = &meta_item - .path - .segments - .iter() - .map(|segment| segment.ident.as_str()) - .collect::>() - .join("::"); - let Ok(lints) = store.find_lints( - // SAFETY: Lint attributes can only have literals - ident, - ) else { - return; - }; - for lint in lints { - self.dont_need_to_run.swap_remove(&lint); - } - // // If it's a tool lint (e.g. clippy::my_clippy_lint) - // if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { - // if meta_item.path.segments.len() == 1 { - // let Ok(lints) = store.find_lints( - // // SAFETY: Lint attributes can only have literals - // meta_list.ident().unwrap().name.as_str(), - // ) else { - // return; - // }; - // for lint in lints { - // dbg!("LINT REMOVED", &lint); - // self.dont_need_to_run.swap_remove(&lint); - // } - // } else { - // let Ok(lints) = store.find_lints( - // // SAFETY: Lint attributes can only have literals - // meta_item.path.segments[1].ident.name.as_str(), - // ) else { - // return; - // }; - // for lint in lints { - // dbg!("LINT REMOVED", &lint); - // self.dont_need_to_run.swap_remove(&lint); - // } - // } + for meta_list in meta_item_list { + // Convert Path to String + let Some(meta_item) = meta_list.meta_item() else { return }; + let ident: &str = &meta_item + .path + .segments + .iter() + .map(|segment| segment.ident.as_str()) + .collect::>() + .join("::"); + let Ok(lints) = store.find_lints( + // SAFETY: Lint attributes can only have literals + ident, + ) else { + return; + }; + for lint in lints { + self.dont_need_to_run.swap_remove(&lint); } - // We handle #![allow]s differently, as these remove checking rather than adding. - } // Some(Level::Allow) if ast::AttrStyle::Inner == attribute.style => { - // for meta_list in meta.meta_item_list().unwrap() { - // // If it's a tool lint (e.g. clippy::my_clippy_lint) - // if let ast::NestedMetaItem::MetaItem(meta_item) = meta_list { - // if meta_item.path.segments.len() == 1 { - // self.lints_allowed - // .insert(meta_list.name_or_empty().as_str().to_string()); - // } else { - // self.lints_allowed - // .insert(meta_item.path.segments[1].ident.name.as_str().to_string()); - // } - // } - // } - // } - _ => { - return; } } } diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 11dd17bcd4ae..1607c8abfb50 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -279,7 +279,7 @@ fn register_builtins(store: &mut LintStore) { store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints()); store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints()); store.register_lints(&foreign_modules::get_lints()); - store.register_lints(&HardwiredLints::default().get_lints()); + store.register_lints(&HardwiredLints::lint_vec()); add_lint_group!( "nonstandard_style", @@ -601,25 +601,25 @@ fn register_builtins(store: &mut LintStore) { } fn register_internals(store: &mut LintStore) { - store.register_lints(&LintPassImpl::default().get_lints()); + store.register_lints(&LintPassImpl::lint_vec()); store.register_early_pass(|| Box::new(LintPassImpl)); - store.register_lints(&DefaultHashTypes::default().get_lints()); + store.register_lints(&DefaultHashTypes::lint_vec()); store.register_late_mod_pass(|_| Box::new(DefaultHashTypes)); - store.register_lints(&QueryStability::default().get_lints()); + store.register_lints(&QueryStability::lint_vec()); store.register_late_mod_pass(|_| Box::new(QueryStability)); - store.register_lints(&ExistingDocKeyword::default().get_lints()); + store.register_lints(&ExistingDocKeyword::lint_vec()); store.register_late_mod_pass(|_| Box::new(ExistingDocKeyword)); - store.register_lints(&TyTyKind::default().get_lints()); + store.register_lints(&TyTyKind::lint_vec()); store.register_late_mod_pass(|_| Box::new(TyTyKind)); - store.register_lints(&TypeIr::default().get_lints()); + store.register_lints(&TypeIr::lint_vec()); store.register_late_mod_pass(|_| Box::new(TypeIr)); - store.register_lints(&Diagnostics::default().get_lints()); + store.register_lints(&Diagnostics::lint_vec()); store.register_late_mod_pass(|_| Box::new(Diagnostics)); - store.register_lints(&BadOptAccess::default().get_lints()); + store.register_lints(&BadOptAccess::lint_vec()); store.register_late_mod_pass(|_| Box::new(BadOptAccess)); - store.register_lints(&PassByValue::default().get_lints()); + store.register_lints(&PassByValue::lint_vec()); store.register_late_mod_pass(|_| Box::new(PassByValue)); - store.register_lints(&SpanUseEqCtxt::default().get_lints()); + store.register_lints(&SpanUseEqCtxt::lint_vec()); store.register_late_mod_pass(|_| Box::new(SpanUseEqCtxt)); // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index 6dbcdefe08d4..18244b14e791 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -70,18 +70,7 @@ macro_rules! declare_late_lint_pass { // for all the `check_*` methods. late_lint_methods!(declare_late_lint_pass, []); -impl LateLintPass<'_> for HardwiredLints { - fn check_fn( - &mut self, - _: &LateContext<'_>, - _: rustc_hir::intravisit::FnKind<'_>, - _: &'_ rustc_hir::FnDecl<'_>, - _: &'_ rustc_hir::Body<'_>, - _: rustc_span::Span, - _: rustc_span::def_id::LocalDefId, - ) { - } -} +impl LateLintPass<'_> for HardwiredLints {} #[macro_export] macro_rules! expand_combined_late_lint_pass_method { @@ -121,7 +110,7 @@ macro_rules! declare_combined_late_lint_pass { $v fn get_lints() -> $crate::LintVec { let mut lints = Vec::new(); - $(lints.extend_from_slice(&$pass::default().get_lints());)* + $(lints.extend_from_slice(&$pass::lint_vec());)* lints } } @@ -236,7 +225,7 @@ macro_rules! declare_combined_early_lint_pass { $v fn get_lints() -> $crate::LintVec { let mut lints = Vec::new(); - $(lints.extend_from_slice(&$pass::default().get_lints());)* + $(lints.extend_from_slice(&$pass::lint_vec());)* lints } } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index df86e9de22e4..3d8da0536bdc 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -12,6 +12,8 @@ use rustc_span::edition::Edition; use crate::{FutureIncompatibilityReason, declare_lint, declare_lint_pass}; declare_lint_pass! { + /// Does nothing as a lint pass, but registers some `Lint`s + /// that are used by other parts of the compiler. HardwiredLints => [ // tidy-alphabetical-start ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, @@ -377,7 +379,7 @@ declare_lint! { pub ARITHMETIC_OVERFLOW, Deny, "arithmetic operation overflows", - [loadbearing: true] + @eval_always = true } declare_lint! { @@ -402,7 +404,7 @@ declare_lint! { pub UNCONDITIONAL_PANIC, Deny, "operation will cause a panic at runtime", - [loadbearing: true] + @eval_always = true } declare_lint! { @@ -634,7 +636,7 @@ declare_lint! { pub UNKNOWN_LINTS, Warn, "unrecognized lint attribute", - [loadbearing: true] + @eval_always = true } declare_lint! { diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 691f37f0977b..da0accb0e093 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -315,7 +315,7 @@ pub struct Lint { /// `true` if this lint should not be filtered out under any circustamces /// (e.g. the unknown_attributes lint) - pub loadbearing: bool, + pub eval_always: bool, } /// Extra information for a future incompatibility lint. @@ -460,7 +460,7 @@ impl Lint { future_incompatible: None, feature_gate: None, crate_level_only: false, - loadbearing: false, + eval_always: false, } } @@ -868,7 +868,8 @@ macro_rules! declare_lint { $(#[$attr])* $vis $NAME, $Level, $desc, ); ); - ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr, $([loadbearing: $loadbearing: literal])? + ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr, + $(@eval_always = $eval_always:literal)? $(@feature_gate = $gate:ident;)? $(@future_incompatible = FutureIncompatibleInfo { reason: $reason:expr, @@ -890,7 +891,7 @@ macro_rules! declare_lint { ..$crate::FutureIncompatibleInfo::default_fields_for_macro() }),)? $(edition_lint_opts: Some(($crate::Edition::$lint_edition, $crate::$edition_level)),)? - $(loadbearing: $loadbearing,)? + $(eval_always: $eval_always,)? ..$crate::Lint::default_fields_for_macro() }; ); @@ -900,8 +901,8 @@ macro_rules! declare_lint { macro_rules! declare_tool_lint { ( $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr + $(, @eval_always = $eval_always:literal)? $(, @feature_gate = $gate:ident;)? - $(, [loadbearing: $loadbearing: literal])? ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?} ); @@ -909,15 +910,15 @@ macro_rules! declare_tool_lint { $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, report_in_external_macro: $rep:expr $(, @feature_gate = $gate:ident;)? - $(, [loadbearing: $loadbearing: literal])? + $(, eval_always: $eval_always: literal)? ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?} ); ( $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, $external:expr + $(, @eval_always: $eval_always: literal)? $(, @feature_gate = $gate:ident;)? - $(, [loadbearing: $loadbearing: literal])? ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { @@ -930,7 +931,7 @@ macro_rules! declare_tool_lint { is_externally_loaded: true, $(feature_gate: Some(rustc_span::symbol::sym::$gate),)? crate_level_only: false, - $(loadbearing: $loadbearing,)? + $(eval_always: $eval_always,)? ..$crate::Lint::default_fields_for_macro() }; ); @@ -951,6 +952,10 @@ macro_rules! impl_lint_pass { fn name(&self) -> &'static str { stringify!($ty) } fn get_lints(&self) -> $crate::LintVec { vec![$($lint),*] } } + impl $ty { + #[allow(unused)] + pub fn lint_vec() -> $crate::LintVec { vec![$($lint),*] } + } }; } @@ -959,7 +964,7 @@ macro_rules! impl_lint_pass { #[macro_export] macro_rules! declare_lint_pass { ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => { - $(#[$m])* #[derive(Copy, Clone, Default)] pub struct $name; + $(#[$m])* #[derive(Copy, Clone)] pub struct $name; $crate::impl_lint_pass!($name => [$($lint),*]); }; } diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index eaec19700c84..b5862565e8e8 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -117,7 +117,7 @@ impl ShallowLintLevelMap { /// This lint level is not usable for diagnostics, it needs to be corrected by /// `reveal_actual_level` beforehand. #[instrument(level = "trace", skip(self, tcx), ret)] - pub fn probe_for_lint_level( + fn probe_for_lint_level( &self, tcx: TyCtxt<'_>, id: LintId, diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index c8f46226a3e9..27879d817b20 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -187,7 +187,6 @@ pub struct Session { /// errors. pub ctfe_backtrace: Lock, - // pub force_ctfe: bool, /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a /// const check, optionally with the relevant feature gate. We use this to /// warn about unleashing, but with a single diagnostic instead of dozens that diff --git a/src/librustdoc/lint.rs b/src/librustdoc/lint.rs index 679fc45df76b..2afb9e549d90 100644 --- a/src/librustdoc/lint.rs +++ b/src/librustdoc/lint.rs @@ -2,7 +2,7 @@ use std::sync::LazyLock as Lazy; use rustc_data_structures::fx::FxHashMap; use rustc_lint::LintStore; -use rustc_lint_defs::{Lint, LintId, LintPass, declare_tool_lint}; +use rustc_lint_defs::{Lint, LintId, declare_tool_lint}; use rustc_session::{Session, lint}; /// This function is used to setup the lint initialization. By default, in rustdoc, everything @@ -31,10 +31,9 @@ where allowed_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned()); let lints = || { - lint::builtin::HardwiredLints::default() - .get_lints() + lint::builtin::HardwiredLints::lint_vec() .into_iter() - .chain(rustc_lint::SoftLints::default().get_lints()) + .chain(rustc_lint::SoftLints::lint_vec()) }; let lint_opts = lints() diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index b027c289a7fc..91cb8b78ba8c 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -25,7 +25,7 @@ pub static COGNITIVE_COMPLEXITY: &Lint = &Lint { future_incompatible: None, is_externally_loaded: true, crate_level_only: false, - loadbearing: true, + eval_always: true, ..Lint::default_fields_for_macro() }; pub(crate) static COGNITIVE_COMPLEXITY_INFO: &'static LintInfo = &LintInfo { @@ -44,7 +44,7 @@ Sometimes it's hard to find a way to reduce the complexity. ### Example You'll see it when you get the warning.", version: Some("1.35.0"), - location: "#L0", + location: "clippy_lints/src/cognitive_complexity.rs#L47", }; pub struct CognitiveComplexity { diff --git a/src/tools/clippy/clippy_lints/src/ctfe.rs b/src/tools/clippy/clippy_lints/src/ctfe.rs index 7b9f71810a99..ddb4eb821659 100644 --- a/src/tools/clippy/clippy_lints/src/ctfe.rs +++ b/src/tools/clippy/clippy_lints/src/ctfe.rs @@ -1,41 +1,28 @@ use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl}; -use rustc_lint::{LateContext, LateLintPass}; +use rustc_lint::Level::Deny; +use rustc_lint::{LateContext, LateLintPass, Lint}; use rustc_session::declare_lint_pass; use rustc_span::Span; -declare_clippy_lint! { - /// ### What it does - /// Checks for comparisons where one side of the relation is - /// either the minimum or maximum value for its type and warns if it involves a - /// case that is always true or always false. Only integer and boolean types are - /// checked. - /// - /// ### Why is this bad? - /// An expression like `min <= x` may misleadingly imply - /// that it is possible for `x` to be less than the minimum. Expressions like - /// `max < x` are probably mistakes. - /// - /// ### Known problems - /// For `usize` the size of the current compile target will - /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such - /// a comparison to detect target pointer width will trigger this lint. One can - /// use `mem::sizeof` and compare its value or conditional compilation - /// attributes - /// like `#[cfg(target_pointer_width = "64")] ..` instead. - /// - /// ### Example - /// ```no_run - /// let vec: Vec = Vec::new(); - /// if vec.len() <= 0 {} - /// if 100 > i32::MAX {} - /// ``` - #[clippy::version = "1.82.0"] - pub CLIPPY_CTFE, - correctness, - "a comparison with a maximum or minimum value that is always true or false" -} +/// Ensures that Constant-time Function Evaluation is being done (specifically, MIR lint passes). +/// See rust-lang/rust#125116 for more info. +#[clippy::version = "1.82.0"] +pub static CLIPPY_CTFE: &Lint = &Lint { + name: &"clippy::CLIPPY_CTFE", + default_level: Deny, + desc: "Ensure CTFE is being made", + edition_lint_opts: None, + report_in_external_macro: true, + future_incompatible: None, + is_externally_loaded: true, + crate_level_only: false, + eval_always: true, + ..Lint::default_fields_for_macro() +}; + +// No static CLIPPY_CTFE_INFO because we want this lint to be invisible declare_lint_pass! { ClippyCtfe => [CLIPPY_CTFE] } diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index a5d2f6a4122a..88a227f5b6db 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -65,7 +65,7 @@ extern crate clippy_utils; #[cfg_attr(feature = "internal", allow(clippy::missing_clippy_version_attribute))] mod utils; -pub mod ctfe; // VERY important lint (rust#125116) +pub mod ctfe; // Very important lint (rust#125116) pub mod declared_lints; pub mod deprecated_lints; diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index f4e166327afc..31f9d84f5e46 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -798,4 +798,3 @@ fn path_to_string(path: &QPath<'_>) -> Result { inner(&mut s, path)?; Ok(s) } - From 8a40884e1c606ac92326ed5ea444eb78d06da975 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Fri, 11 Oct 2024 00:31:17 +0200 Subject: [PATCH 046/366] Unify syntax (all to @eval_always) --- compiler/rustc_lint/src/internal.rs | 4 ++-- compiler/rustc_lint_defs/src/lib.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 11e9e933dd9c..7dec6dbdc05c 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -430,7 +430,7 @@ declare_tool_lint! { Deny, "prevent creation of diagnostics which cannot be translated", report_in_external_macro: true, - eval_always: true + @eval_always = true } declare_tool_lint! { @@ -444,7 +444,7 @@ declare_tool_lint! { Deny, "prevent diagnostic creation outside of `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls", report_in_external_macro: true, - eval_always: true + @eval_always = true } declare_lint_pass!(Diagnostics => [UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL]); diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index da0accb0e093..320668a5dbff 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -910,14 +910,14 @@ macro_rules! declare_tool_lint { $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, report_in_external_macro: $rep:expr $(, @feature_gate = $gate:ident;)? - $(, eval_always: $eval_always: literal)? + $(, @eval_always = $eval_always: literal)? ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?} ); ( $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, $external:expr - $(, @eval_always: $eval_always: literal)? + $(, @eval_always = $eval_always: literal)? $(, @feature_gate = $gate:ident;)? ) => ( $(#[$attr])* From ddad55f6c214357f48134d00050c6dbfcf1d9215 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Tue, 15 Oct 2024 22:15:07 +0200 Subject: [PATCH 047/366] Apply review comments + use `shallow_lint_levels_on` --- compiler/rustc_lint/src/late.rs | 2 +- compiler/rustc_lint/src/levels.rs | 20 +++++++++++++++----- compiler/rustc_lint_defs/src/lib.rs | 11 ----------- src/tools/clippy/clippy_lints/src/ctfe.rs | 2 +- src/tools/clippy/clippy_lints/src/lib.rs | 2 +- 5 files changed, 18 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index ea7a44dd1235..9b1877599bae 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -432,7 +432,7 @@ fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { let mut filtered_passes: Vec>> = passes .into_iter() .filter(|pass| { - let lints = LintPass::get_lints(pass); + let lints = (**pass).get_lints(); !lints.iter().all(|lint| lints_that_dont_need_to_run.contains(&LintId::of(lint))) }) .collect(); diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 64e1cddf2484..2c12899fad0e 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -2,8 +2,8 @@ use rustc_ast_pretty::pprust; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; use rustc_feature::{Features, GateIssue}; -use rustc_hir::HirId; use rustc_hir::intravisit::{self, Visitor}; +use rustc_hir::{CRATE_HIR_ID, HirId}; use rustc_index::IndexVec; use rustc_middle::bug; use rustc_middle::hir::nested_filter; @@ -118,12 +118,22 @@ impl LintLevelSets { fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet { let store = unerased_lint_store(&tcx.sess); + let map = tcx.shallow_lint_levels_on(rustc_hir::CRATE_OWNER_ID); + let dont_need_to_run: FxIndexSet = store .get_lints() .into_iter() .filter_map(|lint| { - if !lint.eval_always && lint.default_level(tcx.sess.edition()) == Level::Allow { - Some(LintId::of(lint)) + if !lint.eval_always { + let lint_level = map.lint_level_id_at_node(tcx, LintId::of(lint), CRATE_HIR_ID); + if matches!(lint_level, (Level::Allow, ..)) + || (matches!(lint_level, (.., LintLevelSource::Default))) + && lint.default_level(tcx.sess.edition()) == Level::Allow + { + Some(LintId::of(lint)) + } else { + None + } } else { None } @@ -372,7 +382,7 @@ impl<'tcx> Visitor<'tcx> for LintLevelMaximum<'tcx> { ) { let store = unerased_lint_store(self.tcx.sess); let Some(meta) = attribute.meta() else { return }; - // SAFETY: Lint attributes are always a metalist inside a + // Lint attributes are always a metalist inside a // metalist (even with just one lint). let Some(meta_item_list) = meta.meta_item_list() else { return }; @@ -387,7 +397,7 @@ impl<'tcx> Visitor<'tcx> for LintLevelMaximum<'tcx> { .collect::>() .join("::"); let Ok(lints) = store.find_lints( - // SAFETY: Lint attributes can only have literals + // Lint attributes can only have literals ident, ) else { return; diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 320668a5dbff..418caa699e2b 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -968,14 +968,3 @@ macro_rules! declare_lint_pass { $crate::impl_lint_pass!($name => [$($lint),*]); }; } - -#[allow(rustc::lint_pass_impl_without_macro)] -impl LintPass for Box

{ - fn name(&self) -> &'static str { - (**self).name() - } - - fn get_lints(&self) -> LintVec { - (**self).get_lints() - } -} diff --git a/src/tools/clippy/clippy_lints/src/ctfe.rs b/src/tools/clippy/clippy_lints/src/ctfe.rs index ddb4eb821659..93d0ad789beb 100644 --- a/src/tools/clippy/clippy_lints/src/ctfe.rs +++ b/src/tools/clippy/clippy_lints/src/ctfe.rs @@ -7,7 +7,7 @@ use rustc_session::declare_lint_pass; use rustc_span::Span; /// Ensures that Constant-time Function Evaluation is being done (specifically, MIR lint passes). -/// See rust-lang/rust#125116 for more info. +/// As Clippy deactivates codegen, this lint ensures that CTFE (used in hard errors) is still ran. #[clippy::version = "1.82.0"] pub static CLIPPY_CTFE: &Lint = &Lint { name: &"clippy::CLIPPY_CTFE", diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index 88a227f5b6db..14110539709d 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -65,7 +65,7 @@ extern crate clippy_utils; #[cfg_attr(feature = "internal", allow(clippy::missing_clippy_version_attribute))] mod utils; -pub mod ctfe; // Very important lint (rust#125116) +pub mod ctfe; // Very important lint, do not remove (rust#125116) pub mod declared_lints; pub mod deprecated_lints; From 2372217f82d6f3a5e04b4537bbeee0bce98f008e Mon Sep 17 00:00:00 2001 From: Giga Bowser <45986823+Giga-Bowser@users.noreply.github.com> Date: Sat, 19 Oct 2024 11:59:52 -0400 Subject: [PATCH 048/366] Combine entry points for wrapping/unwrapping return types --- .../src/handlers/unwrap_return_type.rs | 414 +++++++----- .../src/handlers/wrap_return_type.rs | 598 ++++++++++-------- .../crates/ide-assists/src/lib.rs | 6 +- 3 files changed, 592 insertions(+), 426 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs index b7f873c7798e..64d5e2c9b821 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs @@ -22,9 +22,6 @@ use crate::{AssistContext, AssistId, AssistKind, Assists}; // ``` // fn foo() -> i32 { 42i32 } // ``` -pub(crate) fn unwrap_option_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - unwrap_return_type(acc, ctx, UnwrapperKind::Option) -} // Assist: unwrap_result_return_type // @@ -38,15 +35,8 @@ pub(crate) fn unwrap_option_return_type(acc: &mut Assists, ctx: &AssistContext<' // ``` // fn foo() -> i32 { 42i32 } // ``` -pub(crate) fn unwrap_result_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - unwrap_return_type(acc, ctx, UnwrapperKind::Result) -} -fn unwrap_return_type( - acc: &mut Assists, - ctx: &AssistContext<'_>, - kind: UnwrapperKind, -) -> Option<()> { +pub(crate) fn unwrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let ret_type = ctx.find_node_at_offset::()?; let parent = ret_type.syntax().parent()?; let body = match_ast! { @@ -65,11 +55,12 @@ fn unwrap_return_type( let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else { return None; }; - let core_enum = - kind.core_type(FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()))?; - if ret_enum != core_enum { - return None; - } + + let famous_defs = FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()); + + let kind = UnwrapperKind::ALL + .iter() + .find(|k| matches!(k.core_type(&famous_defs), Some(core_type) if ret_enum == core_type))?; let happy_type = extract_wrapped_type(type_ref)?; @@ -149,6 +140,8 @@ enum UnwrapperKind { } impl UnwrapperKind { + const ALL: &'static [UnwrapperKind] = &[UnwrapperKind::Option, UnwrapperKind::Result]; + fn assist_id(&self) -> AssistId { let s = match self { UnwrapperKind::Option => "unwrap_option_return_type", @@ -165,7 +158,7 @@ impl UnwrapperKind { } } - fn core_type(&self, famous_defs: FamousDefs<'_, '_>) -> Option { + fn core_type(&self, famous_defs: &FamousDefs<'_, '_>) -> Option { match self { UnwrapperKind::Option => famous_defs.core_option_Option(), UnwrapperKind::Result => famous_defs.core_result_Result(), @@ -209,14 +202,14 @@ fn is_unit_type(ty: &ast::Type) -> bool { #[cfg(test)] mod tests { - use crate::tests::{check_assist, check_assist_not_applicable}; + use crate::tests::{check_assist_by_label, check_assist_not_applicable_by_label}; use super::*; #[test] fn unwrap_option_return_type_simple() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -230,13 +223,14 @@ fn foo() -> i32 { return 42i32; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_unit_type() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option<()$0> { @@ -247,11 +241,12 @@ fn foo() -> Option<()$0> { fn foo() { } "#, + "Unwrap Option return type", ); // Unformatted return type - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option<()$0>{ @@ -262,13 +257,14 @@ fn foo() -> Option<()$0>{ fn foo() { } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_none() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -288,13 +284,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_ending_with_parent() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -314,13 +311,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_break_split_tail() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -344,13 +342,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_closure() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() { @@ -368,13 +367,14 @@ fn foo() { }; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_return_type_bad_cursor() { - check_assist_not_applicable( - unwrap_option_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> i32 { @@ -382,13 +382,14 @@ fn foo() -> i32 { return 42i32; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - unwrap_option_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() { @@ -398,24 +399,26 @@ fn foo() { }; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_closure_non_block() { - check_assist_not_applicable( - unwrap_option_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() { || -> i$032 3; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_return_type_already_not_option_std() { - check_assist_not_applicable( - unwrap_option_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -423,13 +426,14 @@ fn foo() -> i32$0 { return 42i32; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_return_type_already_not_option_closure() { - check_assist_not_applicable( - unwrap_option_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() { @@ -439,13 +443,14 @@ fn foo() { }; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() ->$0 Option { @@ -459,13 +464,14 @@ fn foo() -> i32 { 42i32 } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_closure() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() { @@ -483,13 +489,14 @@ fn foo() { }; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_only() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { Some(42i32) } @@ -497,13 +504,14 @@ fn foo() -> Option { Some(42i32) } r#" fn foo() -> i32 { 42i32 } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_block_like() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option$0 { @@ -523,13 +531,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_without_block_closure() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() { @@ -553,13 +562,14 @@ fn foo() { }; } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_nested_if() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option$0 { @@ -587,13 +597,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_await() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option async fn foo() -> Option { @@ -621,13 +632,14 @@ async fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_array() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option<[i32; 3]$0> { Some([1, 2, 3]) } @@ -635,13 +647,14 @@ fn foo() -> Option<[i32; 3]$0> { Some([1, 2, 3]) } r#" fn foo() -> [i32; 3] { [1, 2, 3] } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_cast() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -$0> Option { @@ -669,13 +682,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_block_like_match() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -695,13 +709,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_loop_with_tail() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -723,13 +738,14 @@ fn foo() -> i32 { my_var } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_loop_in_let_stmt() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -747,13 +763,14 @@ fn foo() -> i32 { my_var } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_block_like_match_return_expr() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option$0 { @@ -775,10 +792,11 @@ fn foo() -> i32 { res } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -802,13 +820,14 @@ fn foo() -> i32 { res } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_block_like_match_deeper() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -852,13 +871,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_tail_block_like_early_return() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -878,13 +898,14 @@ fn foo() -> i32 { 53i32 } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_in_tail_position() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(num: i32) -> $0Option { @@ -896,13 +917,14 @@ fn foo(num: i32) -> i32 { return num } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_closure() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> Option { @@ -932,10 +954,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> Option { @@ -977,13 +1000,14 @@ fn foo(the_field: u32) -> u32 { t.unwrap_or_else(|| the_field) } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_simple_with_weird_forms() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -1015,10 +1039,11 @@ fn foo() -> i32 { } } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> Option { @@ -1056,10 +1081,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> Option { @@ -1085,10 +1111,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> Option { @@ -1116,10 +1143,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> Option { @@ -1147,13 +1175,14 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_option_return_type_nested_type() { - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option, result fn foo() -> Option> { @@ -1165,10 +1194,11 @@ fn foo() -> Result { Ok(42) } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option, result fn foo() -> Option, ()>> { @@ -1180,10 +1210,11 @@ fn foo() -> Result, ()> { Err() } "#, + "Unwrap Option return type", ); - check_assist( - unwrap_option_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: option, result, iterators fn foo() -> Option$0> { @@ -1195,13 +1226,14 @@ fn foo() -> impl Iterator { Some(42).into_iter() } "#, + "Unwrap Option return type", ); } #[test] fn unwrap_result_return_type_simple() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1215,13 +1247,14 @@ fn foo() -> i32 { return 42i32; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_unit_type() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result<(), Box> { @@ -1232,11 +1265,12 @@ fn foo() -> Result<(), Box> { fn foo() { } "#, + "Unwrap Result return type", ); // Unformatted return type - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result<(), Box>{ @@ -1247,13 +1281,14 @@ fn foo() -> Result<(), Box>{ fn foo() { } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_ending_with_parent() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result> { @@ -1273,13 +1308,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_break_split_tail() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1303,13 +1339,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_closure() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() { @@ -1327,13 +1364,14 @@ fn foo() { }; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_return_type_bad_cursor() { - check_assist_not_applicable( - unwrap_result_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> i32 { @@ -1341,13 +1379,14 @@ fn foo() -> i32 { return 42i32; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - unwrap_result_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() { @@ -1357,24 +1396,26 @@ fn foo() { }; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_closure_non_block() { - check_assist_not_applicable( - unwrap_result_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() { || -> i$032 3; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_return_type_already_not_result_std() { - check_assist_not_applicable( - unwrap_result_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1382,13 +1423,14 @@ fn foo() -> i32$0 { return 42i32; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_return_type_already_not_result_closure() { - check_assist_not_applicable( - unwrap_result_return_type, + check_assist_not_applicable_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() { @@ -1398,13 +1440,14 @@ fn foo() { }; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() ->$0 Result { @@ -1418,13 +1461,14 @@ fn foo() -> i32 { 42i32 } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_closure() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() { @@ -1442,13 +1486,14 @@ fn foo() { }; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_only() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { Ok(42i32) } @@ -1456,13 +1501,14 @@ fn foo() -> Result { Ok(42i32) } r#" fn foo() -> i32 { 42i32 } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_block_like() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result$0 { @@ -1482,13 +1528,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_without_block_closure() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() { @@ -1512,13 +1559,14 @@ fn foo() { }; } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_nested_if() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result$0 { @@ -1546,13 +1594,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_await() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result async fn foo() -> Result { @@ -1580,13 +1629,14 @@ async fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_array() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result<[i32; 3]$0> { Ok([1, 2, 3]) } @@ -1594,13 +1644,14 @@ fn foo() -> Result<[i32; 3]$0> { Ok([1, 2, 3]) } r#" fn foo() -> [i32; 3] { [1, 2, 3] } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_cast() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -$0> Result { @@ -1628,13 +1679,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_block_like_match() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1654,13 +1706,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_loop_with_tail() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1682,13 +1735,14 @@ fn foo() -> i32 { my_var } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_loop_in_let_stmt() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1706,13 +1760,14 @@ fn foo() -> i32 { my_var } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_block_like_match_return_expr() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result$0 { @@ -1734,10 +1789,11 @@ fn foo() -> i32 { res } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1761,13 +1817,14 @@ fn foo() -> i32 { res } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_block_like_match_deeper() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1811,13 +1868,14 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_tail_block_like_early_return() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1837,13 +1895,14 @@ fn foo() -> i32 { 53i32 } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_in_tail_position() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(num: i32) -> $0Result { @@ -1855,13 +1914,14 @@ fn foo(num: i32) -> i32 { return num } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_closure() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> Result { @@ -1891,10 +1951,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> Result { @@ -1936,13 +1997,14 @@ fn foo(the_field: u32) -> u32 { t.unwrap_or_else(|| the_field) } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_simple_with_weird_forms() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1974,10 +2036,11 @@ fn foo() -> i32 { } } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> Result { @@ -2015,10 +2078,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> Result { @@ -2044,10 +2108,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> Result { @@ -2075,10 +2140,11 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> Result { @@ -2106,13 +2172,14 @@ fn foo(the_field: u32) -> u32 { the_field } "#, + "Unwrap Result return type", ); } #[test] fn unwrap_result_return_type_nested_type() { - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result, option fn foo() -> Result, ()> { @@ -2124,10 +2191,11 @@ fn foo() -> Option { Some(42) } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result, option fn foo() -> Result>, ()> { @@ -2139,10 +2207,11 @@ fn foo() -> Option> { None } "#, + "Unwrap Result return type", ); - check_assist( - unwrap_result_return_type, + check_assist_by_label( + unwrap_return_type, r#" //- minicore: result, option, iterators fn foo() -> Result$0, ()> { @@ -2154,6 +2223,7 @@ fn foo() -> impl Iterator { Some(42).into_iter() } "#, + "Unwrap Result return type", ); } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs index e6e1857a3f76..2d918a5b1c19 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -2,6 +2,7 @@ use std::iter; use hir::HasSource; use ide_db::{ + assists::GroupLabel, famous_defs::FamousDefs, syntax_helpers::node_ext::{for_each_tail_expr, walk_expr}, }; @@ -25,9 +26,6 @@ use crate::{AssistContext, AssistId, AssistKind, Assists}; // ``` // fn foo() -> Option { Some(42i32) } // ``` -pub(crate) fn wrap_return_type_in_option(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - wrap_return_type(acc, ctx, WrapperKind::Option) -} // Assist: wrap_return_type_in_result // @@ -41,8 +39,97 @@ pub(crate) fn wrap_return_type_in_option(acc: &mut Assists, ctx: &AssistContext< // ``` // fn foo() -> Result { Ok(42i32) } // ``` -pub(crate) fn wrap_return_type_in_result(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - wrap_return_type(acc, ctx, WrapperKind::Result) + +pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + let ret_type = ctx.find_node_at_offset::()?; + let parent = ret_type.syntax().parent()?; + let body = match_ast! { + match parent { + ast::Fn(func) => func.body()?, + ast::ClosureExpr(closure) => match closure.body()? { + Expr::BlockExpr(block) => block, + // closures require a block when a return type is specified + _ => return None, + }, + _ => return None, + } + }; + + let type_ref = &ret_type.ty()?; + let ty = ctx.sema.resolve_type(type_ref)?.as_adt(); + let famous_defs = FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()); + + for kind in WrapperKind::ALL { + let Some(core_wrapper) = kind.core_type(&famous_defs) else { + continue; + }; + + if matches!(ty, Some(hir::Adt::Enum(ret_type)) if ret_type == core_wrapper) { + // The return type is already wrapped + cov_mark::hit!(wrap_return_type_simple_return_type_already_wrapped); + continue; + } + + acc.add_group( + &GroupLabel("Wrap return type in...".into()), + kind.assist_id(), + kind.label(), + type_ref.syntax().text_range(), + |edit| { + let alias = wrapper_alias(ctx, &core_wrapper, type_ref, kind.symbol()); + let new_return_ty = + alias.unwrap_or_else(|| kind.wrap_type(type_ref)).clone_for_update(); + + let body = edit.make_mut(ast::Expr::BlockExpr(body.clone())); + + let mut exprs_to_wrap = Vec::new(); + let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); + walk_expr(&body, &mut |expr| { + if let Expr::ReturnExpr(ret_expr) = expr { + if let Some(ret_expr_arg) = &ret_expr.expr() { + for_each_tail_expr(ret_expr_arg, tail_cb); + } + } + }); + for_each_tail_expr(&body, tail_cb); + + for ret_expr_arg in exprs_to_wrap { + let happy_wrapped = make::expr_call( + make::expr_path(make::ext::ident_path(kind.happy_ident())), + make::arg_list(iter::once(ret_expr_arg.clone())), + ) + .clone_for_update(); + ted::replace(ret_expr_arg.syntax(), happy_wrapped.syntax()); + } + + let old_return_ty = edit.make_mut(type_ref.clone()); + ted::replace(old_return_ty.syntax(), new_return_ty.syntax()); + + if let WrapperKind::Result = kind { + // Add a placeholder snippet at the first generic argument that doesn't equal the return type. + // This is normally the error type, but that may not be the case when we inserted a type alias. + let args = + new_return_ty.syntax().descendants().find_map(ast::GenericArgList::cast); + let error_type_arg = args.and_then(|list| { + list.generic_args().find(|arg| match arg { + ast::GenericArg::TypeArg(_) => { + arg.syntax().text() != type_ref.syntax().text() + } + ast::GenericArg::LifetimeArg(_) => false, + _ => true, + }) + }); + if let Some(error_type_arg) = error_type_arg { + if let Some(cap) = ctx.config.snippet_cap { + edit.add_placeholder_snippet(cap, error_type_arg); + } + } + } + }, + ); + } + + Some(()) } enum WrapperKind { @@ -51,6 +138,8 @@ enum WrapperKind { } impl WrapperKind { + const ALL: &'static [WrapperKind] = &[WrapperKind::Option, WrapperKind::Result]; + fn assist_id(&self) -> AssistId { let s = match self { WrapperKind::Option => "wrap_return_type_in_option", @@ -74,7 +163,7 @@ impl WrapperKind { } } - fn core_type(&self, famous_defs: FamousDefs<'_, '_>) -> Option { + fn core_type(&self, famous_defs: &FamousDefs<'_, '_>) -> Option { match self { WrapperKind::Option => famous_defs.core_option_Option(), WrapperKind::Result => famous_defs.core_result_Result(), @@ -96,81 +185,6 @@ impl WrapperKind { } } -fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>, kind: WrapperKind) -> Option<()> { - let ret_type = ctx.find_node_at_offset::()?; - let parent = ret_type.syntax().parent()?; - let body = match_ast! { - match parent { - ast::Fn(func) => func.body()?, - ast::ClosureExpr(closure) => match closure.body()? { - Expr::BlockExpr(block) => block, - // closures require a block when a return type is specified - _ => return None, - }, - _ => return None, - } - }; - - let type_ref = &ret_type.ty()?; - let core_wrapper = - kind.core_type(FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()))?; - - let ty = ctx.sema.resolve_type(type_ref)?.as_adt(); - if matches!(ty, Some(hir::Adt::Enum(ret_type)) if ret_type == core_wrapper) { - // The return type is already wrapped - cov_mark::hit!(wrap_return_type_simple_return_type_already_wrapped); - return None; - } - - acc.add(kind.assist_id(), kind.label(), type_ref.syntax().text_range(), |edit| { - let alias = wrapper_alias(ctx, &core_wrapper, type_ref, kind.symbol()); - let new_return_ty = alias.unwrap_or_else(|| kind.wrap_type(type_ref)).clone_for_update(); - - let body = edit.make_mut(ast::Expr::BlockExpr(body)); - - let mut exprs_to_wrap = Vec::new(); - let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); - walk_expr(&body, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } - } - }); - for_each_tail_expr(&body, tail_cb); - - for ret_expr_arg in exprs_to_wrap { - let happy_wrapped = make::expr_call( - make::expr_path(make::ext::ident_path(kind.happy_ident())), - make::arg_list(iter::once(ret_expr_arg.clone())), - ) - .clone_for_update(); - ted::replace(ret_expr_arg.syntax(), happy_wrapped.syntax()); - } - - let old_return_ty = edit.make_mut(type_ref.clone()); - ted::replace(old_return_ty.syntax(), new_return_ty.syntax()); - - if let WrapperKind::Result = kind { - // Add a placeholder snippet at the first generic argument that doesn't equal the return type. - // This is normally the error type, but that may not be the case when we inserted a type alias. - let args = new_return_ty.syntax().descendants().find_map(ast::GenericArgList::cast); - let error_type_arg = args.and_then(|list| { - list.generic_args().find(|arg| match arg { - ast::GenericArg::TypeArg(_) => arg.syntax().text() != type_ref.syntax().text(), - ast::GenericArg::LifetimeArg(_) => false, - _ => true, - }) - }); - if let Some(error_type_arg) = error_type_arg { - if let Some(cap) = ctx.config.snippet_cap { - edit.add_placeholder_snippet(cap, error_type_arg); - } - } - } - }) -} - // Try to find an wrapper type alias in the current scope (shadowing the default). fn wrapper_alias( ctx: &AssistContext<'_>, @@ -232,14 +246,14 @@ fn tail_cb_impl(acc: &mut Vec, e: &ast::Expr) { #[cfg(test)] mod tests { - use crate::tests::{check_assist, check_assist_not_applicable}; + use crate::tests::{check_assist_by_label, check_assist_not_applicable_by_label}; use super::*; #[test] fn wrap_return_type_in_option_simple() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i3$02 { @@ -253,13 +267,14 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_break_split_tail() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i3$02 { @@ -283,13 +298,14 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_closure() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() { @@ -307,13 +323,14 @@ fn foo() { }; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_return_type_bad_cursor() { - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32 { @@ -321,13 +338,14 @@ fn foo() -> i32 { return 42i32; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option fn foo() { @@ -337,24 +355,26 @@ fn foo() { }; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_closure_non_block() { - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option fn foo() { || -> i$032 3; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_return_type_already_option_std() { - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> core::option::Option { @@ -362,14 +382,15 @@ fn foo() -> core::option::Option { return 42i32; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_return_type_already_option() { cov_mark::check!(wrap_return_type_simple_return_type_already_wrapped); - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> Option { @@ -377,13 +398,14 @@ fn foo() -> Option { return 42i32; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_return_type_already_option_closure() { - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option fn foo() { @@ -393,13 +415,14 @@ fn foo() { }; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_cursor() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> $0i32 { @@ -413,13 +436,14 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() ->$0 i32 { @@ -433,13 +457,14 @@ fn foo() -> Option { Some(42i32) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_closure() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() { @@ -457,13 +482,14 @@ fn foo() { }; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_only() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { 42i32 } @@ -471,13 +497,14 @@ fn foo() -> i32$0 { 42i32 } r#" fn foo() -> Option { Some(42i32) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_block_like() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -497,13 +524,14 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_without_block_closure() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() { @@ -527,13 +555,14 @@ fn foo() { }; } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_nested_if() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -561,13 +590,14 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_await() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option async fn foo() -> i$032 { @@ -595,13 +625,14 @@ async fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_array() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> [i32;$0 3] { [1, 2, 3] } @@ -609,13 +640,14 @@ fn foo() -> [i32;$0 3] { [1, 2, 3] } r#" fn foo() -> Option<[i32; 3]> { Some([1, 2, 3]) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_cast() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -$0> i32 { @@ -643,13 +675,14 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_block_like_match() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -669,13 +702,14 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_loop_with_tail() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -697,13 +731,14 @@ fn foo() -> Option { Some(my_var) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_loop_in_let_stmt() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -721,13 +756,14 @@ fn foo() -> Option { Some(my_var) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_block_like_match_return_expr() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -749,10 +785,11 @@ fn foo() -> Option { Some(res) } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -776,13 +813,14 @@ fn foo() -> Option { Some(res) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_block_like_match_deeper() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -826,13 +864,14 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_tail_block_like_early_return() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i$032 { @@ -852,13 +891,14 @@ fn foo() -> Option { Some(53i32) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_in_option_tail_position() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(num: i32) -> $0i32 { @@ -870,13 +910,14 @@ fn foo(num: i32) -> Option { return Some(num) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_closure() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(the_field: u32) ->$0 u32 { @@ -906,10 +947,11 @@ fn foo(the_field: u32) -> Option { Some(the_field) } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> u32$0 { @@ -951,13 +993,14 @@ fn foo(the_field: u32) -> Option { Some(t.unwrap_or_else(|| the_field)) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_option_simple_with_weird_forms() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i32$0 { @@ -989,10 +1032,11 @@ fn foo() -> Option { } } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> u32$0 { @@ -1030,10 +1074,11 @@ fn foo(the_field: u32) -> Option { Some(the_field) } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> u3$02 { @@ -1059,10 +1104,11 @@ fn foo(the_field: u32) -> Option { Some(the_field) } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> u32$0 { @@ -1090,10 +1136,11 @@ fn foo(the_field: u32) -> Option { Some(the_field) } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo(the_field: u32) -> $0u32 { @@ -1121,13 +1168,14 @@ fn foo(the_field: u32) -> Option { Some(the_field) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_local_option_type() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option type Option = core::option::Option; @@ -1143,10 +1191,11 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option type Option2 = core::option::Option; @@ -1162,13 +1211,14 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_imported_local_option_type() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option mod some_module { @@ -1192,10 +1242,11 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option mod some_module { @@ -1219,13 +1270,14 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_local_option_type_from_function_body() { - check_assist( - wrap_return_type_in_option, + check_assist_by_label( + wrap_return_type, r#" //- minicore: option fn foo() -> i3$02 { @@ -1239,13 +1291,14 @@ fn foo() -> Option { Some(0) } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_local_option_type_already_using_alias() { - check_assist_not_applicable( - wrap_return_type_in_option, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: option pub type Option = core::option::Option; @@ -1254,13 +1307,14 @@ fn foo() -> Option { return Some(42i32); } "#, + WrapperKind::Option.label(), ); } #[test] fn wrap_return_type_in_result_simple() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i3$02 { @@ -1274,13 +1328,14 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_break_split_tail() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i3$02 { @@ -1304,13 +1359,14 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_closure() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() { @@ -1328,13 +1384,14 @@ fn foo() { }; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_return_type_bad_cursor() { - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32 { @@ -1342,13 +1399,14 @@ fn foo() -> i32 { return 42i32; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_return_type_bad_cursor_closure() { - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result fn foo() { @@ -1358,24 +1416,26 @@ fn foo() { }; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_closure_non_block() { - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result fn foo() { || -> i$032 3; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_return_type_already_result_std() { - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> core::result::Result { @@ -1383,14 +1443,15 @@ fn foo() -> core::result::Result { return 42i32; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_return_type_already_result() { cov_mark::check!(wrap_return_type_simple_return_type_already_wrapped); - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> Result { @@ -1398,13 +1459,14 @@ fn foo() -> Result { return 42i32; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_return_type_already_result_closure() { - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result fn foo() { @@ -1414,13 +1476,14 @@ fn foo() { }; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_cursor() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> $0i32 { @@ -1434,13 +1497,14 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() ->$0 i32 { @@ -1454,13 +1518,14 @@ fn foo() -> Result { Ok(42i32) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_closure() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() { @@ -1478,13 +1543,14 @@ fn foo() { }; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_only() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { 42i32 } @@ -1492,13 +1558,14 @@ fn foo() -> i32$0 { 42i32 } r#" fn foo() -> Result { Ok(42i32) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_block_like() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1518,13 +1585,14 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_without_block_closure() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() { @@ -1548,13 +1616,14 @@ fn foo() { }; } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_nested_if() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1582,13 +1651,14 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_await() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result async fn foo() -> i$032 { @@ -1616,13 +1686,14 @@ async fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_array() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> [i32;$0 3] { [1, 2, 3] } @@ -1630,13 +1701,14 @@ fn foo() -> [i32;$0 3] { [1, 2, 3] } r#" fn foo() -> Result<[i32; 3], ${0:_}> { Ok([1, 2, 3]) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_cast() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -$0> i32 { @@ -1664,13 +1736,14 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_block_like_match() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1690,13 +1763,14 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_loop_with_tail() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1718,13 +1792,14 @@ fn foo() -> Result { Ok(my_var) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_loop_in_let_stmt() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1742,13 +1817,14 @@ fn foo() -> Result { Ok(my_var) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_block_like_match_return_expr() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1770,10 +1846,11 @@ fn foo() -> Result { Ok(res) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1797,13 +1874,14 @@ fn foo() -> Result { Ok(res) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_block_like_match_deeper() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -1847,13 +1925,14 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_tail_block_like_early_return() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i$032 { @@ -1873,13 +1952,14 @@ fn foo() -> Result { Ok(53i32) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_in_result_tail_position() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(num: i32) -> $0i32 { @@ -1891,13 +1971,14 @@ fn foo(num: i32) -> Result { return Ok(num) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_closure() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(the_field: u32) ->$0 u32 { @@ -1927,10 +2008,11 @@ fn foo(the_field: u32) -> Result { Ok(the_field) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> u32$0 { @@ -1972,13 +2054,14 @@ fn foo(the_field: u32) -> Result { Ok(t.unwrap_or_else(|| the_field)) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_result_simple_with_weird_forms() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i32$0 { @@ -2010,10 +2093,11 @@ fn foo() -> Result { } } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> u32$0 { @@ -2051,10 +2135,11 @@ fn foo(the_field: u32) -> Result { Ok(the_field) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> u3$02 { @@ -2080,10 +2165,11 @@ fn foo(the_field: u32) -> Result { Ok(the_field) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> u32$0 { @@ -2111,10 +2197,11 @@ fn foo(the_field: u32) -> Result { Ok(the_field) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo(the_field: u32) -> $0u32 { @@ -2142,13 +2229,14 @@ fn foo(the_field: u32) -> Result { Ok(the_field) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_local_result_type() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result type Result = core::result::Result; @@ -2164,10 +2252,11 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result type Result2 = core::result::Result; @@ -2183,13 +2272,14 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_imported_local_result_type() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result mod some_module { @@ -2213,10 +2303,11 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result mod some_module { @@ -2240,13 +2331,14 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_local_result_type_from_function_body() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result fn foo() -> i3$02 { @@ -2260,13 +2352,14 @@ fn foo() -> Result { Ok(0) } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_local_result_type_already_using_alias() { - check_assist_not_applicable( - wrap_return_type_in_result, + check_assist_not_applicable_by_label( + wrap_return_type, r#" //- minicore: result pub type Result = core::result::Result; @@ -2275,13 +2368,14 @@ fn foo() -> Result { return Ok(42i32); } "#, + WrapperKind::Result.label(), ); } #[test] fn wrap_return_type_in_local_result_type_multiple_generics() { - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result type Result = core::result::Result; @@ -2297,10 +2391,11 @@ fn foo() -> Result { Ok(0) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result type Result = core::result::Result, ()>; @@ -2316,10 +2411,11 @@ fn foo() -> Result { Ok(0) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result type Result<'a, T, E> = core::result::Result, &'a ()>; @@ -2335,10 +2431,11 @@ fn foo() -> Result<'_, i32, ${0:_}> { Ok(0) } "#, + WrapperKind::Result.label(), ); - check_assist( - wrap_return_type_in_result, + check_assist_by_label( + wrap_return_type, r#" //- minicore: result type Result = core::result::Result, Bar>; @@ -2354,6 +2451,7 @@ fn foo() -> Result { Ok(0) } "#, + WrapperKind::Result.label(), ); } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs index 8114888d6c3f..22620816d504 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs @@ -355,12 +355,10 @@ mod handlers { unmerge_use::unmerge_use, unnecessary_async::unnecessary_async, unwrap_block::unwrap_block, - unwrap_return_type::unwrap_option_return_type, - unwrap_return_type::unwrap_result_return_type, + unwrap_return_type::unwrap_return_type, unwrap_tuple::unwrap_tuple, unqualify_method_call::unqualify_method_call, - wrap_return_type::wrap_return_type_in_option, - wrap_return_type::wrap_return_type_in_result, + wrap_return_type::wrap_return_type, wrap_unwrap_cfg_attr::wrap_unwrap_cfg_attr, // These are manually sorted for better priorities. By default, From 86abb5439ab71f7aa7cf6c48a84b5bfdd06ba009 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Sat, 19 Oct 2024 15:27:53 -0700 Subject: [PATCH 049/366] rustdoc: hash assets at rustdoc build time Since sha256 is slow enough to show up on small benchmarks, we can save time by embedding the hash in the executable. --- src/librustdoc/Cargo.toml | 5 ++- src/librustdoc/build.rs | 48 +++++++++++++++++++++++++++++ src/librustdoc/html/static_files.rs | 19 ++++-------- 3 files changed, 58 insertions(+), 14 deletions(-) create mode 100644 src/librustdoc/build.rs diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index 42df0b283817..57b6de67ee8a 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -2,6 +2,7 @@ name = "rustdoc" version = "0.0.0" edition = "2021" +build = "build.rs" [lib] path = "lib.rs" @@ -24,13 +25,15 @@ tracing = "0.1" tracing-tree = "0.3.0" threadpool = "1.8.1" unicode-segmentation = "1.9" -sha2 = "0.10.8" [dependencies.tracing-subscriber] version = "0.3.3" default-features = false features = ["fmt", "env-filter", "smallvec", "parking_lot", "ansi"] +[build-dependencies] +sha2 = "0.10.8" + [dev-dependencies] expect-test = "1.4.0" diff --git a/src/librustdoc/build.rs b/src/librustdoc/build.rs new file mode 100644 index 000000000000..69337fb1d250 --- /dev/null +++ b/src/librustdoc/build.rs @@ -0,0 +1,48 @@ +fn main() { + // generate sha256 files + // this avoids having to perform hashing at runtime + let files = &[ + "static/css/rustdoc.css", + "static/css/noscript.css", + "static/css/normalize.css", + "static/js/main.js", + "static/js/search.js", + "static/js/settings.js", + "static/js/src-script.js", + "static/js/storage.js", + "static/js/scrape-examples.js", + "static/COPYRIGHT.txt", + "static/LICENSE-APACHE.txt", + "static/LICENSE-MIT.txt", + "static/images/rust-logo.svg", + "static/images/favicon.svg", + "static/images/favicon-32x32.png", + "static/fonts/FiraSans-Regular.woff2", + "static/fonts/FiraSans-Medium.woff2", + "static/fonts/FiraSans-LICENSE.txt", + "static/fonts/SourceSerif4-Regular.ttf.woff2", + "static/fonts/SourceSerif4-Bold.ttf.woff2", + "static/fonts/SourceSerif4-It.ttf.woff2", + "static/fonts/SourceSerif4-LICENSE.md", + "static/fonts/SourceCodePro-Regular.ttf.woff2", + "static/fonts/SourceCodePro-Semibold.ttf.woff2", + "static/fonts/SourceCodePro-It.ttf.woff2", + "static/fonts/SourceCodePro-LICENSE.txt", + "static/fonts/NanumBarunGothic.ttf.woff2", + "static/fonts/NanumBarunGothic-LICENSE.txt", + ]; + let out_dir = std::env::var("OUT_DIR").expect("standard Cargo environment variable"); + for path in files { + let inpath = format!("html/{path}"); + println!("cargo::rerun-if-changed={inpath}"); + let bytes = std::fs::read(inpath).expect("static path exists"); + use sha2::Digest; + let bytes = sha2::Sha256::digest(bytes); + let mut digest = format!("-{bytes:x}"); + digest.truncate(9); + let outpath = std::path::PathBuf::from(format!("{out_dir}/{path}.sha256")); + std::fs::create_dir_all(outpath.parent().expect("all file paths are in a directory")) + .expect("should be able to write to out_dir"); + std::fs::write(&outpath, digest.as_bytes()).expect("write to out_dir"); + } +} diff --git a/src/librustdoc/html/static_files.rs b/src/librustdoc/html/static_files.rs index 9e0803f5d3fd..a4dc8cd1ed91 100644 --- a/src/librustdoc/html/static_files.rs +++ b/src/librustdoc/html/static_files.rs @@ -12,8 +12,8 @@ pub(crate) struct StaticFile { } impl StaticFile { - fn new(filename: &str, bytes: &'static [u8]) -> StaticFile { - Self { filename: static_filename(filename, bytes), bytes } + fn new(filename: &str, bytes: &'static [u8], sha256: &'static str) -> StaticFile { + Self { filename: static_filename(filename, sha256), bytes } } pub(crate) fn minified(&self) -> Vec { @@ -55,17 +55,9 @@ pub(crate) fn suffix_path(filename: &str, suffix: &str) -> PathBuf { filename.into() } -pub(crate) fn static_filename(filename: &str, contents: &[u8]) -> PathBuf { +pub(crate) fn static_filename(filename: &str, sha256: &str) -> PathBuf { let filename = filename.rsplit('/').next().unwrap(); - suffix_path(filename, &static_suffix(contents)) -} - -fn static_suffix(bytes: &[u8]) -> String { - use sha2::Digest; - let bytes = sha2::Sha256::digest(bytes); - let mut digest = format!("-{bytes:x}"); - digest.truncate(9); - digest + suffix_path(filename, &sha256) } macro_rules! static_files { @@ -74,8 +66,9 @@ macro_rules! static_files { $(pub $field: StaticFile,)+ } + // sha256 files are generated in build.rs pub(crate) static STATIC_FILES: std::sync::LazyLock = std::sync::LazyLock::new(|| StaticFiles { - $($field: StaticFile::new($file_path, include_bytes!($file_path)),)+ + $($field: StaticFile::new($file_path, include_bytes!($file_path), include_str!(concat!(env!("OUT_DIR"), "/", $file_path, ".sha256"))),)+ }); pub(crate) fn for_each(f: impl Fn(&StaticFile) -> Result<(), E>) -> Result<(), E> { From 98c4d9695718b309fe790f7b2da2e886ccd042c6 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 19 Oct 2024 21:47:42 +1100 Subject: [PATCH 050/366] Reduce visibility of coverage FFI functions/types --- .../src/coverageinfo/ffi.rs | 20 +++++++++---------- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 16 +++++++-------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs index 90f7dd733ca1..2a35b4adbcda 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs @@ -5,7 +5,7 @@ use rustc_middle::mir::coverage::{ /// Must match the layout of `LLVMRustCounterKind`. #[derive(Copy, Clone, Debug)] #[repr(C)] -pub enum CounterKind { +pub(crate) enum CounterKind { Zero = 0, CounterValueReference = 1, Expression = 2, @@ -25,9 +25,9 @@ pub enum CounterKind { /// Must match the layout of `LLVMRustCounter`. #[derive(Copy, Clone, Debug)] #[repr(C)] -pub struct Counter { +pub(crate) struct Counter { // Important: The layout (order and types of fields) must match its C++ counterpart. - pub kind: CounterKind, + pub(crate) kind: CounterKind, id: u32, } @@ -36,7 +36,7 @@ impl Counter { pub(crate) const ZERO: Self = Self { kind: CounterKind::Zero, id: 0 }; /// Constructs a new `Counter` of kind `CounterValueReference`. - pub fn counter_value_reference(counter_id: CounterId) -> Self { + pub(crate) fn counter_value_reference(counter_id: CounterId) -> Self { Self { kind: CounterKind::CounterValueReference, id: counter_id.as_u32() } } @@ -59,7 +59,7 @@ impl Counter { /// Must match the layout of `LLVMRustCounterExprKind`. #[derive(Copy, Clone, Debug)] #[repr(C)] -pub enum ExprKind { +pub(crate) enum ExprKind { Subtract = 0, Add = 1, } @@ -69,10 +69,10 @@ pub enum ExprKind { /// Must match the layout of `LLVMRustCounterExpression`. #[derive(Copy, Clone, Debug)] #[repr(C)] -pub struct CounterExpression { - pub kind: ExprKind, - pub lhs: Counter, - pub rhs: Counter, +pub(crate) struct CounterExpression { + pub(crate) kind: ExprKind, + pub(crate) lhs: Counter, + pub(crate) rhs: Counter, } /// Corresponds to enum `llvm::coverage::CounterMappingRegion::RegionKind`. @@ -199,7 +199,7 @@ mod mcdc { /// Must match the layout of `LLVMRustCounterMappingRegion`. #[derive(Copy, Clone, Debug)] #[repr(C)] -pub struct CounterMappingRegion { +pub(crate) struct CounterMappingRegion { /// The counter type and type-dependent counter data, if any. counter: Counter, diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 661debbb9f12..c41961fb3946 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1740,7 +1740,7 @@ unsafe extern "C" { ) -> bool; #[allow(improper_ctypes)] - pub fn LLVMRustCoverageWriteFilenamesSectionToBuffer( + pub(crate) fn LLVMRustCoverageWriteFilenamesSectionToBuffer( Filenames: *const *const c_char, FilenamesLen: size_t, Lengths: *const size_t, @@ -1749,7 +1749,7 @@ unsafe extern "C" { ); #[allow(improper_ctypes)] - pub fn LLVMRustCoverageWriteMappingToBuffer( + pub(crate) fn LLVMRustCoverageWriteMappingToBuffer( VirtualFileMappingIDs: *const c_uint, NumVirtualFileMappingIDs: c_uint, Expressions: *const crate::coverageinfo::ffi::CounterExpression, @@ -1759,23 +1759,23 @@ unsafe extern "C" { BufferOut: &RustString, ); - pub fn LLVMRustCoverageCreatePGOFuncNameVar( + pub(crate) fn LLVMRustCoverageCreatePGOFuncNameVar( F: &Value, FuncName: *const c_char, FuncNameLen: size_t, ) -> &Value; - pub fn LLVMRustCoverageHashByteArray(Bytes: *const c_char, NumBytes: size_t) -> u64; + pub(crate) fn LLVMRustCoverageHashByteArray(Bytes: *const c_char, NumBytes: size_t) -> u64; #[allow(improper_ctypes)] - pub fn LLVMRustCoverageWriteMapSectionNameToString(M: &Module, Str: &RustString); + pub(crate) fn LLVMRustCoverageWriteMapSectionNameToString(M: &Module, Str: &RustString); #[allow(improper_ctypes)] - pub fn LLVMRustCoverageWriteFuncSectionNameToString(M: &Module, Str: &RustString); + pub(crate) fn LLVMRustCoverageWriteFuncSectionNameToString(M: &Module, Str: &RustString); #[allow(improper_ctypes)] - pub fn LLVMRustCoverageWriteMappingVarNameToString(Str: &RustString); + pub(crate) fn LLVMRustCoverageWriteMappingVarNameToString(Str: &RustString); - pub fn LLVMRustCoverageMappingVersion() -> u32; + pub(crate) fn LLVMRustCoverageMappingVersion() -> u32; pub fn LLVMRustDebugMetadataVersion() -> u32; pub fn LLVMRustVersionMajor() -> u32; pub fn LLVMRustVersionMinor() -> u32; From d1bf77eb3404bf1e46f4c81eebf6cc83508b0de7 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 19 Oct 2024 22:22:43 +1100 Subject: [PATCH 051/366] Pass coverage mappings to LLVM as separate structs --- .../src/coverageinfo/ffi.rs | 380 +++--------------- .../src/coverageinfo/mapgen.rs | 48 ++- .../src/coverageinfo/mod.rs | 18 +- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 10 +- .../llvm-wrapper/CoverageMappingWrapper.cpp | 182 ++++----- 5 files changed, 207 insertions(+), 431 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs index 2a35b4adbcda..feac97f3e2b6 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs @@ -1,6 +1,4 @@ -use rustc_middle::mir::coverage::{ - ConditionInfo, CounterId, CovTerm, DecisionInfo, ExpressionId, MappingKind, SourceRegion, -}; +use rustc_middle::mir::coverage::{CounterId, CovTerm, ExpressionId, SourceRegion}; /// Must match the layout of `LLVMRustCounterKind`. #[derive(Copy, Clone, Debug)] @@ -75,42 +73,7 @@ pub(crate) struct CounterExpression { pub(crate) rhs: Counter, } -/// Corresponds to enum `llvm::coverage::CounterMappingRegion::RegionKind`. -/// -/// Must match the layout of `LLVMRustCounterMappingRegionKind`. -#[derive(Copy, Clone, Debug)] -#[repr(C)] -enum RegionKind { - /// A CodeRegion associates some code with a counter - CodeRegion = 0, - - /// An ExpansionRegion represents a file expansion region that associates - /// a source range with the expansion of a virtual source file, such as - /// for a macro instantiation or #include file. - ExpansionRegion = 1, - - /// A SkippedRegion represents a source range with code that was skipped - /// by a preprocessor or similar means. - SkippedRegion = 2, - - /// A GapRegion is like a CodeRegion, but its count is only set as the - /// line execution count when its the only region in the line. - GapRegion = 3, - - /// A BranchRegion represents leaf-level boolean expressions and is - /// associated with two counters, each representing the number of times the - /// expression evaluates to true or false. - BranchRegion = 4, - - /// A DecisionRegion represents a top-level boolean expression and is - /// associated with a variable length bitmap index and condition number. - MCDCDecisionRegion = 5, - - /// A Branch Region can be extended to include IDs to facilitate MC/DC. - MCDCBranchRegion = 6, -} - -mod mcdc { +pub(crate) mod mcdc { use rustc_middle::mir::coverage::{ConditionId, ConditionInfo, DecisionInfo}; /// Must match the layout of `LLVMRustMCDCDecisionParameters`. @@ -121,8 +84,6 @@ mod mcdc { num_conditions: u16, } - // ConditionId in llvm is `unsigned int` at 18 while `int16_t` at - // [19](https://github.com/llvm/llvm-project/pull/81257). type LLVMConditionId = i16; /// Must match the layout of `LLVMRustMCDCBranchParameters`. @@ -133,38 +94,6 @@ mod mcdc { condition_ids: [LLVMConditionId; 2], } - #[repr(C)] - #[derive(Clone, Copy, Debug)] - enum ParameterTag { - None = 0, - Decision = 1, - Branch = 2, - } - /// Same layout with `LLVMRustMCDCParameters` - #[repr(C)] - #[derive(Clone, Copy, Debug)] - pub(crate) struct Parameters { - tag: ParameterTag, - decision_params: DecisionParameters, - branch_params: BranchParameters, - } - - impl Parameters { - pub(crate) fn none() -> Self { - Self { - tag: ParameterTag::None, - decision_params: Default::default(), - branch_params: Default::default(), - } - } - pub(crate) fn decision(decision_params: DecisionParameters) -> Self { - Self { tag: ParameterTag::Decision, decision_params, branch_params: Default::default() } - } - pub(crate) fn branch(branch_params: BranchParameters) -> Self { - Self { tag: ParameterTag::Branch, decision_params: Default::default(), branch_params } - } - } - impl From for BranchParameters { fn from(value: ConditionInfo) -> Self { let to_llvm_cond_id = |cond_id: Option| { @@ -186,267 +115,68 @@ mod mcdc { } } -/// This struct provides LLVM's representation of a "CoverageMappingRegion", encoded into the -/// coverage map, in accordance with the -/// [LLVM Code Coverage Mapping Format](https://github.com/rust-lang/llvm-project/blob/rustc/13.0-2021-09-30/llvm/docs/CoverageMappingFormat.rst#llvm-code-coverage-mapping-format). -/// The struct composes fields representing the `Counter` type and value(s) (injected counter -/// ID, or expression type and operands), the source file (an indirect index into a "filenames -/// array", encoded separately), and source location (start and end positions of the represented -/// code region). +/// A span of source code coordinates to be embedded in coverage metadata. /// -/// Corresponds to struct `llvm::coverage::CounterMappingRegion`. -/// -/// Must match the layout of `LLVMRustCounterMappingRegion`. -#[derive(Copy, Clone, Debug)] +/// Must match the layout of `LLVMRustCoverageSpan`. +#[derive(Clone, Debug)] #[repr(C)] -pub(crate) struct CounterMappingRegion { - /// The counter type and type-dependent counter data, if any. - counter: Counter, - - /// If the `RegionKind` is a `BranchRegion`, this represents the counter - /// for the false branch of the region. - false_counter: Counter, - - mcdc_params: mcdc::Parameters, - /// An indirect reference to the source filename. In the LLVM Coverage Mapping Format, the - /// file_id is an index into a function-specific `virtual_file_mapping` array of indexes - /// that, in turn, are used to look up the filename for this region. +pub(crate) struct CoverageSpan { + /// Local index into the function's local-to-global file ID table. + /// The value at that index is itself an index into the coverage filename + /// table in the CGU's `__llvm_covmap` section. file_id: u32, - /// If the `RegionKind` is an `ExpansionRegion`, the `expanded_file_id` can be used to find - /// the mapping regions created as a result of macro expansion, by checking if their file id - /// matches the expanded file id. - expanded_file_id: u32, - - /// 1-based starting line of the mapping region. + /// 1-based starting line of the source code span. start_line: u32, - - /// 1-based starting column of the mapping region. + /// 1-based starting column of the source code span. start_col: u32, - - /// 1-based ending line of the mapping region. + /// 1-based ending line of the source code span. end_line: u32, - - /// 1-based ending column of the mapping region. If the high bit is set, the current - /// mapping region is a gap area. + /// 1-based ending column of the source code span. High bit must be unset. end_col: u32, - - kind: RegionKind, } -impl CounterMappingRegion { - pub(crate) fn from_mapping( - mapping_kind: &MappingKind, - local_file_id: u32, - source_region: &SourceRegion, - ) -> Self { - let &SourceRegion { file_name: _, start_line, start_col, end_line, end_col } = - source_region; - match *mapping_kind { - MappingKind::Code(term) => Self::code_region( - Counter::from_term(term), - local_file_id, - start_line, - start_col, - end_line, - end_col, - ), - MappingKind::Branch { true_term, false_term } => Self::branch_region( - Counter::from_term(true_term), - Counter::from_term(false_term), - local_file_id, - start_line, - start_col, - end_line, - end_col, - ), - MappingKind::MCDCBranch { true_term, false_term, mcdc_params } => { - Self::mcdc_branch_region( - Counter::from_term(true_term), - Counter::from_term(false_term), - mcdc_params, - local_file_id, - start_line, - start_col, - end_line, - end_col, - ) - } - MappingKind::MCDCDecision(decision_info) => Self::decision_region( - decision_info, - local_file_id, - start_line, - start_col, - end_line, - end_col, - ), - } - } - - pub(crate) fn code_region( - counter: Counter, - file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - Self { - counter, - false_counter: Counter::ZERO, - mcdc_params: mcdc::Parameters::none(), - file_id, - expanded_file_id: 0, - start_line, - start_col, - end_line, - end_col, - kind: RegionKind::CodeRegion, - } - } - - pub(crate) fn branch_region( - counter: Counter, - false_counter: Counter, - file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - Self { - counter, - false_counter, - mcdc_params: mcdc::Parameters::none(), - file_id, - expanded_file_id: 0, - start_line, - start_col, - end_line, - end_col, - kind: RegionKind::BranchRegion, - } - } - - pub(crate) fn mcdc_branch_region( - counter: Counter, - false_counter: Counter, - condition_info: ConditionInfo, - file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - Self { - counter, - false_counter, - mcdc_params: mcdc::Parameters::branch(condition_info.into()), - file_id, - expanded_file_id: 0, - start_line, - start_col, - end_line, - end_col, - kind: RegionKind::MCDCBranchRegion, - } - } - - pub(crate) fn decision_region( - decision_info: DecisionInfo, - file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - let mcdc_params = mcdc::Parameters::decision(decision_info.into()); - - Self { - counter: Counter::ZERO, - false_counter: Counter::ZERO, - mcdc_params, - file_id, - expanded_file_id: 0, - start_line, - start_col, - end_line, - end_col, - kind: RegionKind::MCDCDecisionRegion, - } - } - - // This function might be used in the future; the LLVM API is still evolving, as is coverage - // support. - #[allow(dead_code)] - pub(crate) fn expansion_region( - file_id: u32, - expanded_file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - Self { - counter: Counter::ZERO, - false_counter: Counter::ZERO, - mcdc_params: mcdc::Parameters::none(), - file_id, - expanded_file_id, - start_line, - start_col, - end_line, - end_col, - kind: RegionKind::ExpansionRegion, - } - } - - // This function might be used in the future; the LLVM API is still evolving, as is coverage - // support. - #[allow(dead_code)] - pub(crate) fn skipped_region( - file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - Self { - counter: Counter::ZERO, - false_counter: Counter::ZERO, - mcdc_params: mcdc::Parameters::none(), - file_id, - expanded_file_id: 0, - start_line, - start_col, - end_line, - end_col, - kind: RegionKind::SkippedRegion, - } - } - - // This function might be used in the future; the LLVM API is still evolving, as is coverage - // support. - #[allow(dead_code)] - pub(crate) fn gap_region( - counter: Counter, - file_id: u32, - start_line: u32, - start_col: u32, - end_line: u32, - end_col: u32, - ) -> Self { - Self { - counter, - false_counter: Counter::ZERO, - mcdc_params: mcdc::Parameters::none(), - file_id, - expanded_file_id: 0, - start_line, - start_col, - end_line, - end_col: (1_u32 << 31) | end_col, - kind: RegionKind::GapRegion, - } +impl CoverageSpan { + pub(crate) fn from_source_region(file_id: u32, code_region: &SourceRegion) -> Self { + let &SourceRegion { file_name: _, start_line, start_col, end_line, end_col } = code_region; + // Internally, LLVM uses the high bit of `end_col` to distinguish between + // code regions and gap regions, so it can't be used by the column number. + assert!(end_col & (1u32 << 31) == 0, "high bit of `end_col` must be unset: {end_col:#X}"); + Self { file_id, start_line, start_col, end_line, end_col } } } + +/// Must match the layout of `LLVMRustCoverageCodeRegion`. +#[derive(Clone, Debug)] +#[repr(C)] +pub(crate) struct CodeRegion { + pub(crate) span: CoverageSpan, + pub(crate) counter: Counter, +} + +/// Must match the layout of `LLVMRustCoverageBranchRegion`. +#[derive(Clone, Debug)] +#[repr(C)] +pub(crate) struct BranchRegion { + pub(crate) span: CoverageSpan, + pub(crate) true_counter: Counter, + pub(crate) false_counter: Counter, +} + +/// Must match the layout of `LLVMRustCoverageMCDCBranchRegion`. +#[derive(Clone, Debug)] +#[repr(C)] +pub(crate) struct MCDCBranchRegion { + pub(crate) span: CoverageSpan, + pub(crate) true_counter: Counter, + pub(crate) false_counter: Counter, + pub(crate) mcdc_branch_params: mcdc::BranchParameters, +} + +/// Must match the layout of `LLVMRustCoverageMCDCDecisionRegion`. +#[derive(Clone, Debug)] +#[repr(C)] +pub(crate) struct MCDCDecisionRegion { + pub(crate) span: CoverageSpan, + pub(crate) mcdc_decision_params: mcdc::DecisionParameters, +} diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index c2c261da79b6..cc366ba4b2c2 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -3,6 +3,7 @@ use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_index::IndexVec; +use rustc_middle::mir::coverage::MappingKind; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, mir}; use rustc_span::Symbol; @@ -10,7 +11,7 @@ use rustc_span::def_id::DefIdSet; use tracing::debug; use crate::common::CodegenCx; -use crate::coverageinfo::ffi::CounterMappingRegion; +use crate::coverageinfo::ffi; use crate::coverageinfo::map_data::{FunctionCoverage, FunctionCoverageCollector}; use crate::{coverageinfo, llvm}; @@ -235,7 +236,10 @@ fn encode_mappings_for_function( let expressions = function_coverage.counter_expressions().collect::>(); let mut virtual_file_mapping = VirtualFileMapping::default(); - let mut mapping_regions = Vec::with_capacity(counter_regions.len()); + let mut code_regions = vec![]; + let mut branch_regions = vec![]; + let mut mcdc_branch_regions = vec![]; + let mut mcdc_decision_regions = vec![]; // Group mappings into runs with the same filename, preserving the order // yielded by `FunctionCoverage`. @@ -255,11 +259,36 @@ fn encode_mappings_for_function( // form suitable for FFI. for (mapping_kind, region) in counter_regions_for_file { debug!("Adding counter {mapping_kind:?} to map for {region:?}"); - mapping_regions.push(CounterMappingRegion::from_mapping( - &mapping_kind, - local_file_id.as_u32(), - region, - )); + let span = ffi::CoverageSpan::from_source_region(local_file_id.as_u32(), region); + match mapping_kind { + MappingKind::Code(term) => { + code_regions + .push(ffi::CodeRegion { span, counter: ffi::Counter::from_term(term) }); + } + MappingKind::Branch { true_term, false_term } => { + branch_regions.push(ffi::BranchRegion { + span, + true_counter: ffi::Counter::from_term(true_term), + false_counter: ffi::Counter::from_term(false_term), + }); + } + MappingKind::MCDCBranch { true_term, false_term, mcdc_params } => { + mcdc_branch_regions.push(ffi::MCDCBranchRegion { + span, + true_counter: ffi::Counter::from_term(true_term), + false_counter: ffi::Counter::from_term(false_term), + mcdc_branch_params: ffi::mcdc::BranchParameters::from(mcdc_params), + }); + } + MappingKind::MCDCDecision(mcdc_decision_params) => { + mcdc_decision_regions.push(ffi::MCDCDecisionRegion { + span, + mcdc_decision_params: ffi::mcdc::DecisionParameters::from( + mcdc_decision_params, + ), + }); + } + } } } @@ -268,7 +297,10 @@ fn encode_mappings_for_function( coverageinfo::write_mapping_to_buffer( virtual_file_mapping.into_vec(), expressions, - mapping_regions, + &code_regions, + &branch_regions, + &mcdc_branch_regions, + &mcdc_decision_regions, buffer, ); }) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index d7d29eebf859..7f08659e5a22 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -16,7 +16,6 @@ use tracing::{debug, instrument}; use crate::builder::Builder; use crate::common::CodegenCx; -use crate::coverageinfo::ffi::{CounterExpression, CounterMappingRegion}; use crate::coverageinfo::map_data::FunctionCoverageCollector; use crate::llvm; @@ -255,8 +254,11 @@ pub(crate) fn write_filenames_section_to_buffer<'a>( pub(crate) fn write_mapping_to_buffer( virtual_file_mapping: Vec, - expressions: Vec, - mapping_regions: Vec, + expressions: Vec, + code_regions: &[ffi::CodeRegion], + branch_regions: &[ffi::BranchRegion], + mcdc_branch_regions: &[ffi::MCDCBranchRegion], + mcdc_decision_regions: &[ffi::MCDCDecisionRegion], buffer: &RustString, ) { unsafe { @@ -265,8 +267,14 @@ pub(crate) fn write_mapping_to_buffer( virtual_file_mapping.len() as c_uint, expressions.as_ptr(), expressions.len() as c_uint, - mapping_regions.as_ptr(), - mapping_regions.len() as c_uint, + code_regions.as_ptr(), + code_regions.len() as c_uint, + branch_regions.as_ptr(), + branch_regions.len() as c_uint, + mcdc_branch_regions.as_ptr(), + mcdc_branch_regions.len() as c_uint, + mcdc_decision_regions.as_ptr(), + mcdc_decision_regions.len() as c_uint, buffer, ); } diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index c41961fb3946..73e977da2e3a 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1754,8 +1754,14 @@ unsafe extern "C" { NumVirtualFileMappingIDs: c_uint, Expressions: *const crate::coverageinfo::ffi::CounterExpression, NumExpressions: c_uint, - MappingRegions: *const crate::coverageinfo::ffi::CounterMappingRegion, - NumMappingRegions: c_uint, + CodeRegions: *const crate::coverageinfo::ffi::CodeRegion, + NumCodeRegions: c_uint, + BranchRegions: *const crate::coverageinfo::ffi::BranchRegion, + NumBranchRegions: c_uint, + MCDCBranchRegions: *const crate::coverageinfo::ffi::MCDCBranchRegion, + NumMCDCBranchRegions: c_uint, + MCDCDecisionRegions: *const crate::coverageinfo::ffi::MCDCDecisionRegion, + NumMCDCDecisionRegions: c_uint, BufferOut: &RustString, ); diff --git a/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp index cda81d4a9b5b..b32af5e5e75c 100644 --- a/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp @@ -33,45 +33,6 @@ static coverage::Counter fromRust(LLVMRustCounter Counter) { report_fatal_error("Bad LLVMRustCounterKind!"); } -// FFI equivalent of enum `llvm::coverage::CounterMappingRegion::RegionKind` -// https://github.com/rust-lang/llvm-project/blob/ea6fa9c2/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h#L213-L234 -enum class LLVMRustCounterMappingRegionKind { - CodeRegion = 0, - ExpansionRegion = 1, - SkippedRegion = 2, - GapRegion = 3, - BranchRegion = 4, - MCDCDecisionRegion = 5, - MCDCBranchRegion = 6 -}; - -static coverage::CounterMappingRegion::RegionKind -fromRust(LLVMRustCounterMappingRegionKind Kind) { - switch (Kind) { - case LLVMRustCounterMappingRegionKind::CodeRegion: - return coverage::CounterMappingRegion::CodeRegion; - case LLVMRustCounterMappingRegionKind::ExpansionRegion: - return coverage::CounterMappingRegion::ExpansionRegion; - case LLVMRustCounterMappingRegionKind::SkippedRegion: - return coverage::CounterMappingRegion::SkippedRegion; - case LLVMRustCounterMappingRegionKind::GapRegion: - return coverage::CounterMappingRegion::GapRegion; - case LLVMRustCounterMappingRegionKind::BranchRegion: - return coverage::CounterMappingRegion::BranchRegion; - case LLVMRustCounterMappingRegionKind::MCDCDecisionRegion: - return coverage::CounterMappingRegion::MCDCDecisionRegion; - case LLVMRustCounterMappingRegionKind::MCDCBranchRegion: - return coverage::CounterMappingRegion::MCDCBranchRegion; - } - report_fatal_error("Bad LLVMRustCounterMappingRegionKind!"); -} - -enum LLVMRustMCDCParametersTag { - None = 0, - Decision = 1, - Branch = 2, -}; - struct LLVMRustMCDCDecisionParameters { uint32_t BitmapIdx; uint16_t NumConditions; @@ -82,47 +43,58 @@ struct LLVMRustMCDCBranchParameters { int16_t ConditionIDs[2]; }; -struct LLVMRustMCDCParameters { - LLVMRustMCDCParametersTag Tag; - LLVMRustMCDCDecisionParameters DecisionParameters; - LLVMRustMCDCBranchParameters BranchParameters; -}; - #if LLVM_VERSION_GE(19, 0) -static coverage::mcdc::Parameters fromRust(LLVMRustMCDCParameters Params) { - switch (Params.Tag) { - case LLVMRustMCDCParametersTag::None: - return std::monostate(); - case LLVMRustMCDCParametersTag::Decision: - return coverage::mcdc::DecisionParameters( - Params.DecisionParameters.BitmapIdx, - Params.DecisionParameters.NumConditions); - case LLVMRustMCDCParametersTag::Branch: - return coverage::mcdc::BranchParameters( - static_cast( - Params.BranchParameters.ConditionID), - {static_cast( - Params.BranchParameters.ConditionIDs[0]), - static_cast( - Params.BranchParameters.ConditionIDs[1])}); - } - report_fatal_error("Bad LLVMRustMCDCParametersTag!"); +static coverage::mcdc::BranchParameters +fromRust(LLVMRustMCDCBranchParameters Params) { + return coverage::mcdc::BranchParameters( + Params.ConditionID, {Params.ConditionIDs[0], Params.ConditionIDs[1]}); +} + +static coverage::mcdc::DecisionParameters +fromRust(LLVMRustMCDCDecisionParameters Params) { + return coverage::mcdc::DecisionParameters(Params.BitmapIdx, + Params.NumConditions); } #endif -// FFI equivalent of struct `llvm::coverage::CounterMappingRegion` -// https://github.com/rust-lang/llvm-project/blob/ea6fa9c2/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h#L211-L304 -struct LLVMRustCounterMappingRegion { - LLVMRustCounter Count; - LLVMRustCounter FalseCount; - LLVMRustMCDCParameters MCDCParameters; +// Must match the layout of +// `rustc_codegen_llvm::coverageinfo::ffi::CoverageSpan`. +struct LLVMRustCoverageSpan { uint32_t FileID; - uint32_t ExpandedFileID; uint32_t LineStart; uint32_t ColumnStart; uint32_t LineEnd; uint32_t ColumnEnd; - LLVMRustCounterMappingRegionKind Kind; +}; + +// Must match the layout of `rustc_codegen_llvm::coverageinfo::ffi::CodeRegion`. +struct LLVMRustCoverageCodeRegion { + LLVMRustCoverageSpan Span; + LLVMRustCounter Count; +}; + +// Must match the layout of +// `rustc_codegen_llvm::coverageinfo::ffi::BranchRegion`. +struct LLVMRustCoverageBranchRegion { + LLVMRustCoverageSpan Span; + LLVMRustCounter TrueCount; + LLVMRustCounter FalseCount; +}; + +// Must match the layout of +// `rustc_codegen_llvm::coverageinfo::ffi::MCDCBranchRegion`. +struct LLVMRustCoverageMCDCBranchRegion { + LLVMRustCoverageSpan Span; + LLVMRustCounter TrueCount; + LLVMRustCounter FalseCount; + LLVMRustMCDCBranchParameters MCDCBranchParams; +}; + +// Must match the layout of +// `rustc_codegen_llvm::coverageinfo::ffi::MCDCDecisionRegion`. +struct LLVMRustCoverageMCDCDecisionRegion { + LLVMRustCoverageSpan Span; + LLVMRustMCDCDecisionParameters MCDCDecisionParams; }; // FFI equivalent of enum `llvm::coverage::CounterExpression::ExprKind` @@ -174,28 +146,16 @@ extern "C" void LLVMRustCoverageWriteFilenamesSectionToBuffer( extern "C" void LLVMRustCoverageWriteMappingToBuffer( const unsigned *VirtualFileMappingIDs, unsigned NumVirtualFileMappingIDs, const LLVMRustCounterExpression *RustExpressions, unsigned NumExpressions, - const LLVMRustCounterMappingRegion *RustMappingRegions, - unsigned NumMappingRegions, RustStringRef BufferOut) { + const LLVMRustCoverageCodeRegion *CodeRegions, unsigned NumCodeRegions, + const LLVMRustCoverageBranchRegion *BranchRegions, + unsigned NumBranchRegions, + const LLVMRustCoverageMCDCBranchRegion *MCDCBranchRegions, + unsigned NumMCDCBranchRegions, + const LLVMRustCoverageMCDCDecisionRegion *MCDCDecisionRegions, + unsigned NumMCDCDecisionRegions, RustStringRef BufferOut) { // Convert from FFI representation to LLVM representation. - SmallVector MappingRegions; - MappingRegions.reserve(NumMappingRegions); - for (const auto &Region : ArrayRef( - RustMappingRegions, NumMappingRegions)) { - MappingRegions.emplace_back( - fromRust(Region.Count), fromRust(Region.FalseCount), -#if LLVM_VERSION_LT(19, 0) - coverage::CounterMappingRegion::MCDCParameters{}, -#endif - Region.FileID, Region.ExpandedFileID, // File IDs, then region info. - Region.LineStart, Region.ColumnStart, Region.LineEnd, Region.ColumnEnd, - fromRust(Region.Kind) -#if LLVM_VERSION_GE(19, 0) - , - fromRust(Region.MCDCParameters) -#endif - ); - } + // Expressions: std::vector Expressions; Expressions.reserve(NumExpressions); for (const auto &Expression : @@ -205,6 +165,46 @@ extern "C" void LLVMRustCoverageWriteMappingToBuffer( fromRust(Expression.RHS)); } + std::vector MappingRegions; + MappingRegions.reserve(NumCodeRegions + NumBranchRegions + + NumMCDCBranchRegions + NumMCDCDecisionRegions); + + // Code regions: + for (const auto &Region : ArrayRef(CodeRegions, NumCodeRegions)) { + MappingRegions.push_back(coverage::CounterMappingRegion::makeRegion( + fromRust(Region.Count), Region.Span.FileID, Region.Span.LineStart, + Region.Span.ColumnStart, Region.Span.LineEnd, Region.Span.ColumnEnd)); + } + + // Branch regions: + for (const auto &Region : ArrayRef(BranchRegions, NumBranchRegions)) { + MappingRegions.push_back(coverage::CounterMappingRegion::makeBranchRegion( + fromRust(Region.TrueCount), fromRust(Region.FalseCount), + Region.Span.FileID, Region.Span.LineStart, Region.Span.ColumnStart, + Region.Span.LineEnd, Region.Span.ColumnEnd)); + } + +#if LLVM_VERSION_GE(19, 0) + // MC/DC branch regions: + for (const auto &Region : ArrayRef(MCDCBranchRegions, NumMCDCBranchRegions)) { + MappingRegions.push_back(coverage::CounterMappingRegion::makeBranchRegion( + fromRust(Region.TrueCount), fromRust(Region.FalseCount), + Region.Span.FileID, Region.Span.LineStart, Region.Span.ColumnStart, + Region.Span.LineEnd, Region.Span.ColumnEnd, + fromRust(Region.MCDCBranchParams))); + } + + // MC/DC decision regions: + for (const auto &Region : + ArrayRef(MCDCDecisionRegions, NumMCDCDecisionRegions)) { + MappingRegions.push_back(coverage::CounterMappingRegion::makeDecisionRegion( + fromRust(Region.MCDCDecisionParams), Region.Span.FileID, + Region.Span.LineStart, Region.Span.ColumnStart, Region.Span.LineEnd, + Region.Span.ColumnEnd)); + } +#endif + + // Write the converted expressions and mappings to a byte buffer. auto CoverageMappingWriter = coverage::CoverageMappingWriter( ArrayRef(VirtualFileMappingIDs, NumVirtualFileMappingIDs), Expressions, MappingRegions); From ccfc8e20633ed94ef2be849e68a4752e99dac483 Mon Sep 17 00:00:00 2001 From: roife Date: Sun, 20 Oct 2024 16:45:38 +0800 Subject: [PATCH 052/366] feat: initial support for safe_kw in extern blocks --- .../rust-analyzer/crates/hir-def/src/data.rs | 4 + .../crates/hir-def/src/item_tree.rs | 1 + .../crates/hir-def/src/item_tree/lower.rs | 3 + .../crates/hir-def/src/item_tree/pretty.rs | 3 + .../rust-analyzer/crates/hir-ty/src/utils.rs | 12 +- .../src/handlers/missing_unsafe.rs | 4 +- .../crates/parser/src/grammar/items.rs | 6 + .../parser/src/syntax_kind/generated.rs | 6 +- ...73_safe_declarations_in_extern_blocks.rast | 208 ++++++++++++++++++ ...0073_safe_declarations_in_extern_blocks.rs | 17 ++ .../rust-analyzer/crates/syntax/rust.ungram | 3 +- .../crates/syntax/src/ast/generated/nodes.rs | 6 + 12 files changed, 264 insertions(+), 9 deletions(-) create mode 100644 src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rast create mode 100644 src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rs diff --git a/src/tools/rust-analyzer/crates/hir-def/src/data.rs b/src/tools/rust-analyzer/crates/hir-def/src/data.rs index 3ecb57c75671..f2c49813fa0e 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/data.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/data.rs @@ -148,6 +148,10 @@ impl FunctionData { self.flags.contains(FnFlags::HAS_UNSAFE_KW) } + pub fn is_safe(&self) -> bool { + self.flags.contains(FnFlags::HAS_SAFE_KW) + } + pub fn is_varargs(&self) -> bool { self.flags.contains(FnFlags::IS_VARARGS) } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs index f16230e1dc31..4bee7eeb9e52 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs @@ -754,6 +754,7 @@ bitflags::bitflags! { const HAS_ASYNC_KW = 1 << 4; const HAS_UNSAFE_KW = 1 << 5; const IS_VARARGS = 1 << 6; + const HAS_SAFE_KW = 1 << 7; } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index 7aac383ab479..1d8d236d971f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -440,6 +440,9 @@ impl<'a> Ctx<'a> { if func.unsafe_token().is_some() { flags |= FnFlags::HAS_UNSAFE_KW; } + if func.safe_token().is_some() { + flags |= FnFlags::HAS_SAFE_KW; + } if has_var_args { flags |= FnFlags::IS_VARARGS; } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs index b5a65abce869..5ab4718a36b9 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs @@ -278,6 +278,9 @@ impl Printer<'_> { if flags.contains(FnFlags::HAS_UNSAFE_KW) { w!(self, "unsafe "); } + if flags.contains(FnFlags::HAS_SAFE_KW) { + w!(self, "safe "); + } if let Some(abi) = abi { w!(self, "extern \"{}\" ", abi); } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs index d1ce68da6d6d..10252ce6f3e4 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs @@ -257,10 +257,12 @@ pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool { return true; } - match func.lookup(db.upcast()).container { + let loc = func.lookup(db.upcast()); + match loc.container { hir_def::ItemContainerId::ExternBlockId(block) => { - // Function in an `extern` block are always unsafe to call, except when it has - // `"rust-intrinsic"` ABI there are a few exceptions. + // Function in an `extern` block are always unsafe to call, except when + // it is marked as `safe` or it has `"rust-intrinsic"` ABI there are a + // few exceptions. let id = block.lookup(db.upcast()).id; let is_intrinsic = @@ -270,8 +272,8 @@ pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool { // Intrinsics are unsafe unless they have the rustc_safe_intrinsic attribute !data.attrs.by_key(&sym::rustc_safe_intrinsic).exists() } else { - // Extern items are always unsafe - true + // Extern items without `safe` modifier are always unsafe + !db.function_data(func).is_safe() } } _ => false, diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs index 5b43f4b2af3d..a53dd31286fc 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs @@ -554,7 +554,7 @@ fn main() { r#" //- /ed2021.rs crate:ed2021 edition:2021 #[rustc_deprecated_safe_2024] -unsafe fn safe() -> u8 { +unsafe fn safe_fn() -> u8 { 0 } //- /ed2024.rs crate:ed2024 edition:2024 @@ -564,7 +564,7 @@ unsafe fn not_safe() -> u8 { } //- /main.rs crate:main deps:ed2021,ed2024 fn main() { - ed2021::safe(); + ed2021::safe_fn(); ed2024::not_safe(); //^^^^^^^^^^^^^^^^^^💡 error: this operation is unsafe and requires an unsafe function or block } diff --git a/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs b/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs index 4e2a50d7a1fe..5f46093da523 100644 --- a/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs +++ b/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs @@ -135,6 +135,11 @@ pub(super) fn opt_item(p: &mut Parser<'_>, m: Marker) -> Result<(), Marker> { has_mods = true; } + if p.at(T![safe]) { + p.eat(T![safe]); + has_mods = true; + } + if p.at(T![extern]) { has_extern = true; has_mods = true; @@ -189,6 +194,7 @@ pub(super) fn opt_item(p: &mut Parser<'_>, m: Marker) -> Result<(), Marker> { T![fn] => fn_(p, m), T![const] if p.nth(1) != T!['{'] => consts::konst(p, m), + T![static] if matches!(p.nth(1), IDENT | T![_] | T![mut]) => consts::static_(p, m), T![trait] => traits::trait_(p, m), T![impl] => traits::impl_(p, m), diff --git a/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs b/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs index 288a07ef44dc..39d9d7e340b1 100644 --- a/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs +++ b/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs @@ -94,6 +94,7 @@ pub enum SyntaxKind { PUB_KW, REF_KW, RETURN_KW, + SAFE_KW, SELF_KW, STATIC_KW, STRUCT_KW, @@ -364,6 +365,7 @@ impl SyntaxKind { | PUB_KW | REF_KW | RETURN_KW + | SAFE_KW | SELF_KW | STATIC_KW | STRUCT_KW @@ -458,6 +460,7 @@ impl SyntaxKind { | PUB_KW | REF_KW | RETURN_KW + | SAFE_KW | SELF_KW | STATIC_KW | STRUCT_KW @@ -614,6 +617,7 @@ impl SyntaxKind { "pub" => PUB_KW, "ref" => REF_KW, "return" => RETURN_KW, + "safe" => SAFE_KW, "self" => SELF_KW, "static" => STATIC_KW, "struct" => STRUCT_KW, @@ -707,4 +711,4 @@ impl SyntaxKind { } } #[macro_export] -macro_rules ! T { [$] => { $ crate :: SyntaxKind :: DOLLAR } ; [;] => { $ crate :: SyntaxKind :: SEMICOLON } ; [,] => { $ crate :: SyntaxKind :: COMMA } ; ['('] => { $ crate :: SyntaxKind :: L_PAREN } ; [')'] => { $ crate :: SyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: SyntaxKind :: L_CURLY } ; ['}'] => { $ crate :: SyntaxKind :: R_CURLY } ; ['['] => { $ crate :: SyntaxKind :: L_BRACK } ; [']'] => { $ crate :: SyntaxKind :: R_BRACK } ; [<] => { $ crate :: SyntaxKind :: L_ANGLE } ; [>] => { $ crate :: SyntaxKind :: R_ANGLE } ; [@] => { $ crate :: SyntaxKind :: AT } ; [#] => { $ crate :: SyntaxKind :: POUND } ; [~] => { $ crate :: SyntaxKind :: TILDE } ; [?] => { $ crate :: SyntaxKind :: QUESTION } ; [&] => { $ crate :: SyntaxKind :: AMP } ; [|] => { $ crate :: SyntaxKind :: PIPE } ; [+] => { $ crate :: SyntaxKind :: PLUS } ; [*] => { $ crate :: SyntaxKind :: STAR } ; [/] => { $ crate :: SyntaxKind :: SLASH } ; [^] => { $ crate :: SyntaxKind :: CARET } ; [%] => { $ crate :: SyntaxKind :: PERCENT } ; [_] => { $ crate :: SyntaxKind :: UNDERSCORE } ; [.] => { $ crate :: SyntaxKind :: DOT } ; [..] => { $ crate :: SyntaxKind :: DOT2 } ; [...] => { $ crate :: SyntaxKind :: DOT3 } ; [..=] => { $ crate :: SyntaxKind :: DOT2EQ } ; [:] => { $ crate :: SyntaxKind :: COLON } ; [::] => { $ crate :: SyntaxKind :: COLON2 } ; [=] => { $ crate :: SyntaxKind :: EQ } ; [==] => { $ crate :: SyntaxKind :: EQ2 } ; [=>] => { $ crate :: SyntaxKind :: FAT_ARROW } ; [!] => { $ crate :: SyntaxKind :: BANG } ; [!=] => { $ crate :: SyntaxKind :: NEQ } ; [-] => { $ crate :: SyntaxKind :: MINUS } ; [->] => { $ crate :: SyntaxKind :: THIN_ARROW } ; [<=] => { $ crate :: SyntaxKind :: LTEQ } ; [>=] => { $ crate :: SyntaxKind :: GTEQ } ; [+=] => { $ crate :: SyntaxKind :: PLUSEQ } ; [-=] => { $ crate :: SyntaxKind :: MINUSEQ } ; [|=] => { $ crate :: SyntaxKind :: PIPEEQ } ; [&=] => { $ crate :: SyntaxKind :: AMPEQ } ; [^=] => { $ crate :: SyntaxKind :: CARETEQ } ; [/=] => { $ crate :: SyntaxKind :: SLASHEQ } ; [*=] => { $ crate :: SyntaxKind :: STAREQ } ; [%=] => { $ crate :: SyntaxKind :: PERCENTEQ } ; [&&] => { $ crate :: SyntaxKind :: AMP2 } ; [||] => { $ crate :: SyntaxKind :: PIPE2 } ; [<<] => { $ crate :: SyntaxKind :: SHL } ; [>>] => { $ crate :: SyntaxKind :: SHR } ; [<<=] => { $ crate :: SyntaxKind :: SHLEQ } ; [>>=] => { $ crate :: SyntaxKind :: SHREQ } ; [Self] => { $ crate :: SyntaxKind :: SELF_TYPE_KW } ; [abstract] => { $ crate :: SyntaxKind :: ABSTRACT_KW } ; [as] => { $ crate :: SyntaxKind :: AS_KW } ; [become] => { $ crate :: SyntaxKind :: BECOME_KW } ; [box] => { $ crate :: SyntaxKind :: BOX_KW } ; [break] => { $ crate :: SyntaxKind :: BREAK_KW } ; [const] => { $ crate :: SyntaxKind :: CONST_KW } ; [continue] => { $ crate :: SyntaxKind :: CONTINUE_KW } ; [crate] => { $ crate :: SyntaxKind :: CRATE_KW } ; [do] => { $ crate :: SyntaxKind :: DO_KW } ; [else] => { $ crate :: SyntaxKind :: ELSE_KW } ; [enum] => { $ crate :: SyntaxKind :: ENUM_KW } ; [extern] => { $ crate :: SyntaxKind :: EXTERN_KW } ; [false] => { $ crate :: SyntaxKind :: FALSE_KW } ; [final] => { $ crate :: SyntaxKind :: FINAL_KW } ; [fn] => { $ crate :: SyntaxKind :: FN_KW } ; [for] => { $ crate :: SyntaxKind :: FOR_KW } ; [if] => { $ crate :: SyntaxKind :: IF_KW } ; [impl] => { $ crate :: SyntaxKind :: IMPL_KW } ; [in] => { $ crate :: SyntaxKind :: IN_KW } ; [let] => { $ crate :: SyntaxKind :: LET_KW } ; [loop] => { $ crate :: SyntaxKind :: LOOP_KW } ; [macro] => { $ crate :: SyntaxKind :: MACRO_KW } ; [match] => { $ crate :: SyntaxKind :: MATCH_KW } ; [mod] => { $ crate :: SyntaxKind :: MOD_KW } ; [move] => { $ crate :: SyntaxKind :: MOVE_KW } ; [mut] => { $ crate :: SyntaxKind :: MUT_KW } ; [override] => { $ crate :: SyntaxKind :: OVERRIDE_KW } ; [priv] => { $ crate :: SyntaxKind :: PRIV_KW } ; [pub] => { $ crate :: SyntaxKind :: PUB_KW } ; [ref] => { $ crate :: SyntaxKind :: REF_KW } ; [return] => { $ crate :: SyntaxKind :: RETURN_KW } ; [self] => { $ crate :: SyntaxKind :: SELF_KW } ; [static] => { $ crate :: SyntaxKind :: STATIC_KW } ; [struct] => { $ crate :: SyntaxKind :: STRUCT_KW } ; [super] => { $ crate :: SyntaxKind :: SUPER_KW } ; [trait] => { $ crate :: SyntaxKind :: TRAIT_KW } ; [true] => { $ crate :: SyntaxKind :: TRUE_KW } ; [type] => { $ crate :: SyntaxKind :: TYPE_KW } ; [typeof] => { $ crate :: SyntaxKind :: TYPEOF_KW } ; [unsafe] => { $ crate :: SyntaxKind :: UNSAFE_KW } ; [unsized] => { $ crate :: SyntaxKind :: UNSIZED_KW } ; [use] => { $ crate :: SyntaxKind :: USE_KW } ; [virtual] => { $ crate :: SyntaxKind :: VIRTUAL_KW } ; [where] => { $ crate :: SyntaxKind :: WHERE_KW } ; [while] => { $ crate :: SyntaxKind :: WHILE_KW } ; [yield] => { $ crate :: SyntaxKind :: YIELD_KW } ; [asm] => { $ crate :: SyntaxKind :: ASM_KW } ; [att_syntax] => { $ crate :: SyntaxKind :: ATT_SYNTAX_KW } ; [auto] => { $ crate :: SyntaxKind :: AUTO_KW } ; [builtin] => { $ crate :: SyntaxKind :: BUILTIN_KW } ; [clobber_abi] => { $ crate :: SyntaxKind :: CLOBBER_ABI_KW } ; [default] => { $ crate :: SyntaxKind :: DEFAULT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [format_args] => { $ crate :: SyntaxKind :: FORMAT_ARGS_KW } ; [inlateout] => { $ crate :: SyntaxKind :: INLATEOUT_KW } ; [inout] => { $ crate :: SyntaxKind :: INOUT_KW } ; [label] => { $ crate :: SyntaxKind :: LABEL_KW } ; [lateout] => { $ crate :: SyntaxKind :: LATEOUT_KW } ; [macro_rules] => { $ crate :: SyntaxKind :: MACRO_RULES_KW } ; [may_unwind] => { $ crate :: SyntaxKind :: MAY_UNWIND_KW } ; [nomem] => { $ crate :: SyntaxKind :: NOMEM_KW } ; [noreturn] => { $ crate :: SyntaxKind :: NORETURN_KW } ; [nostack] => { $ crate :: SyntaxKind :: NOSTACK_KW } ; [offset_of] => { $ crate :: SyntaxKind :: OFFSET_OF_KW } ; [options] => { $ crate :: SyntaxKind :: OPTIONS_KW } ; [out] => { $ crate :: SyntaxKind :: OUT_KW } ; [preserves_flags] => { $ crate :: SyntaxKind :: PRESERVES_FLAGS_KW } ; [pure] => { $ crate :: SyntaxKind :: PURE_KW } ; [raw] => { $ crate :: SyntaxKind :: RAW_KW } ; [readonly] => { $ crate :: SyntaxKind :: READONLY_KW } ; [sym] => { $ crate :: SyntaxKind :: SYM_KW } ; [union] => { $ crate :: SyntaxKind :: UNION_KW } ; [yeet] => { $ crate :: SyntaxKind :: YEET_KW } ; [async] => { $ crate :: SyntaxKind :: ASYNC_KW } ; [await] => { $ crate :: SyntaxKind :: AWAIT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [gen] => { $ crate :: SyntaxKind :: GEN_KW } ; [try] => { $ crate :: SyntaxKind :: TRY_KW } ; [lifetime_ident] => { $ crate :: SyntaxKind :: LIFETIME_IDENT } ; [int_number] => { $ crate :: SyntaxKind :: INT_NUMBER } ; [ident] => { $ crate :: SyntaxKind :: IDENT } ; [string] => { $ crate :: SyntaxKind :: STRING } ; [shebang] => { $ crate :: SyntaxKind :: SHEBANG } ; } +macro_rules ! T { [$] => { $ crate :: SyntaxKind :: DOLLAR } ; [;] => { $ crate :: SyntaxKind :: SEMICOLON } ; [,] => { $ crate :: SyntaxKind :: COMMA } ; ['('] => { $ crate :: SyntaxKind :: L_PAREN } ; [')'] => { $ crate :: SyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: SyntaxKind :: L_CURLY } ; ['}'] => { $ crate :: SyntaxKind :: R_CURLY } ; ['['] => { $ crate :: SyntaxKind :: L_BRACK } ; [']'] => { $ crate :: SyntaxKind :: R_BRACK } ; [<] => { $ crate :: SyntaxKind :: L_ANGLE } ; [>] => { $ crate :: SyntaxKind :: R_ANGLE } ; [@] => { $ crate :: SyntaxKind :: AT } ; [#] => { $ crate :: SyntaxKind :: POUND } ; [~] => { $ crate :: SyntaxKind :: TILDE } ; [?] => { $ crate :: SyntaxKind :: QUESTION } ; [&] => { $ crate :: SyntaxKind :: AMP } ; [|] => { $ crate :: SyntaxKind :: PIPE } ; [+] => { $ crate :: SyntaxKind :: PLUS } ; [*] => { $ crate :: SyntaxKind :: STAR } ; [/] => { $ crate :: SyntaxKind :: SLASH } ; [^] => { $ crate :: SyntaxKind :: CARET } ; [%] => { $ crate :: SyntaxKind :: PERCENT } ; [_] => { $ crate :: SyntaxKind :: UNDERSCORE } ; [.] => { $ crate :: SyntaxKind :: DOT } ; [..] => { $ crate :: SyntaxKind :: DOT2 } ; [...] => { $ crate :: SyntaxKind :: DOT3 } ; [..=] => { $ crate :: SyntaxKind :: DOT2EQ } ; [:] => { $ crate :: SyntaxKind :: COLON } ; [::] => { $ crate :: SyntaxKind :: COLON2 } ; [=] => { $ crate :: SyntaxKind :: EQ } ; [==] => { $ crate :: SyntaxKind :: EQ2 } ; [=>] => { $ crate :: SyntaxKind :: FAT_ARROW } ; [!] => { $ crate :: SyntaxKind :: BANG } ; [!=] => { $ crate :: SyntaxKind :: NEQ } ; [-] => { $ crate :: SyntaxKind :: MINUS } ; [->] => { $ crate :: SyntaxKind :: THIN_ARROW } ; [<=] => { $ crate :: SyntaxKind :: LTEQ } ; [>=] => { $ crate :: SyntaxKind :: GTEQ } ; [+=] => { $ crate :: SyntaxKind :: PLUSEQ } ; [-=] => { $ crate :: SyntaxKind :: MINUSEQ } ; [|=] => { $ crate :: SyntaxKind :: PIPEEQ } ; [&=] => { $ crate :: SyntaxKind :: AMPEQ } ; [^=] => { $ crate :: SyntaxKind :: CARETEQ } ; [/=] => { $ crate :: SyntaxKind :: SLASHEQ } ; [*=] => { $ crate :: SyntaxKind :: STAREQ } ; [%=] => { $ crate :: SyntaxKind :: PERCENTEQ } ; [&&] => { $ crate :: SyntaxKind :: AMP2 } ; [||] => { $ crate :: SyntaxKind :: PIPE2 } ; [<<] => { $ crate :: SyntaxKind :: SHL } ; [>>] => { $ crate :: SyntaxKind :: SHR } ; [<<=] => { $ crate :: SyntaxKind :: SHLEQ } ; [>>=] => { $ crate :: SyntaxKind :: SHREQ } ; [Self] => { $ crate :: SyntaxKind :: SELF_TYPE_KW } ; [abstract] => { $ crate :: SyntaxKind :: ABSTRACT_KW } ; [as] => { $ crate :: SyntaxKind :: AS_KW } ; [become] => { $ crate :: SyntaxKind :: BECOME_KW } ; [box] => { $ crate :: SyntaxKind :: BOX_KW } ; [break] => { $ crate :: SyntaxKind :: BREAK_KW } ; [const] => { $ crate :: SyntaxKind :: CONST_KW } ; [continue] => { $ crate :: SyntaxKind :: CONTINUE_KW } ; [crate] => { $ crate :: SyntaxKind :: CRATE_KW } ; [do] => { $ crate :: SyntaxKind :: DO_KW } ; [else] => { $ crate :: SyntaxKind :: ELSE_KW } ; [enum] => { $ crate :: SyntaxKind :: ENUM_KW } ; [extern] => { $ crate :: SyntaxKind :: EXTERN_KW } ; [false] => { $ crate :: SyntaxKind :: FALSE_KW } ; [final] => { $ crate :: SyntaxKind :: FINAL_KW } ; [fn] => { $ crate :: SyntaxKind :: FN_KW } ; [for] => { $ crate :: SyntaxKind :: FOR_KW } ; [if] => { $ crate :: SyntaxKind :: IF_KW } ; [impl] => { $ crate :: SyntaxKind :: IMPL_KW } ; [in] => { $ crate :: SyntaxKind :: IN_KW } ; [let] => { $ crate :: SyntaxKind :: LET_KW } ; [loop] => { $ crate :: SyntaxKind :: LOOP_KW } ; [macro] => { $ crate :: SyntaxKind :: MACRO_KW } ; [match] => { $ crate :: SyntaxKind :: MATCH_KW } ; [mod] => { $ crate :: SyntaxKind :: MOD_KW } ; [move] => { $ crate :: SyntaxKind :: MOVE_KW } ; [mut] => { $ crate :: SyntaxKind :: MUT_KW } ; [override] => { $ crate :: SyntaxKind :: OVERRIDE_KW } ; [priv] => { $ crate :: SyntaxKind :: PRIV_KW } ; [pub] => { $ crate :: SyntaxKind :: PUB_KW } ; [ref] => { $ crate :: SyntaxKind :: REF_KW } ; [return] => { $ crate :: SyntaxKind :: RETURN_KW } ; [safe] => { $ crate :: SyntaxKind :: SAFE_KW } ; [self] => { $ crate :: SyntaxKind :: SELF_KW } ; [static] => { $ crate :: SyntaxKind :: STATIC_KW } ; [struct] => { $ crate :: SyntaxKind :: STRUCT_KW } ; [super] => { $ crate :: SyntaxKind :: SUPER_KW } ; [trait] => { $ crate :: SyntaxKind :: TRAIT_KW } ; [true] => { $ crate :: SyntaxKind :: TRUE_KW } ; [type] => { $ crate :: SyntaxKind :: TYPE_KW } ; [typeof] => { $ crate :: SyntaxKind :: TYPEOF_KW } ; [unsafe] => { $ crate :: SyntaxKind :: UNSAFE_KW } ; [unsized] => { $ crate :: SyntaxKind :: UNSIZED_KW } ; [use] => { $ crate :: SyntaxKind :: USE_KW } ; [virtual] => { $ crate :: SyntaxKind :: VIRTUAL_KW } ; [where] => { $ crate :: SyntaxKind :: WHERE_KW } ; [while] => { $ crate :: SyntaxKind :: WHILE_KW } ; [yield] => { $ crate :: SyntaxKind :: YIELD_KW } ; [asm] => { $ crate :: SyntaxKind :: ASM_KW } ; [att_syntax] => { $ crate :: SyntaxKind :: ATT_SYNTAX_KW } ; [auto] => { $ crate :: SyntaxKind :: AUTO_KW } ; [builtin] => { $ crate :: SyntaxKind :: BUILTIN_KW } ; [clobber_abi] => { $ crate :: SyntaxKind :: CLOBBER_ABI_KW } ; [default] => { $ crate :: SyntaxKind :: DEFAULT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [format_args] => { $ crate :: SyntaxKind :: FORMAT_ARGS_KW } ; [inlateout] => { $ crate :: SyntaxKind :: INLATEOUT_KW } ; [inout] => { $ crate :: SyntaxKind :: INOUT_KW } ; [label] => { $ crate :: SyntaxKind :: LABEL_KW } ; [lateout] => { $ crate :: SyntaxKind :: LATEOUT_KW } ; [macro_rules] => { $ crate :: SyntaxKind :: MACRO_RULES_KW } ; [may_unwind] => { $ crate :: SyntaxKind :: MAY_UNWIND_KW } ; [nomem] => { $ crate :: SyntaxKind :: NOMEM_KW } ; [noreturn] => { $ crate :: SyntaxKind :: NORETURN_KW } ; [nostack] => { $ crate :: SyntaxKind :: NOSTACK_KW } ; [offset_of] => { $ crate :: SyntaxKind :: OFFSET_OF_KW } ; [options] => { $ crate :: SyntaxKind :: OPTIONS_KW } ; [out] => { $ crate :: SyntaxKind :: OUT_KW } ; [preserves_flags] => { $ crate :: SyntaxKind :: PRESERVES_FLAGS_KW } ; [pure] => { $ crate :: SyntaxKind :: PURE_KW } ; [raw] => { $ crate :: SyntaxKind :: RAW_KW } ; [readonly] => { $ crate :: SyntaxKind :: READONLY_KW } ; [sym] => { $ crate :: SyntaxKind :: SYM_KW } ; [union] => { $ crate :: SyntaxKind :: UNION_KW } ; [yeet] => { $ crate :: SyntaxKind :: YEET_KW } ; [async] => { $ crate :: SyntaxKind :: ASYNC_KW } ; [await] => { $ crate :: SyntaxKind :: AWAIT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [gen] => { $ crate :: SyntaxKind :: GEN_KW } ; [try] => { $ crate :: SyntaxKind :: TRY_KW } ; [lifetime_ident] => { $ crate :: SyntaxKind :: LIFETIME_IDENT } ; [int_number] => { $ crate :: SyntaxKind :: INT_NUMBER } ; [ident] => { $ crate :: SyntaxKind :: IDENT } ; [string] => { $ crate :: SyntaxKind :: STRING } ; [shebang] => { $ crate :: SyntaxKind :: SHEBANG } ; } diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rast b/src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rast new file mode 100644 index 000000000000..b3d9e5580675 --- /dev/null +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rast @@ -0,0 +1,208 @@ +SOURCE_FILE + EXTERN_BLOCK + UNSAFE_KW "unsafe" + WHITESPACE " " + ABI + EXTERN_KW "extern" + WHITESPACE " " + EXTERN_ITEM_LIST + L_CURLY "{" + WHITESPACE "\n " + FN + COMMENT "// sqrt (from libm) may be called with any `f64`" + WHITESPACE "\n " + VISIBILITY + PUB_KW "pub" + WHITESPACE " " + SAFE_KW "safe" + WHITESPACE " " + FN_KW "fn" + WHITESPACE " " + NAME + IDENT "sqrt" + PARAM_LIST + L_PAREN "(" + PARAM + IDENT_PAT + NAME + IDENT "x" + COLON ":" + WHITESPACE " " + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "f64" + R_PAREN ")" + WHITESPACE " " + RET_TYPE + THIN_ARROW "->" + WHITESPACE " " + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "f64" + SEMICOLON ";" + WHITESPACE "\n\n " + FN + COMMENT "// strlen (from libc) requires a valid pointer," + WHITESPACE "\n " + COMMENT "// so we mark it as being an unsafe fn" + WHITESPACE "\n " + VISIBILITY + PUB_KW "pub" + WHITESPACE " " + UNSAFE_KW "unsafe" + WHITESPACE " " + FN_KW "fn" + WHITESPACE " " + NAME + IDENT "strlen" + PARAM_LIST + L_PAREN "(" + PARAM + IDENT_PAT + NAME + IDENT "p" + COLON ":" + WHITESPACE " " + PTR_TYPE + STAR "*" + CONST_KW "const" + WHITESPACE " " + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "c_char" + R_PAREN ")" + WHITESPACE " " + RET_TYPE + THIN_ARROW "->" + WHITESPACE " " + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "usize" + SEMICOLON ";" + WHITESPACE "\n\n " + FN + COMMENT "// this function doesn't say safe or unsafe, so it defaults to unsafe" + WHITESPACE "\n " + VISIBILITY + PUB_KW "pub" + WHITESPACE " " + FN_KW "fn" + WHITESPACE " " + NAME + IDENT "free" + PARAM_LIST + L_PAREN "(" + PARAM + IDENT_PAT + NAME + IDENT "p" + COLON ":" + WHITESPACE " " + PTR_TYPE + STAR "*" + MUT_KW "mut" + WHITESPACE " " + PATH_TYPE + PATH + PATH + PATH + PATH_SEGMENT + NAME_REF + IDENT "core" + COLON2 "::" + PATH_SEGMENT + NAME_REF + IDENT "ffi" + COLON2 "::" + PATH_SEGMENT + NAME_REF + IDENT "c_void" + R_PAREN ")" + SEMICOLON ";" + WHITESPACE "\n\n " + STATIC + VISIBILITY + PUB_KW "pub" + WHITESPACE " " + SAFE_KW "safe" + WHITESPACE " " + STATIC_KW "static" + WHITESPACE " " + MUT_KW "mut" + WHITESPACE " " + NAME + IDENT "COUNTER" + COLON ":" + WHITESPACE " " + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "i32" + SEMICOLON ";" + WHITESPACE "\n\n " + STATIC + VISIBILITY + PUB_KW "pub" + WHITESPACE " " + UNSAFE_KW "unsafe" + WHITESPACE " " + STATIC_KW "static" + WHITESPACE " " + NAME + IDENT "IMPORTANT_BYTES" + COLON ":" + WHITESPACE " " + ARRAY_TYPE + L_BRACK "[" + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "u8" + SEMICOLON ";" + WHITESPACE " " + CONST_ARG + LITERAL + INT_NUMBER "256" + R_BRACK "]" + SEMICOLON ";" + WHITESPACE "\n\n " + STATIC + VISIBILITY + PUB_KW "pub" + WHITESPACE " " + SAFE_KW "safe" + WHITESPACE " " + STATIC_KW "static" + WHITESPACE " " + NAME + IDENT "LINES" + COLON ":" + WHITESPACE " " + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "SyncUnsafeCell" + GENERIC_ARG_LIST + L_ANGLE "<" + TYPE_ARG + PATH_TYPE + PATH + PATH_SEGMENT + NAME_REF + IDENT "i32" + R_ANGLE ">" + SEMICOLON ";" + WHITESPACE "\n" + R_CURLY "}" + WHITESPACE "\n" diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rs b/src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rs new file mode 100644 index 000000000000..267a128649c7 --- /dev/null +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rs @@ -0,0 +1,17 @@ +unsafe extern { + // sqrt (from libm) may be called with any `f64` + pub safe fn sqrt(x: f64) -> f64; + + // strlen (from libc) requires a valid pointer, + // so we mark it as being an unsafe fn + pub unsafe fn strlen(p: *const c_char) -> usize; + + // this function doesn't say safe or unsafe, so it defaults to unsafe + pub fn free(p: *mut core::ffi::c_void); + + pub safe static mut COUNTER: i32; + + pub unsafe static IMPORTANT_BYTES: [u8; 256]; + + pub safe static LINES: SyncUnsafeCell; +} diff --git a/src/tools/rust-analyzer/crates/syntax/rust.ungram b/src/tools/rust-analyzer/crates/syntax/rust.ungram index 52ad439e4dec..90441c27f628 100644 --- a/src/tools/rust-analyzer/crates/syntax/rust.ungram +++ b/src/tools/rust-analyzer/crates/syntax/rust.ungram @@ -190,7 +190,7 @@ UseTreeList = Fn = Attr* Visibility? - 'default'? 'const'? 'async'? 'gen'? 'unsafe'? Abi? + 'default'? 'const'? 'async'? 'gen'? 'unsafe'? 'safe'? Abi? 'fn' Name GenericParamList? ParamList RetType? WhereClause? (body:BlockExpr | ';') @@ -284,6 +284,7 @@ Const = Static = Attr* Visibility? + 'unsafe'? 'safe'? 'static' 'mut'? Name ':' Type ('=' body:Expr)? ';' diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs index c81a19f3bda4..4f8bff489cfb 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs @@ -668,6 +668,8 @@ impl Fn { #[inline] pub fn gen_token(&self) -> Option { support::token(&self.syntax, T![gen]) } #[inline] + pub fn safe_token(&self) -> Option { support::token(&self.syntax, T![safe]) } + #[inline] pub fn unsafe_token(&self) -> Option { support::token(&self.syntax, T![unsafe]) } } @@ -1761,7 +1763,11 @@ impl Static { #[inline] pub fn mut_token(&self) -> Option { support::token(&self.syntax, T![mut]) } #[inline] + pub fn safe_token(&self) -> Option { support::token(&self.syntax, T![safe]) } + #[inline] pub fn static_token(&self) -> Option { support::token(&self.syntax, T![static]) } + #[inline] + pub fn unsafe_token(&self) -> Option { support::token(&self.syntax, T![unsafe]) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] From 57d5f864e3ff87d7e5ba06f6175c9aa50d576848 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 18 Oct 2024 07:53:56 +0200 Subject: [PATCH 053/366] x86-32 float return for 'Rust' ABI: treat all float types consistently --- compiler/rustc_ty_utils/src/abi.rs | 41 +++++++++++-------------- tests/codegen/float/f128.rs | 6 ++-- tests/codegen/float/f16.rs | 49 ++++++++++++++++-------------- 3 files changed, 48 insertions(+), 48 deletions(-) diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 13691204c96a..09b9ecb3486e 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -1,6 +1,5 @@ use std::iter; -use rustc_abi::Float::*; use rustc_abi::Primitive::{Float, Pointer}; use rustc_abi::{Abi, AddressSpace, PointerKind, Scalar, Size}; use rustc_hir as hir; @@ -695,37 +694,31 @@ fn fn_abi_adjust_for_abi<'tcx>( } // Avoid returning floats in x87 registers on x86 as loading and storing from x87 - // registers will quiet signalling NaNs. + // registers will quiet signalling NaNs. Also avoid using SSE registers since they + // are not always available (depending on target features). if tcx.sess.target.arch == "x86" && arg_idx.is_none() // Intrinsics themselves are not actual "real" functions, so theres no need to // change their ABIs. && abi != SpecAbi::RustIntrinsic { - match arg.layout.abi { - // Handle similar to the way arguments with an `Abi::Aggregate` abi are handled - // below, by returning arguments up to the size of a pointer (32 bits on x86) - // cast to an appropriately sized integer. - Abi::Scalar(s) if s.primitive() == Float(F32) => { - // Same size as a pointer, return in a register. - arg.cast_to(Reg::i32()); - return; + let has_float = match arg.layout.abi { + Abi::Scalar(s) => matches!(s.primitive(), Float(_)), + Abi::ScalarPair(s1, s2) => { + matches!(s1.primitive(), Float(_)) || matches!(s2.primitive(), Float(_)) } - Abi::Scalar(s) if s.primitive() == Float(F64) => { - // Larger than a pointer, return indirectly. - arg.make_indirect(); - return; - } - Abi::ScalarPair(s1, s2) - if matches!(s1.primitive(), Float(F32 | F64)) - || matches!(s2.primitive(), Float(F32 | F64)) => - { - // Larger than a pointer, return indirectly. - arg.make_indirect(); - return; - } - _ => {} + _ => false, // anyway not passed via registers on x86 }; + if has_float { + if arg.layout.size <= Pointer(AddressSpace::DATA).size(cx) { + // Same size or smaller than pointer, return in a register. + arg.cast_to(Reg { kind: RegKind::Integer, size: arg.layout.size }); + } else { + // Larger than a pointer, return indirectly. + arg.make_indirect(); + } + return; + } } if arg_idx.is_none() && arg.layout.size > Pointer(AddressSpace::DATA).size(cx) * 2 { diff --git a/tests/codegen/float/f128.rs b/tests/codegen/float/f128.rs index 4af264101dee..514d35433e12 100644 --- a/tests/codegen/float/f128.rs +++ b/tests/codegen/float/f128.rs @@ -1,4 +1,4 @@ -// 32-bit x86 returns `f32` and `f64` differently to avoid the x87 stack. +// 32-bit x86 returns float types differently to avoid the x87 stack. // 32-bit systems will return 128bit values using a return area pointer. //@ revisions: x86 bit32 bit64 //@[x86] only-x86 @@ -152,7 +152,9 @@ pub fn f128_rem_assign(a: &mut f128, b: f128) { /* float to float conversions */ -// CHECK-LABEL: half @f128_as_f16( +// x86-LABEL: i16 @f128_as_f16( +// bits32-LABEL: half @f128_as_f16( +// bits64-LABEL: half @f128_as_f16( #[no_mangle] pub fn f128_as_f16(a: f128) -> f16 { // CHECK: fptrunc fp128 %{{.+}} to half diff --git a/tests/codegen/float/f16.rs b/tests/codegen/float/f16.rs index 80931051f188..5c3a5893b9d2 100644 --- a/tests/codegen/float/f16.rs +++ b/tests/codegen/float/f16.rs @@ -1,4 +1,4 @@ -// 32-bit x86 returns `f32` and `f64` differently to avoid the x87 stack. +// 32-bit x86 returns float types differently to avoid the x87 stack. // 32-bit systems will return 128bit values using a return area pointer. //@ revisions: x86 bit32 bit64 //@[x86] only-x86 @@ -58,42 +58,44 @@ pub fn f16_le(a: f16, b: f16) -> bool { a <= b } -// CHECK-LABEL: half @f16_neg( +// This is where we check the argument and return ABI for f16. +// other-LABEL: half @f16_neg(half +// x86-LABEL: i16 @f16_neg(half #[no_mangle] pub fn f16_neg(a: f16) -> f16 { // CHECK: fneg half %{{.+}} -a } -// CHECK-LABEL: half @f16_add( +// CHECK-LABEL: @f16_add #[no_mangle] pub fn f16_add(a: f16, b: f16) -> f16 { // CHECK: fadd half %{{.+}}, %{{.+}} a + b } -// CHECK-LABEL: half @f16_sub( +// CHECK-LABEL: @f16_sub #[no_mangle] pub fn f16_sub(a: f16, b: f16) -> f16 { // CHECK: fsub half %{{.+}}, %{{.+}} a - b } -// CHECK-LABEL: half @f16_mul( +// CHECK-LABEL: @f16_mul #[no_mangle] pub fn f16_mul(a: f16, b: f16) -> f16 { // CHECK: fmul half %{{.+}}, %{{.+}} a * b } -// CHECK-LABEL: half @f16_div( +// CHECK-LABEL: @f16_div #[no_mangle] pub fn f16_div(a: f16, b: f16) -> f16 { // CHECK: fdiv half %{{.+}}, %{{.+}} a / b } -// CHECK-LABEL: half @f16_rem( +// CHECK-LABEL: @f16_rem #[no_mangle] pub fn f16_rem(a: f16, b: f16) -> f16 { // CHECK: frem half %{{.+}}, %{{.+}} @@ -142,10 +144,13 @@ pub fn f16_rem_assign(a: &mut f16, b: f16) { /* float to float conversions */ -// CHECK-LABEL: half @f16_as_self( +// other-LABEL: half @f16_as_self( +// x86-LABEL: i16 @f16_as_self( #[no_mangle] pub fn f16_as_self(a: f16) -> f16 { - // CHECK: ret half %{{.+}} + // other-CHECK: ret half %{{.+}} + // x86-CHECK: bitcast half + // x86-CHECK: ret i16 a as f16 } @@ -176,21 +181,21 @@ pub fn f16_as_f128(a: f16) -> f128 { a as f128 } -// CHECK-LABEL: half @f32_as_f16( +// CHECK-LABEL: @f32_as_f16 #[no_mangle] pub fn f32_as_f16(a: f32) -> f16 { // CHECK: fptrunc float %{{.+}} to half a as f16 } -// CHECK-LABEL: half @f64_as_f16( +// CHECK-LABEL: @f64_as_f16 #[no_mangle] pub fn f64_as_f16(a: f64) -> f16 { // CHECK: fptrunc double %{{.+}} to half a as f16 } -// CHECK-LABEL: half @f128_as_f16( +// CHECK-LABEL: @f128_as_f16 #[no_mangle] pub fn f128_as_f16(a: f128) -> f16 { // CHECK: fptrunc fp128 %{{.+}} to half @@ -273,70 +278,70 @@ pub fn f16_as_i128(a: f16) -> i128 { /* int to float conversions */ -// CHECK-LABEL: half @u8_as_f16( +// CHECK-LABEL: @u8_as_f16 #[no_mangle] pub fn u8_as_f16(a: u8) -> f16 { // CHECK: uitofp i8 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @u16_as_f16( +// CHECK-LABEL: @u16_as_f16 #[no_mangle] pub fn u16_as_f16(a: u16) -> f16 { // CHECK: uitofp i16 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @u32_as_f16( +// CHECK-LABEL: @u32_as_f16 #[no_mangle] pub fn u32_as_f16(a: u32) -> f16 { // CHECK: uitofp i32 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @u64_as_f16( +// CHECK-LABEL: @u64_as_f16 #[no_mangle] pub fn u64_as_f16(a: u64) -> f16 { // CHECK: uitofp i64 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @u128_as_f16( +// CHECK-LABEL: @u128_as_f16 #[no_mangle] pub fn u128_as_f16(a: u128) -> f16 { // CHECK: uitofp i128 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @i8_as_f16( +// CHECK-LABEL: @i8_as_f16 #[no_mangle] pub fn i8_as_f16(a: i8) -> f16 { // CHECK: sitofp i8 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @i16_as_f16( +// CHECK-LABEL: @i16_as_f16 #[no_mangle] pub fn i16_as_f16(a: i16) -> f16 { // CHECK: sitofp i16 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @i32_as_f16( +// CHECK-LABEL: @i32_as_f16 #[no_mangle] pub fn i32_as_f16(a: i32) -> f16 { // CHECK: sitofp i32 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @i64_as_f16( +// CHECK-LABEL: @i64_as_f16 #[no_mangle] pub fn i64_as_f16(a: i64) -> f16 { // CHECK: sitofp i64 %{{.+}} to half a as f16 } -// CHECK-LABEL: half @i128_as_f16( +// CHECK-LABEL: @i128_as_f16 #[no_mangle] pub fn i128_as_f16(a: i128) -> f16 { // CHECK: sitofp i128 %{{.+}} to half From 37dc4ec8d6519d7ba1ed8a11fb57ff4d1eb995dd Mon Sep 17 00:00:00 2001 From: Andrew Zhogin <44302620+azhogin@users.noreply.github.com> Date: Sun, 20 Oct 2024 18:18:01 +0700 Subject: [PATCH 054/366] Limited -Zregparm support (no Rust calling conv) descriptions Co-authored-by: Jubilee --- compiler/rustc_session/src/options.rs | 3 ++- src/doc/unstable-book/src/compiler-flags/regparm.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index f4a9d4bf92cb..54a4621db246 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2002,7 +2002,8 @@ options! { "randomize the layout of types (default: no)"), regparm: Option = (None, parse_opt_number, [TRACKED], "On x86-32 targets, setting this to N causes the compiler to pass N arguments \ - in registers EAX, EDX, and ECX instead of on the stack.\ + in registers EAX, EDX, and ECX instead of on the stack for\ + \"C\", \"cdecl\", and \"stdcall\" fn.\ It is UNSOUND to link together crates that use different values for this flag!"), relax_elf_relocations: Option = (None, parse_opt_bool, [TRACKED], "whether ELF relocations can be relaxed"), diff --git a/src/doc/unstable-book/src/compiler-flags/regparm.md b/src/doc/unstable-book/src/compiler-flags/regparm.md index a054d55cd8b6..8f311f091c0a 100644 --- a/src/doc/unstable-book/src/compiler-flags/regparm.md +++ b/src/doc/unstable-book/src/compiler-flags/regparm.md @@ -5,7 +5,7 @@ The tracking issue for this feature is: https://github.com/rust-lang/rust/issues ------------------------ Option -Zregparm=N causes the compiler to pass N arguments -in registers EAX, EDX, and ECX instead of on the stack. +in registers EAX, EDX, and ECX instead of on the stack for "C", "cdecl", and "stdcall" fn. It is UNSOUND to link together crates that use different values for this flag. It is only supported on `x86`. From a269e4da72ed1e2dc71eca2871acab6b9f1423c5 Mon Sep 17 00:00:00 2001 From: The 8472 Date: Sun, 20 Oct 2024 02:10:19 +0200 Subject: [PATCH 055/366] run git commands in bootstrap in parallel this saves about 150ms on many ./x invocations --- src/bootstrap/src/lib.rs | 19 ++++++++++++------- src/bootstrap/src/utils/channel.rs | 14 +++++++------- src/bootstrap/src/utils/helpers.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 14 deletions(-) diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 3924a6d714e3..a9db0377a507 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -545,23 +545,28 @@ impl Build { .args(["--get-regexp", "path"]) .run_capture(self) .stdout(); - for line in output.lines() { + std::thread::scope(|s| { // Look for `submodule.$name.path = $path` // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer` - let submodule = line.split_once(' ').unwrap().1; - self.update_existing_submodule(submodule); - } + for line in output.lines() { + let submodule = line.split_once(' ').unwrap().1; + let config = self.config.clone(); + s.spawn(move || { + Self::update_existing_submodule(&config, submodule); + }); + } + }); } /// Updates the given submodule only if it's initialized already; nothing happens otherwise. - pub fn update_existing_submodule(&self, submodule: &str) { + pub fn update_existing_submodule(config: &Config, submodule: &str) { // Avoid running git when there isn't a git checkout. - if !self.config.submodules() { + if !config.submodules() { return; } if GitInfo::new(false, Path::new(submodule)).is_managed_git_subrepository() { - self.config.update_submodule(submodule); + config.update_submodule(submodule); } } diff --git a/src/bootstrap/src/utils/channel.rs b/src/bootstrap/src/utils/channel.rs index c361abb9c9e1..4a9ecc7a4f8a 100644 --- a/src/bootstrap/src/utils/channel.rs +++ b/src/bootstrap/src/utils/channel.rs @@ -10,7 +10,7 @@ use std::path::Path; use super::helpers; use crate::Build; -use crate::utils::helpers::{output, t}; +use crate::utils::helpers::{start_process, t}; #[derive(Clone, Default)] pub enum GitInfo { @@ -56,7 +56,7 @@ impl GitInfo { } // Ok, let's scrape some info - let ver_date = output( + let ver_date = start_process( helpers::git(Some(dir)) .arg("log") .arg("-1") @@ -65,14 +65,14 @@ impl GitInfo { .as_command_mut(), ); let ver_hash = - output(helpers::git(Some(dir)).arg("rev-parse").arg("HEAD").as_command_mut()); - let short_ver_hash = output( + start_process(helpers::git(Some(dir)).arg("rev-parse").arg("HEAD").as_command_mut()); + let short_ver_hash = start_process( helpers::git(Some(dir)).arg("rev-parse").arg("--short=9").arg("HEAD").as_command_mut(), ); GitInfo::Present(Some(Info { - commit_date: ver_date.trim().to_string(), - sha: ver_hash.trim().to_string(), - short_sha: short_ver_hash.trim().to_string(), + commit_date: ver_date().trim().to_string(), + sha: ver_hash().trim().to_string(), + short_sha: short_ver_hash().trim().to_string(), })) } diff --git a/src/bootstrap/src/utils/helpers.rs b/src/bootstrap/src/utils/helpers.rs index 2519ace92b9e..7162007e9f0f 100644 --- a/src/bootstrap/src/utils/helpers.rs +++ b/src/bootstrap/src/utils/helpers.rs @@ -288,6 +288,33 @@ pub fn output(cmd: &mut Command) -> String { String::from_utf8(output.stdout).unwrap() } +/// Spawn a process and return a closure that will wait for the process +/// to finish and then return its output. This allows the spawned process +/// to do work without immediately blocking bootstrap. +#[track_caller] +pub fn start_process(cmd: &mut Command) -> impl FnOnce() -> String { + let child = match cmd.stderr(Stdio::inherit()).stdout(Stdio::piped()).spawn() { + Ok(child) => child, + Err(e) => fail(&format!("failed to execute command: {cmd:?}\nERROR: {e}")), + }; + + let command = format!("{:?}", cmd); + + move || { + let output = child.wait_with_output().unwrap(); + + if !output.status.success() { + panic!( + "command did not execute successfully: {}\n\ + expected success, got: {}", + command, output.status + ); + } + + String::from_utf8(output.stdout).unwrap() + } +} + /// Returns the last-modified time for `path`, or zero if it doesn't exist. pub fn mtime(path: &Path) -> SystemTime { fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH) From bc9fc714fb18519c66a10f048c137aba89862b7b Mon Sep 17 00:00:00 2001 From: lucarlig Date: Tue, 15 Oct 2024 11:37:32 +0100 Subject: [PATCH 056/366] add TestFloatParse to tools for bootstrap --- src/bootstrap/src/core/build_steps/test.rs | 4 +-- src/bootstrap/src/core/build_steps/tool.rs | 32 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index e25b571acbac..0a160ce41821 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -3549,9 +3549,7 @@ impl Step for TestFloatParse { let path = self.path.to_str().unwrap(); let crate_name = self.path.components().last().unwrap().as_os_str().to_str().unwrap(); - if !builder.download_rustc() { - builder.ensure(compile::Std::new(compiler, self.host)); - } + builder.ensure(tool::TestFloatParse { host: self.host }); // Run any unit tests in the crate let cargo_test = tool::prepare_tool_cargo( diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index f1a10c3296e9..44f60e186850 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1096,6 +1096,38 @@ tool_extended!((self, builder), Rustfmt, "src/tools/rustfmt", "rustfmt", stable=true, add_bins_to_sysroot = ["rustfmt", "cargo-fmt"]; ); +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct TestFloatParse { + pub host: TargetSelection, +} + +impl Step for TestFloatParse { + type Output = (); + const ONLY_HOSTS: bool = true; + const DEFAULT: bool = false; + + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + run.path("src/etc/test-float-parse") + } + + fn run(self, builder: &Builder<'_>) { + let bootstrap_host = builder.config.build; + let compiler = builder.compiler(builder.top_stage, bootstrap_host); + + builder.ensure(ToolBuild { + compiler, + target: bootstrap_host, + tool: "test-float-parse", + mode: Mode::ToolStd, + path: "src/etc/test-float-parse", + source_type: SourceType::InTree, + extra_features: Vec::new(), + allow_features: "", + cargo_args: Vec::new(), + }); + } +} + impl Builder<'_> { /// Gets a `BootstrapCommand` which is ready to run `tool` in `stage` built for /// `host`. From 1b90ae48926850fbada77692c48f1fd5eee85cd8 Mon Sep 17 00:00:00 2001 From: roife Date: Sun, 20 Oct 2024 19:48:15 +0800 Subject: [PATCH 057/366] fix: do not emit unsafe diagnositcs for safe statics in extern blocks --- .../rust-analyzer/crates/hir-def/src/data.rs | 4 +++ .../crates/hir-def/src/item_tree.rs | 3 ++ .../crates/hir-def/src/item_tree/lower.rs | 5 ++- .../crates/hir-def/src/item_tree/pretty.rs | 16 ++++++++- .../hir-ty/src/diagnostics/unsafe_check.rs | 2 +- .../src/handlers/missing_unsafe.rs | 35 +++++++++++++++++++ 6 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/data.rs b/src/tools/rust-analyzer/crates/hir-def/src/data.rs index f2c49813fa0e..263fad51d78e 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/data.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/data.rs @@ -571,6 +571,8 @@ pub struct StaticData { pub visibility: RawVisibility, pub mutable: bool, pub is_extern: bool, + pub has_safe_kw: bool, + pub has_unsafe_kw: bool, } impl StaticData { @@ -585,6 +587,8 @@ impl StaticData { visibility: item_tree[statik.visibility].clone(), mutable: statik.mutable, is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)), + has_safe_kw: statik.has_safe_kw, + has_unsafe_kw: statik.has_unsafe_kw, }) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs index 4bee7eeb9e52..7cb833fdce7c 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs @@ -823,7 +823,10 @@ pub struct Const { pub struct Static { pub name: Name, pub visibility: RawVisibilityId, + // TODO: use bitflags when we have more flags pub mutable: bool, + pub has_safe_kw: bool, + pub has_unsafe_kw: bool, pub type_ref: Interned, pub ast_id: FileAstId, } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index 1d8d236d971f..431a7f66f405 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -487,8 +487,11 @@ impl<'a> Ctx<'a> { let type_ref = self.lower_type_ref_opt(static_.ty()); let visibility = self.lower_visibility(static_); let mutable = static_.mut_token().is_some(); + let has_safe_kw = static_.safe_token().is_some(); + let has_unsafe_kw = static_.unsafe_token().is_some(); let ast_id = self.source_ast_id_map.ast_id(static_); - let res = Static { name, visibility, mutable, type_ref, ast_id }; + let res = + Static { name, visibility, mutable, type_ref, ast_id, has_safe_kw, has_unsafe_kw }; Some(id(self.data().statics.alloc(res))) } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs index 5ab4718a36b9..9dce28b2e492 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs @@ -382,9 +382,23 @@ impl Printer<'_> { wln!(self, " = _;"); } ModItem::Static(it) => { - let Static { name, visibility, mutable, type_ref, ast_id } = &self.tree[it]; + let Static { + name, + visibility, + mutable, + type_ref, + ast_id, + has_safe_kw, + has_unsafe_kw, + } = &self.tree[it]; self.print_ast_id(ast_id.erase()); self.print_visibility(*visibility); + if *has_safe_kw { + w!(self, "safe "); + } + if *has_unsafe_kw { + w!(self, "unsafe "); + } w!(self, "static "); if *mutable { w!(self, "mut "); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs index ff45c725c73c..bcfc37c86711 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -89,7 +89,7 @@ fn walk_unsafe( let value_or_partial = resolver.resolve_path_in_value_ns(db.upcast(), path); if let Some(ResolveValueResult::ValueNs(ValueNs::StaticId(id), _)) = value_or_partial { let static_data = db.static_data(id); - if static_data.mutable || static_data.is_extern { + if static_data.mutable || (static_data.is_extern && !static_data.has_safe_kw) { unsafe_expr_cb(UnsafeExpr { expr: current, inside_unsafe_block }); } } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs index a53dd31286fc..cc0f4bfccc9a 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs @@ -595,4 +595,39 @@ unsafe fn foo(p: *mut i32) { "#, ) } + + #[test] + fn no_unsafe_diagnostic_with_safe_kw() { + check_diagnostics( + r#" +unsafe extern { + pub safe fn f(); + + pub unsafe fn g(); + + pub fn h(); + + pub safe static S1: i32; + + pub unsafe static S2: i32; + + pub static S3: i32; +} + +fn main() { + f(); + g(); + //^^^💡 error: this operation is unsafe and requires an unsafe function or block + h(); + //^^^💡 error: this operation is unsafe and requires an unsafe function or block + + let _ = S1; + let _ = S2; + //^^💡 error: this operation is unsafe and requires an unsafe function or block + let _ = S3; + //^^💡 error: this operation is unsafe and requires an unsafe function or block +} +"#, + ); + } } From de3cbf3c567e6d81e6ead5c0f646add33df457d1 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 3 Sep 2024 18:48:15 +0200 Subject: [PATCH 058/366] make unsupported_calling_conventions a hard error --- .../rustc_hir_analysis/src/check/check.rs | 45 +++++++---------- compiler/rustc_hir_typeck/src/lib.rs | 2 +- compiler/rustc_lint/src/lib.rs | 1 + compiler/rustc_lint_defs/src/builtin.rs | 48 ------------------- compiler/rustc_target/src/spec/mod.rs | 11 ++--- .../missing_const_for_fn/could_be_const.fixed | 8 ++-- .../ui/missing_const_for_fn/could_be_const.rs | 8 ++-- .../could_be_const.stderr | 12 ++--- tests/ui/abi/unsupported.aarch64.stderr | 25 ++++------ tests/ui/abi/unsupported.arm.stderr | 25 ++++------ tests/ui/abi/unsupported.i686.stderr | 8 ++-- tests/ui/abi/unsupported.riscv32.stderr | 25 ++++------ tests/ui/abi/unsupported.riscv64.stderr | 25 ++++------ tests/ui/abi/unsupported.rs | 30 ++++-------- tests/ui/abi/unsupported.x64.stderr | 25 ++++------ 15 files changed, 97 insertions(+), 201 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 94da3d4ea840..4c383233941d 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -22,7 +22,7 @@ use rustc_middle::ty::{ AdtDef, GenericArgKind, ParamEnv, RegionKind, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; -use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS}; +use rustc_session::lint::builtin::UNINHABITED_STATIC; use rustc_target::abi::FieldIdx; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; @@ -36,36 +36,25 @@ use super::compare_impl_item::{check_type_bounds, compare_impl_method, compare_i use super::*; use crate::check::intrinsicck::InlineAsmCtxt; -pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) { - match tcx.sess.target.is_abi_supported(abi) { - Some(true) => (), - Some(false) => { - struct_span_code_err!( - tcx.dcx(), - span, - E0570, - "`{abi}` is not a supported ABI for the current target", - ) - .emit(); - } - None => { - tcx.node_span_lint(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| { - lint.primary_message("use of calling convention not supported on this target"); - }); - } +pub fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { + if !tcx.sess.target.is_abi_supported(abi) { + struct_span_code_err!( + tcx.dcx(), + span, + E0570, + "`{abi}` is not a supported ABI for the current target", + ) + .emit(); } } pub fn check_abi_fn_ptr(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) { - match tcx.sess.target.is_abi_supported(abi) { - Some(true) => (), - Some(false) | None => { - tcx.node_span_lint(UNSUPPORTED_FN_PTR_CALLING_CONVENTIONS, hir_id, span, |lint| { - lint.primary_message(format!( - "the calling convention {abi} is not supported on this target" - )); - }); - } + if !tcx.sess.target.is_abi_supported(abi) { + tcx.node_span_lint(UNSUPPORTED_FN_PTR_CALLING_CONVENTIONS, hir_id, span, |lint| { + lint.primary_message(format!( + "the calling convention {abi} is not supported on this target" + )); + }); } } @@ -705,7 +694,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) { let hir::ItemKind::ForeignMod { abi, items } = it.kind else { return; }; - check_abi(tcx, it.hir_id(), it.span, abi); + check_abi(tcx, it.span, abi); match abi { Abi::RustIntrinsic => { diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 9e36f7a9aea8..85ee0a5cf7da 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -155,7 +155,7 @@ fn typeck_with_fallback<'tcx>( tcx.fn_sig(def_id).instantiate_identity() }; - check_abi(tcx, id, span, fn_sig.abi()); + check_abi(tcx, span, fn_sig.abi()); // Compute the function signature from point of view of inside the fn. let fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig); diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 81352af3d48f..a7faab0868d8 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -598,6 +598,7 @@ fn register_builtins(store: &mut LintStore) { "converted into hard error, see PR #125380 \ for more information", ); + store.register_removed("unsupported_calling_conventions", "converted into hard error"); } fn register_internals(store: &mut LintStore) { diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 45a5ce0ca20e..b51d44bd51fa 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -123,7 +123,6 @@ declare_lint_pass! { UNSAFE_OP_IN_UNSAFE_FN, UNSTABLE_NAME_COLLISIONS, UNSTABLE_SYNTAX_PRE_EXPANSION, - UNSUPPORTED_CALLING_CONVENTIONS, UNSUPPORTED_FN_PTR_CALLING_CONVENTIONS, UNUSED_ASSIGNMENTS, UNUSED_ASSOCIATED_TYPE_BOUNDS, @@ -3789,53 +3788,6 @@ declare_lint! { crate_level_only } -declare_lint! { - /// The `unsupported_calling_conventions` lint is output whenever there is a use of the - /// `stdcall`, `fastcall`, `thiscall`, `vectorcall` calling conventions (or their unwind - /// variants) on targets that cannot meaningfully be supported for the requested target. - /// - /// For example `stdcall` does not make much sense for a x86_64 or, more apparently, powerpc - /// code, because this calling convention was never specified for those targets. - /// - /// Historically MSVC toolchains have fallen back to the regular C calling convention for - /// targets other than x86, but Rust doesn't really see a similar need to introduce a similar - /// hack across many more targets. - /// - /// ### Example - /// - /// ```rust,ignore (needs specific targets) - /// extern "stdcall" fn stdcall() {} - /// ``` - /// - /// This will produce: - /// - /// ```text - /// warning: use of calling convention not supported on this target - /// --> $DIR/unsupported.rs:39:1 - /// | - /// LL | extern "stdcall" fn stdcall() {} - /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - /// | - /// = note: `#[warn(unsupported_calling_conventions)]` on by default - /// = warning: this was previously accepted by the compiler but is being phased out; - /// it will become a hard error in a future release! - /// = note: for more information, see issue ... - /// ``` - /// - /// ### Explanation - /// - /// On most of the targets the behaviour of `stdcall` and similar calling conventions is not - /// defined at all, but was previously accepted due to a bug in the implementation of the - /// compiler. - pub UNSUPPORTED_CALLING_CONVENTIONS, - Warn, - "use of unsupported calling convention", - @future_incompatible = FutureIncompatibleInfo { - reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps, - reference: "issue #87678 ", - }; -} - declare_lint! { /// The `unsupported_fn_ptr_calling_conventions` lint is output whenever there is a use of /// a target dependent calling convention on a target that does not support this calling diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index f4b45a081952..24f5646a9ea4 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -2757,10 +2757,9 @@ impl Target { } } - /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted - pub fn is_abi_supported(&self, abi: Abi) -> Option { + pub fn is_abi_supported(&self, abi: Abi) -> bool { use Abi::*; - Some(match abi { + match abi { Rust | C { .. } | System { .. } @@ -2819,9 +2818,9 @@ impl Target { // architectures for which these calling conventions are actually well defined. Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true, Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true, - // Return a `None` for other cases so that we know to emit a future compat lint. - Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None, - }) + // Reject these calling conventions everywhere else. + Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => false, + } } /// Minimum integer size in bits that this target can perform atomic diff --git a/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.fixed b/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.fixed index 41b424a8e5d5..f7b6e1a186bb 100644 --- a/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.fixed +++ b/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.fixed @@ -1,7 +1,7 @@ #![warn(clippy::missing_const_for_fn)] #![allow(incomplete_features, clippy::let_and_return, clippy::missing_transmute_annotations)] -#![allow(unsupported_calling_conventions)] -#![feature(const_trait_impl)] +#![feature(const_trait_impl, abi_vectorcall)] + use std::mem::transmute; @@ -212,8 +212,8 @@ mod extern_fn { //~^ ERROR: this could be a `const fn` const extern "system-unwind" fn system_unwind() {} //~^ ERROR: this could be a `const fn` - pub const extern "stdcall" fn std_call() {} + pub const extern "vectorcall" fn std_call() {} //~^ ERROR: this could be a `const fn` - pub const extern "stdcall-unwind" fn std_call_unwind() {} + pub const extern "vectorcall-unwind" fn std_call_unwind() {} //~^ ERROR: this could be a `const fn` } diff --git a/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.rs b/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.rs index 27593575a013..4866e3210245 100644 --- a/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.rs +++ b/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.rs @@ -1,7 +1,7 @@ #![warn(clippy::missing_const_for_fn)] #![allow(incomplete_features, clippy::let_and_return, clippy::missing_transmute_annotations)] -#![allow(unsupported_calling_conventions)] -#![feature(const_trait_impl)] +#![feature(const_trait_impl, abi_vectorcall)] + use std::mem::transmute; @@ -212,8 +212,8 @@ mod extern_fn { //~^ ERROR: this could be a `const fn` extern "system-unwind" fn system_unwind() {} //~^ ERROR: this could be a `const fn` - pub extern "stdcall" fn std_call() {} + pub extern "vectorcall" fn std_call() {} //~^ ERROR: this could be a `const fn` - pub extern "stdcall-unwind" fn std_call_unwind() {} + pub extern "vectorcall-unwind" fn std_call_unwind() {} //~^ ERROR: this could be a `const fn` } diff --git a/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.stderr b/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.stderr index 12d97b171191..f28dec5c7f19 100644 --- a/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.stderr +++ b/src/tools/clippy/tests/ui/missing_const_for_fn/could_be_const.stderr @@ -319,23 +319,23 @@ LL | const extern "system-unwind" fn system_unwind() {} error: this could be a `const fn` --> tests/ui/missing_const_for_fn/could_be_const.rs:215:5 | -LL | pub extern "stdcall" fn std_call() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern "vectorcall" fn std_call() {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: make the function `const` | -LL | pub const extern "stdcall" fn std_call() {} +LL | pub const extern "vectorcall" fn std_call() {} | +++++ error: this could be a `const fn` --> tests/ui/missing_const_for_fn/could_be_const.rs:217:5 | -LL | pub extern "stdcall-unwind" fn std_call_unwind() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern "vectorcall-unwind" fn std_call_unwind() {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: make the function `const` | -LL | pub const extern "stdcall-unwind" fn std_call_unwind() {} +LL | pub const extern "vectorcall-unwind" fn std_call_unwind() {} | +++++ error: aborting due to 26 previous errors diff --git a/tests/ui/abi/unsupported.aarch64.stderr b/tests/ui/abi/unsupported.aarch64.stderr index 82908ef88a8b..81aa200012fe 100644 --- a/tests/ui/abi/unsupported.aarch64.stderr +++ b/tests/ui/abi/unsupported.aarch64.stderr @@ -105,7 +105,7 @@ LL | extern "thiscall" {} | ^^^^^^^^^^^^^^^^^^^^ warning: the calling convention "stdcall" is not supported on this target - --> $DIR/unsupported.rs:170:19 + --> $DIR/unsupported.rs:165:19 | LL | fn stdcall_ptr(f: extern "stdcall" fn()) { | ^^^^^^^^^^^^^^^^^^^^^ @@ -113,18 +113,14 @@ LL | fn stdcall_ptr(f: extern "stdcall" fn()) { = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #130260 -warning: use of calling convention not supported on this target - --> $DIR/unsupported.rs:183:1 +error[E0570]: `"stdcall"` is not a supported ABI for the current target + --> $DIR/unsupported.rs:178:1 | LL | extern "stdcall" {} | ^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 - = note: `#[warn(unsupported_calling_conventions)]` on by default warning: the calling convention "C-cmse-nonsecure-call" is not supported on this target - --> $DIR/unsupported.rs:195:21 + --> $DIR/unsupported.rs:185:21 | LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +129,7 @@ LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { = note: for more information, see issue #130260 warning: the calling convention "C-cmse-nonsecure-entry" is not supported on this target - --> $DIR/unsupported.rs:203:22 + --> $DIR/unsupported.rs:193:22 | LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -142,7 +138,7 @@ LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { = note: for more information, see issue #130260 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:208:1 + --> $DIR/unsupported.rs:198:1 | LL | extern "C-cmse-nonsecure-entry" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -189,21 +185,18 @@ error[E0570]: `"thiscall"` is not a supported ABI for the current target LL | extern "thiscall" fn thiscall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: use of calling convention not supported on this target +error[E0570]: `"stdcall"` is not a supported ABI for the current target --> $DIR/unsupported.rs:159:1 | LL | extern "stdcall" fn stdcall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:201:1 + --> $DIR/unsupported.rs:191:1 | LL | extern "C-cmse-nonsecure-entry" fn cmse_entry() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 16 previous errors; 12 warnings emitted +error: aborting due to 18 previous errors; 10 warnings emitted For more information about this error, try `rustc --explain E0570`. diff --git a/tests/ui/abi/unsupported.arm.stderr b/tests/ui/abi/unsupported.arm.stderr index 39ec5d16fcd0..8e758ee451f5 100644 --- a/tests/ui/abi/unsupported.arm.stderr +++ b/tests/ui/abi/unsupported.arm.stderr @@ -90,7 +90,7 @@ LL | extern "thiscall" {} | ^^^^^^^^^^^^^^^^^^^^ warning: the calling convention "stdcall" is not supported on this target - --> $DIR/unsupported.rs:170:19 + --> $DIR/unsupported.rs:165:19 | LL | fn stdcall_ptr(f: extern "stdcall" fn()) { | ^^^^^^^^^^^^^^^^^^^^^ @@ -98,18 +98,14 @@ LL | fn stdcall_ptr(f: extern "stdcall" fn()) { = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #130260 -warning: use of calling convention not supported on this target - --> $DIR/unsupported.rs:183:1 +error[E0570]: `"stdcall"` is not a supported ABI for the current target + --> $DIR/unsupported.rs:178:1 | LL | extern "stdcall" {} | ^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 - = note: `#[warn(unsupported_calling_conventions)]` on by default warning: the calling convention "C-cmse-nonsecure-call" is not supported on this target - --> $DIR/unsupported.rs:195:21 + --> $DIR/unsupported.rs:185:21 | LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -118,7 +114,7 @@ LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { = note: for more information, see issue #130260 warning: the calling convention "C-cmse-nonsecure-entry" is not supported on this target - --> $DIR/unsupported.rs:203:22 + --> $DIR/unsupported.rs:193:22 | LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,7 +123,7 @@ LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { = note: for more information, see issue #130260 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:208:1 + --> $DIR/unsupported.rs:198:1 | LL | extern "C-cmse-nonsecure-entry" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -168,21 +164,18 @@ error[E0570]: `"thiscall"` is not a supported ABI for the current target LL | extern "thiscall" fn thiscall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: use of calling convention not supported on this target +error[E0570]: `"stdcall"` is not a supported ABI for the current target --> $DIR/unsupported.rs:159:1 | LL | extern "stdcall" fn stdcall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:201:1 + --> $DIR/unsupported.rs:191:1 | LL | extern "C-cmse-nonsecure-entry" fn cmse_entry() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 14 previous errors; 11 warnings emitted +error: aborting due to 16 previous errors; 9 warnings emitted For more information about this error, try `rustc --explain E0570`. diff --git a/tests/ui/abi/unsupported.i686.stderr b/tests/ui/abi/unsupported.i686.stderr index 1dc01a66aabc..b3c74ad63537 100644 --- a/tests/ui/abi/unsupported.i686.stderr +++ b/tests/ui/abi/unsupported.i686.stderr @@ -75,7 +75,7 @@ LL | extern "riscv-interrupt-m" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: the calling convention "C-cmse-nonsecure-call" is not supported on this target - --> $DIR/unsupported.rs:195:21 + --> $DIR/unsupported.rs:185:21 | LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -84,7 +84,7 @@ LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { = note: for more information, see issue #130260 warning: the calling convention "C-cmse-nonsecure-entry" is not supported on this target - --> $DIR/unsupported.rs:203:22 + --> $DIR/unsupported.rs:193:22 | LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -93,7 +93,7 @@ LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { = note: for more information, see issue #130260 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:208:1 + --> $DIR/unsupported.rs:198:1 | LL | extern "C-cmse-nonsecure-entry" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -129,7 +129,7 @@ LL | extern "riscv-interrupt-m" fn riscv() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:201:1 + --> $DIR/unsupported.rs:191:1 | LL | extern "C-cmse-nonsecure-entry" fn cmse_entry() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/abi/unsupported.riscv32.stderr b/tests/ui/abi/unsupported.riscv32.stderr index e7d5197feebb..92728b1df18c 100644 --- a/tests/ui/abi/unsupported.riscv32.stderr +++ b/tests/ui/abi/unsupported.riscv32.stderr @@ -90,7 +90,7 @@ LL | extern "thiscall" {} | ^^^^^^^^^^^^^^^^^^^^ warning: the calling convention "stdcall" is not supported on this target - --> $DIR/unsupported.rs:170:19 + --> $DIR/unsupported.rs:165:19 | LL | fn stdcall_ptr(f: extern "stdcall" fn()) { | ^^^^^^^^^^^^^^^^^^^^^ @@ -98,18 +98,14 @@ LL | fn stdcall_ptr(f: extern "stdcall" fn()) { = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #130260 -warning: use of calling convention not supported on this target - --> $DIR/unsupported.rs:183:1 +error[E0570]: `"stdcall"` is not a supported ABI for the current target + --> $DIR/unsupported.rs:178:1 | LL | extern "stdcall" {} | ^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 - = note: `#[warn(unsupported_calling_conventions)]` on by default warning: the calling convention "C-cmse-nonsecure-call" is not supported on this target - --> $DIR/unsupported.rs:195:21 + --> $DIR/unsupported.rs:185:21 | LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -118,7 +114,7 @@ LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { = note: for more information, see issue #130260 warning: the calling convention "C-cmse-nonsecure-entry" is not supported on this target - --> $DIR/unsupported.rs:203:22 + --> $DIR/unsupported.rs:193:22 | LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,7 +123,7 @@ LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { = note: for more information, see issue #130260 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:208:1 + --> $DIR/unsupported.rs:198:1 | LL | extern "C-cmse-nonsecure-entry" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -168,21 +164,18 @@ error[E0570]: `"thiscall"` is not a supported ABI for the current target LL | extern "thiscall" fn thiscall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: use of calling convention not supported on this target +error[E0570]: `"stdcall"` is not a supported ABI for the current target --> $DIR/unsupported.rs:159:1 | LL | extern "stdcall" fn stdcall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:201:1 + --> $DIR/unsupported.rs:191:1 | LL | extern "C-cmse-nonsecure-entry" fn cmse_entry() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 14 previous errors; 11 warnings emitted +error: aborting due to 16 previous errors; 9 warnings emitted For more information about this error, try `rustc --explain E0570`. diff --git a/tests/ui/abi/unsupported.riscv64.stderr b/tests/ui/abi/unsupported.riscv64.stderr index e7d5197feebb..92728b1df18c 100644 --- a/tests/ui/abi/unsupported.riscv64.stderr +++ b/tests/ui/abi/unsupported.riscv64.stderr @@ -90,7 +90,7 @@ LL | extern "thiscall" {} | ^^^^^^^^^^^^^^^^^^^^ warning: the calling convention "stdcall" is not supported on this target - --> $DIR/unsupported.rs:170:19 + --> $DIR/unsupported.rs:165:19 | LL | fn stdcall_ptr(f: extern "stdcall" fn()) { | ^^^^^^^^^^^^^^^^^^^^^ @@ -98,18 +98,14 @@ LL | fn stdcall_ptr(f: extern "stdcall" fn()) { = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #130260 -warning: use of calling convention not supported on this target - --> $DIR/unsupported.rs:183:1 +error[E0570]: `"stdcall"` is not a supported ABI for the current target + --> $DIR/unsupported.rs:178:1 | LL | extern "stdcall" {} | ^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 - = note: `#[warn(unsupported_calling_conventions)]` on by default warning: the calling convention "C-cmse-nonsecure-call" is not supported on this target - --> $DIR/unsupported.rs:195:21 + --> $DIR/unsupported.rs:185:21 | LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -118,7 +114,7 @@ LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { = note: for more information, see issue #130260 warning: the calling convention "C-cmse-nonsecure-entry" is not supported on this target - --> $DIR/unsupported.rs:203:22 + --> $DIR/unsupported.rs:193:22 | LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,7 +123,7 @@ LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { = note: for more information, see issue #130260 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:208:1 + --> $DIR/unsupported.rs:198:1 | LL | extern "C-cmse-nonsecure-entry" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -168,21 +164,18 @@ error[E0570]: `"thiscall"` is not a supported ABI for the current target LL | extern "thiscall" fn thiscall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: use of calling convention not supported on this target +error[E0570]: `"stdcall"` is not a supported ABI for the current target --> $DIR/unsupported.rs:159:1 | LL | extern "stdcall" fn stdcall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:201:1 + --> $DIR/unsupported.rs:191:1 | LL | extern "C-cmse-nonsecure-entry" fn cmse_entry() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 14 previous errors; 11 warnings emitted +error: aborting due to 16 previous errors; 9 warnings emitted For more information about this error, try `rustc --explain E0570`. diff --git a/tests/ui/abi/unsupported.rs b/tests/ui/abi/unsupported.rs index 0eb039269a3e..a56f001ef952 100644 --- a/tests/ui/abi/unsupported.rs +++ b/tests/ui/abi/unsupported.rs @@ -157,16 +157,11 @@ extern "thiscall" {} //[riscv64]~^^^^^ ERROR is not a supported ABI extern "stdcall" fn stdcall() {} -//[x64]~^ WARN use of calling convention not supported -//[x64]~^^ WARN this was previously accepted -//[arm]~^^^ WARN use of calling convention not supported -//[arm]~^^^^ WARN this was previously accepted -//[aarch64]~^^^^^ WARN use of calling convention not supported -//[aarch64]~^^^^^^ WARN this was previously accepted -//[riscv32]~^^^^^^^ WARN use of calling convention not supported -//[riscv32]~^^^^^^^^ WARN this was previously accepted -//[riscv64]~^^^^^^^^^ WARN use of calling convention not supported -//[riscv64]~^^^^^^^^^^ WARN this was previously accepted +//[x64]~^ ERROR is not a supported ABI +//[arm]~^^ ERROR is not a supported ABI +//[aarch64]~^^^ ERROR is not a supported ABI +//[riscv32]~^^^^ ERROR is not a supported ABI +//[riscv64]~^^^^^ ERROR is not a supported ABI fn stdcall_ptr(f: extern "stdcall" fn()) { //[x64]~^ WARN unsupported_fn_ptr_calling_conventions //[x64]~^^ WARN this was previously accepted @@ -181,16 +176,11 @@ fn stdcall_ptr(f: extern "stdcall" fn()) { f() } extern "stdcall" {} -//[x64]~^ WARN use of calling convention not supported -//[x64]~^^ WARN this was previously accepted -//[arm]~^^^ WARN use of calling convention not supported -//[arm]~^^^^ WARN this was previously accepted -//[aarch64]~^^^^^ WARN use of calling convention not supported -//[aarch64]~^^^^^^ WARN this was previously accepted -//[riscv32]~^^^^^^^ WARN use of calling convention not supported -//[riscv32]~^^^^^^^^ WARN this was previously accepted -//[riscv64]~^^^^^^^^^ WARN use of calling convention not supported -//[riscv64]~^^^^^^^^^^ WARN this was previously accepted +//[x64]~^ ERROR is not a supported ABI +//[arm]~^^ ERROR is not a supported ABI +//[aarch64]~^^^ ERROR is not a supported ABI +//[riscv32]~^^^^ ERROR is not a supported ABI +//[riscv64]~^^^^^ ERROR is not a supported ABI fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { //~^ WARN unsupported_fn_ptr_calling_conventions diff --git a/tests/ui/abi/unsupported.x64.stderr b/tests/ui/abi/unsupported.x64.stderr index bbca754dd41f..27a4f1f532c6 100644 --- a/tests/ui/abi/unsupported.x64.stderr +++ b/tests/ui/abi/unsupported.x64.stderr @@ -90,7 +90,7 @@ LL | extern "thiscall" {} | ^^^^^^^^^^^^^^^^^^^^ warning: the calling convention "stdcall" is not supported on this target - --> $DIR/unsupported.rs:170:19 + --> $DIR/unsupported.rs:165:19 | LL | fn stdcall_ptr(f: extern "stdcall" fn()) { | ^^^^^^^^^^^^^^^^^^^^^ @@ -98,18 +98,14 @@ LL | fn stdcall_ptr(f: extern "stdcall" fn()) { = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #130260 -warning: use of calling convention not supported on this target - --> $DIR/unsupported.rs:183:1 +error[E0570]: `"stdcall"` is not a supported ABI for the current target + --> $DIR/unsupported.rs:178:1 | LL | extern "stdcall" {} | ^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 - = note: `#[warn(unsupported_calling_conventions)]` on by default warning: the calling convention "C-cmse-nonsecure-call" is not supported on this target - --> $DIR/unsupported.rs:195:21 + --> $DIR/unsupported.rs:185:21 | LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -118,7 +114,7 @@ LL | fn cmse_call_ptr(f: extern "C-cmse-nonsecure-call" fn()) { = note: for more information, see issue #130260 warning: the calling convention "C-cmse-nonsecure-entry" is not supported on this target - --> $DIR/unsupported.rs:203:22 + --> $DIR/unsupported.rs:193:22 | LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,7 +123,7 @@ LL | fn cmse_entry_ptr(f: extern "C-cmse-nonsecure-entry" fn()) { = note: for more information, see issue #130260 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:208:1 + --> $DIR/unsupported.rs:198:1 | LL | extern "C-cmse-nonsecure-entry" {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -168,21 +164,18 @@ error[E0570]: `"thiscall"` is not a supported ABI for the current target LL | extern "thiscall" fn thiscall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: use of calling convention not supported on this target +error[E0570]: `"stdcall"` is not a supported ABI for the current target --> $DIR/unsupported.rs:159:1 | LL | extern "stdcall" fn stdcall() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #87678 error[E0570]: `"C-cmse-nonsecure-entry"` is not a supported ABI for the current target - --> $DIR/unsupported.rs:201:1 + --> $DIR/unsupported.rs:191:1 | LL | extern "C-cmse-nonsecure-entry" fn cmse_entry() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 14 previous errors; 11 warnings emitted +error: aborting due to 16 previous errors; 9 warnings emitted For more information about this error, try `rustc --explain E0570`. From 3bbf1b257f4905ab2f5ca157c35b8f8ca22fecab Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 20 Oct 2024 18:50:05 +0300 Subject: [PATCH 059/366] Update Cargo.lock --- src/tools/rust-analyzer/Cargo.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index a99294033b44..da65d8804949 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -731,7 +731,7 @@ dependencies = [ "indexmap", "itertools", "limit", - "line-index 0.1.1", + "line-index 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "memchr", "nohash-hasher", "parser", @@ -939,20 +939,20 @@ version = "0.0.0" [[package]] name = "line-index" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67d61795376ae2683928c218fda7d7d7db136fd38c06b7552904667f0d55580a" +version = "0.1.2" dependencies = [ "nohash-hasher", + "oorandom", "text-size", ] [[package]] name = "line-index" version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e27e0ed5a392a7f5ba0b3808a2afccff16c64933312c84b57618b49d1209bd2" dependencies = [ "nohash-hasher", - "oorandom", "text-size", ] From 46cc5e9e962fda2f99d4956ef539bf4b79fead26 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Fri, 18 Oct 2024 16:47:19 +0200 Subject: [PATCH 060/366] elaborate why dropping principal in `*dyn` casts is non-trivial --- compiler/rustc_hir_typeck/src/cast.rs | 31 +++++++++++++++++-- .../cast/ptr-to-trait-obj-drop-principal.rs | 21 +++++++++++++ .../ptr-to-trait-obj-drop-principal.stderr | 11 +++++++ 3 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 tests/ui/cast/ptr-to-trait-obj-drop-principal.rs create mode 100644 tests/ui/cast/ptr-to-trait-obj-drop-principal.stderr diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 7341d3fa3c4e..86af6c97af57 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -959,8 +959,35 @@ impl<'a, 'tcx> CastCheck<'tcx> { // dyn Auto -> dyn Auto'? ok. (None, None) => Ok(CastKind::PtrPtrCast), - // dyn Trait -> dyn Auto? should be ok, but we used to not allow it. - // FIXME: allow this + // dyn Trait -> dyn Auto? not ok (for now). + // + // Although dropping the principal is already allowed for unsizing coercions + // (e.g. `*const (dyn Trait + Auto)` to `*const dyn Auto`), dropping it is + // currently **NOT** allowed for (non-coercion) ptr-to-ptr casts (e.g + // `*const Foo` to `*const Bar` where `Foo` has a `dyn Trait + Auto` tail + // and `Bar` has a `dyn Auto` tail), because the underlying MIR operations + // currently work very differently: + // + // * A MIR unsizing coercion on raw pointers to trait objects (`*const dyn Src` + // to `*const dyn Dst`) is currently equivalent to downcasting the source to + // the concrete sized type that it was originally unsized from first (via a + // ptr-to-ptr cast from `*const Src` to `*const T` with `T: Sized`) and then + // unsizing this thin pointer to the target type (unsizing `*const T` to + // `*const Dst`). In particular, this means that the pointer's metadata + // (vtable) will semantically change, e.g. for const eval and miri, even + // though the vtables will always be merged for codegen. + // + // * A MIR ptr-to-ptr cast is currently equivalent to a transmute and does not + // change the pointer metadata (vtable) at all. + // + // In addition to this potentially surprising difference between coercion and + // non-coercion casts, casting away the principal with a MIR ptr-to-ptr cast + // is currently considered undefined behavior: + // + // As a validity invariant of pointers to trait objects, we currently require + // that the principal of the vtable in the pointer metadata exactly matches + // the principal of the pointee type, where "no principal" is also considered + // a kind of principal. (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }), // dyn Auto -> dyn Trait? not ok. diff --git a/tests/ui/cast/ptr-to-trait-obj-drop-principal.rs b/tests/ui/cast/ptr-to-trait-obj-drop-principal.rs new file mode 100644 index 000000000000..01dd91fc77dd --- /dev/null +++ b/tests/ui/cast/ptr-to-trait-obj-drop-principal.rs @@ -0,0 +1,21 @@ +//! Test that non-coercion casts aren't allowed to drop the principal, +//! because they cannot modify the pointer metadata. +//! +//! We test this in a const context to guard against UB if this is allowed +//! in the future. + +trait Trait {} +impl Trait for () {} + +struct Wrapper(T); + +const OBJECT: *const (dyn Trait + Send) = &(); + +// coercions are allowed +const _: *const dyn Send = OBJECT as _; + +// casts are **not** allowed +const _: *const Wrapper = OBJECT as _; +//~^ ERROR casting `*const (dyn Trait + Send + 'static)` as `*const Wrapper` is invalid + +fn main() {} diff --git a/tests/ui/cast/ptr-to-trait-obj-drop-principal.stderr b/tests/ui/cast/ptr-to-trait-obj-drop-principal.stderr new file mode 100644 index 000000000000..719e0711f5b9 --- /dev/null +++ b/tests/ui/cast/ptr-to-trait-obj-drop-principal.stderr @@ -0,0 +1,11 @@ +error[E0606]: casting `*const (dyn Trait + Send + 'static)` as `*const Wrapper` is invalid + --> $DIR/ptr-to-trait-obj-drop-principal.rs:18:37 + | +LL | const _: *const Wrapper = OBJECT as _; + | ^^^^^^^^^^^ + | + = note: the trait objects may have different vtables + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0606`. From bac672c04be96b4cdda580a61730dc778acb0973 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 29 Sep 2024 23:20:04 +0300 Subject: [PATCH 061/366] Remove now-incorrect code Because our lint infra *can* handle allows from within macro expansions! (Also, what did this reason have to do with something that is a hard error and not a lint? I'm puzzled). I wonder how many such diagnostics we have... Maybe that also mean we can change `unused_mut` to no-longer-experimental? But this is a change I'm afraid to do without checking. --- .../ide-diagnostics/src/handlers/mutability_errors.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs index 6fa0e7a5a896..b982d1041fe3 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -8,10 +8,6 @@ use crate::{fix, Diagnostic, DiagnosticCode, DiagnosticsContext}; // // This diagnostic is triggered on mutating an immutable variable. pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Option { - if d.span.file_id.macro_file().is_some() { - // FIXME: Our infra can't handle allow from within macro expansions rn - return None; - } let fixes = (|| { if d.local.is_ref(ctx.sema.db) { // There is no simple way to add `mut` to `ref x` and `ref mut x` @@ -53,10 +49,6 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Option // This diagnostic is triggered when a mutable variable isn't actually mutated. pub(crate) fn unused_mut(ctx: &DiagnosticsContext<'_>, d: &hir::UnusedMut) -> Option { let ast = d.local.primary_source(ctx.sema.db).syntax_ptr(); - if ast.file_id.macro_file().is_some() { - // FIXME: Our infra can't handle allow from within macro expansions rn - return None; - } let fixes = (|| { let file_id = ast.file_id.file_id()?; let mut edit_builder = TextEdit::builder(); From b4f040331fbc524ee2180aaa33f4fb889ed2d988 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 6 Oct 2024 18:14:07 +0300 Subject: [PATCH 062/366] Handle destructuring assignments uniformly Instead of lowering them to ` = `, then hacking on-demand to resolve them, we lower them to ` = `, and use the pattern infrastructure to handle them. It turns out, destructuring assignments are surprisingly similar to pattern bindings, and so only minor modifications are needed. This fixes few bugs that arose because of the non-uniform handling (for example, MIR lowering not handling slice and record patterns, and closure capture calculation not handling destructuring assignments at all), and furthermore, guarantees we won't have such bugs in the future, since the programmer will always have to explicitly handle `Expr::Assignment`. Tests don't pass yet; that's because the generated patterns do not exist in the source map. The next commit will fix that. --- .../rust-analyzer/crates/hir-def/src/body.rs | 143 +++++++- .../crates/hir-def/src/body/lower.rs | 313 ++++++++++++------ .../crates/hir-def/src/body/pretty.rs | 21 +- .../crates/hir-def/src/body/scope.rs | 2 +- .../rust-analyzer/crates/hir-def/src/hir.rs | 187 +++-------- .../crates/hir-ty/src/consteval.rs | 2 +- .../crates/hir-ty/src/diagnostics/expr.rs | 5 +- .../hir-ty/src/diagnostics/unsafe_check.rs | 4 +- .../rust-analyzer/crates/hir-ty/src/infer.rs | 6 +- .../crates/hir-ty/src/infer/closure.rs | 102 ++++-- .../crates/hir-ty/src/infer/expr.rs | 224 ++++--------- .../crates/hir-ty/src/infer/mutability.rs | 27 +- .../crates/hir-ty/src/infer/pat.rs | 169 ++++++---- .../crates/hir-ty/src/mir/lower.rs | 240 ++++++-------- .../crates/hir-ty/src/mir/lower/as_place.rs | 9 +- .../hir-ty/src/mir/lower/pattern_matching.rs | 96 ++++-- .../crates/hir/src/diagnostics.rs | 22 +- .../src/handlers/mutability_errors.rs | 15 + .../src/handlers/unresolved_ident.rs | 2 +- .../crates/syntax/src/ast/expr_ext.rs | 4 + 20 files changed, 886 insertions(+), 707 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body.rs b/src/tools/rust-analyzer/crates/hir-def/src/body.rs index 9535b5aea7c7..d843ac1cad24 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body.rs @@ -22,7 +22,8 @@ use crate::{ db::DefDatabase, expander::Expander, hir::{ - dummy_expr_id, Binding, BindingId, Expr, ExprId, Label, LabelId, Pat, PatId, RecordFieldPat, + dummy_expr_id, Array, AsmOperand, Binding, BindingId, Expr, ExprId, Label, LabelId, Pat, + PatId, RecordFieldPat, Statement, }, item_tree::AttrOwner, nameres::DefMap, @@ -286,7 +287,8 @@ impl Body { | Pat::Path(..) | Pat::ConstBlock(..) | Pat::Wild - | Pat::Missing => {} + | Pat::Missing + | Pat::Expr(_) => {} &Pat::Bind { subpat, .. } => { if let Some(subpat) = subpat { f(subpat); @@ -322,6 +324,143 @@ impl Body { None => true, } } + + pub fn walk_child_exprs(&self, expr_id: ExprId, mut f: impl FnMut(ExprId)) { + let expr = &self[expr_id]; + match expr { + Expr::Continue { .. } + | Expr::Const(_) + | Expr::Missing + | Expr::Path(_) + | Expr::OffsetOf(_) + | Expr::Literal(_) + | Expr::Underscore => {} + Expr::InlineAsm(it) => it.operands.iter().for_each(|(_, op)| match op { + AsmOperand::In { expr, .. } + | AsmOperand::Out { expr: Some(expr), .. } + | AsmOperand::InOut { expr, .. } => f(*expr), + AsmOperand::SplitInOut { in_expr, out_expr, .. } => { + f(*in_expr); + if let Some(out_expr) = out_expr { + f(*out_expr); + } + } + AsmOperand::Out { expr: None, .. } + | AsmOperand::Const(_) + | AsmOperand::Label(_) + | AsmOperand::Sym(_) => (), + }), + Expr::If { condition, then_branch, else_branch } => { + f(*condition); + f(*then_branch); + if let &Some(else_branch) = else_branch { + f(else_branch); + } + } + Expr::Let { expr, .. } => { + f(*expr); + } + Expr::Block { statements, tail, .. } + | Expr::Unsafe { statements, tail, .. } + | Expr::Async { statements, tail, .. } => { + for stmt in statements.iter() { + match stmt { + Statement::Let { initializer, else_branch, pat, .. } => { + if let &Some(expr) = initializer { + f(expr); + } + if let &Some(expr) = else_branch { + f(expr); + } + walk_exprs_in_pat(self, *pat, &mut f); + } + Statement::Expr { expr: expression, .. } => f(*expression), + Statement::Item => (), + } + } + if let &Some(expr) = tail { + f(expr); + } + } + Expr::Loop { body, .. } => f(*body), + Expr::Call { callee, args, .. } => { + f(*callee); + args.iter().copied().for_each(f); + } + Expr::MethodCall { receiver, args, .. } => { + f(*receiver); + args.iter().copied().for_each(f); + } + Expr::Match { expr, arms } => { + f(*expr); + arms.iter().map(|arm| arm.expr).for_each(f); + } + Expr::Break { expr, .. } + | Expr::Return { expr } + | Expr::Yield { expr } + | Expr::Yeet { expr } => { + if let &Some(expr) = expr { + f(expr); + } + } + Expr::Become { expr } => f(*expr), + Expr::RecordLit { fields, spread, .. } => { + for field in fields.iter() { + f(field.expr); + } + if let &Some(expr) = spread { + f(expr); + } + } + Expr::Closure { body, .. } => { + f(*body); + } + Expr::BinaryOp { lhs, rhs, .. } => { + f(*lhs); + f(*rhs); + } + Expr::Range { lhs, rhs, .. } => { + if let &Some(lhs) = rhs { + f(lhs); + } + if let &Some(rhs) = lhs { + f(rhs); + } + } + Expr::Index { base, index, .. } => { + f(*base); + f(*index); + } + Expr::Field { expr, .. } + | Expr::Await { expr } + | Expr::Cast { expr, .. } + | Expr::Ref { expr, .. } + | Expr::UnaryOp { expr, .. } + | Expr::Box { expr } => { + f(*expr); + } + Expr::Tuple { exprs, .. } => exprs.iter().copied().for_each(f), + Expr::Array(a) => match a { + Array::ElementList { elements, .. } => elements.iter().copied().for_each(f), + Array::Repeat { initializer, repeat } => { + f(*initializer); + f(*repeat) + } + }, + &Expr::Assignment { target, value } => { + walk_exprs_in_pat(self, target, &mut f); + f(value); + } + } + + fn walk_exprs_in_pat(this: &Body, pat_id: PatId, f: &mut impl FnMut(ExprId)) { + this.walk_pats(pat_id, &mut |pat| { + if let Pat::Expr(expr) | Pat::ConstBlock(expr) = this[pat] { + f(expr); + } + }); + } + } } impl Default for Body { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index 9c547574ecb1..3dff6ecd756c 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -70,7 +70,6 @@ pub(super) fn lower( body: Body::default(), expander, current_try_block_label: None, - is_lowering_assignee_expr: false, is_lowering_coroutine: false, label_ribs: Vec::new(), current_binding_owner: None, @@ -89,7 +88,6 @@ struct ExprCollector<'a> { body: Body, source_map: BodySourceMap, - is_lowering_assignee_expr: bool, is_lowering_coroutine: bool, current_try_block_label: Option, @@ -359,14 +357,7 @@ impl ExprCollector<'_> { } else { Box::default() }; - self.alloc_expr( - Expr::Call { - callee, - args, - is_assignee_expr: self.is_lowering_assignee_expr, - }, - syntax_ptr, - ) + self.alloc_expr(Expr::Call { callee, args }, syntax_ptr) } } ast::Expr::MethodCallExpr(e) => { @@ -457,7 +448,6 @@ impl ExprCollector<'_> { ast::Expr::RecordExpr(e) => { let path = e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); - let is_assignee_expr = self.is_lowering_assignee_expr; let record_lit = if let Some(nfl) = e.record_expr_field_list() { let fields = nfl .fields() @@ -476,16 +466,9 @@ impl ExprCollector<'_> { }) .collect(); let spread = nfl.spread().map(|s| self.collect_expr(s)); - let ellipsis = nfl.dotdot_token().is_some(); - Expr::RecordLit { path, fields, spread, ellipsis, is_assignee_expr } + Expr::RecordLit { path, fields, spread } } else { - Expr::RecordLit { - path, - fields: Box::default(), - spread: None, - ellipsis: false, - is_assignee_expr, - } + Expr::RecordLit { path, fields: Box::default(), spread: None } }; self.alloc_expr(record_lit, syntax_ptr) @@ -602,12 +585,14 @@ impl ExprCollector<'_> { ast::Expr::BinExpr(e) => { let op = e.op_kind(); if let Some(ast::BinaryOp::Assignment { op: None }) = op { - self.is_lowering_assignee_expr = true; + let target = self.collect_expr_as_pat_opt(e.lhs()); + let value = self.collect_expr_opt(e.rhs()); + self.alloc_expr(Expr::Assignment { target, value }, syntax_ptr) + } else { + let lhs = self.collect_expr_opt(e.lhs()); + let rhs = self.collect_expr_opt(e.rhs()); + self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr) } - let lhs = self.collect_expr_opt(e.lhs()); - self.is_lowering_assignee_expr = false; - let rhs = self.collect_expr_opt(e.rhs()); - self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr) } ast::Expr::TupleExpr(e) => { let mut exprs: Vec<_> = e.fields().map(|expr| self.collect_expr(expr)).collect(); @@ -617,13 +602,7 @@ impl ExprCollector<'_> { exprs.insert(0, self.missing_expr()); } - self.alloc_expr( - Expr::Tuple { - exprs: exprs.into_boxed_slice(), - is_assignee_expr: self.is_lowering_assignee_expr, - }, - syntax_ptr, - ) + self.alloc_expr(Expr::Tuple { exprs: exprs.into_boxed_slice() }, syntax_ptr) } ast::Expr::ArrayExpr(e) => { let kind = e.kind(); @@ -631,13 +610,7 @@ impl ExprCollector<'_> { match kind { ArrayExprKind::ElementList(e) => { let elements = e.map(|expr| self.collect_expr(expr)).collect(); - self.alloc_expr( - Expr::Array(Array::ElementList { - elements, - is_assignee_expr: self.is_lowering_assignee_expr, - }), - syntax_ptr, - ) + self.alloc_expr(Expr::Array(Array::ElementList { elements }), syntax_ptr) } ArrayExprKind::Repeat { initializer, repeat } => { let initializer = self.collect_expr_opt(initializer); @@ -664,8 +637,7 @@ impl ExprCollector<'_> { ast::Expr::IndexExpr(e) => { let base = self.collect_expr_opt(e.base()); let index = self.collect_expr_opt(e.index()); - let is_assignee_expr = self.is_lowering_assignee_expr; - self.alloc_expr(Expr::Index { base, index, is_assignee_expr }, syntax_ptr) + self.alloc_expr(Expr::Index { base, index }, syntax_ptr) } ast::Expr::RangeExpr(e) => { let lhs = e.start().map(|lhs| self.collect_expr(lhs)); @@ -705,6 +677,178 @@ impl ExprCollector<'_> { }) } + fn collect_expr_as_pat_opt(&mut self, expr: Option) -> PatId { + match expr { + Some(expr) => self.collect_expr_as_pat(expr), + _ => self.missing_pat(), + } + } + + fn collect_expr_as_pat(&mut self, expr: ast::Expr) -> PatId { + self.maybe_collect_expr_as_pat(&expr).unwrap_or_else(|| { + let syntax_ptr = AstPtr::new(&expr); + let expr = self.collect_expr(expr); + self.alloc_pat_from_expr(Pat::Expr(expr), syntax_ptr) + }) + } + + fn maybe_collect_expr_as_pat(&mut self, expr: &ast::Expr) -> Option { + self.check_cfg(expr)?; + let syntax_ptr = AstPtr::new(expr); + + let result = match expr { + ast::Expr::UnderscoreExpr(_) => self.alloc_pat_from_expr(Pat::Wild, syntax_ptr), + ast::Expr::ParenExpr(e) => { + // We special-case `(..)` for consistency with patterns. + if let Some(ast::Expr::RangeExpr(range)) = e.expr() { + if range.is_range_full() { + return Some(self.alloc_pat_from_expr( + Pat::Tuple { args: Box::default(), ellipsis: Some(0) }, + syntax_ptr, + )); + } + } + return e.expr().and_then(|expr| self.maybe_collect_expr_as_pat(&expr)); + } + ast::Expr::TupleExpr(e) => { + let (ellipsis, args) = collect_tuple(self, e.fields()); + self.alloc_pat_from_expr(Pat::Tuple { args, ellipsis }, syntax_ptr) + } + ast::Expr::ArrayExpr(e) => { + if e.semicolon_token().is_some() { + return None; + } + + let mut elements = e.exprs(); + let prefix = elements + .by_ref() + .map_while(|elem| collect_possibly_rest(self, elem).left()) + .collect(); + let suffix = elements.map(|elem| self.collect_expr_as_pat(elem)).collect(); + self.alloc_pat_from_expr(Pat::Slice { prefix, slice: None, suffix }, syntax_ptr) + } + ast::Expr::CallExpr(e) => { + let path = collect_path(self, e.expr()?)?; + let path = path + .path() + .and_then(|path| self.expander.parse_path(self.db, path)) + .map(Box::new); + let (ellipsis, args) = collect_tuple(self, e.arg_list()?.args()); + self.alloc_pat_from_expr(Pat::TupleStruct { path, args, ellipsis }, syntax_ptr) + } + ast::Expr::PathExpr(e) => { + let path = Box::new(self.expander.parse_path(self.db, e.path()?)?); + self.alloc_pat_from_expr(Pat::Path(path), syntax_ptr) + } + ast::Expr::MacroExpr(e) => { + let e = e.macro_call()?; + let macro_ptr = AstPtr::new(&e); + let id = self.collect_macro_call(e, macro_ptr, true, |this, expansion| { + expansion.map(|it| this.collect_expr_as_pat(it)) + }); + match id { + Some(id) => { + // FIXME: Insert pat into source map. + id + } + None => self.alloc_pat_from_expr(Pat::Missing, syntax_ptr), + } + } + ast::Expr::RecordExpr(e) => { + let path = + e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); + let record_field_list = e.record_expr_field_list()?; + let ellipsis = record_field_list.dotdot_token().is_some(); + // FIXME: Report an error here if `record_field_list.spread().is_some()`. + let args = record_field_list + .fields() + .filter_map(|f| { + self.check_cfg(&f)?; + let field_expr = f.expr()?; + let pat = self.collect_expr_as_pat(field_expr); + let name = f.field_name()?.as_name(); + // FIXME: Enable this. + // let src = self.expander.in_file(AstPtr::new(&f)); + // self.source_map.pat_field_map_back.insert(pat, src); + Some(RecordFieldPat { name, pat }) + }) + .collect(); + self.alloc_pat_from_expr(Pat::Record { path, args, ellipsis }, syntax_ptr) + } + _ => return None, + }; + return Some(result); + + fn collect_path(this: &mut ExprCollector<'_>, expr: ast::Expr) -> Option { + match expr { + ast::Expr::PathExpr(e) => Some(e), + ast::Expr::MacroExpr(mac) => { + let call = mac.macro_call()?; + { + let macro_ptr = AstPtr::new(&call); + this.collect_macro_call(call, macro_ptr, true, |this, expanded_path| { + collect_path(this, expanded_path?) + }) + } + } + _ => None, + } + } + + fn collect_possibly_rest( + this: &mut ExprCollector<'_>, + expr: ast::Expr, + ) -> Either { + match &expr { + ast::Expr::RangeExpr(e) if e.is_range_full() => Either::Right(()), + ast::Expr::MacroExpr(mac) => match mac.macro_call() { + Some(call) => { + let macro_ptr = AstPtr::new(&call); + let pat = this.collect_macro_call( + call, + macro_ptr, + true, + |this, expanded_expr| match expanded_expr { + Some(expanded_pat) => collect_possibly_rest(this, expanded_pat), + None => Either::Left(this.missing_pat()), + }, + ); + // FIXME: Insert pat into source map. + pat + } + None => { + let ptr = AstPtr::new(&expr); + Either::Left(this.alloc_pat_from_expr(Pat::Missing, ptr)) + } + }, + _ => Either::Left(this.collect_expr_as_pat(expr)), + } + } + + fn collect_tuple( + this: &mut ExprCollector<'_>, + fields: ast::AstChildren, + ) -> (Option, Box<[la_arena::Idx]>) { + let mut ellipsis = None; + let args = fields + .enumerate() + .filter_map(|(idx, elem)| { + match collect_possibly_rest(this, elem) { + Either::Left(pat) => Some(pat), + Either::Right(()) => { + if ellipsis.is_none() { + ellipsis = Some(idx as u32); + } + // FIXME: Report an error here otherwise. + None + } + } + }) + .collect(); + (ellipsis, args) + } + } + fn initialize_binding_owner( &mut self, syntax_ptr: AstPtr, @@ -755,17 +899,13 @@ impl ExprCollector<'_> { let callee = self.alloc_expr_desugared_with_ptr(Expr::Path(try_from_output), ptr); let next_tail = match btail { - Some(tail) => self.alloc_expr_desugared_with_ptr( - Expr::Call { callee, args: Box::new([tail]), is_assignee_expr: false }, - ptr, - ), + Some(tail) => self + .alloc_expr_desugared_with_ptr(Expr::Call { callee, args: Box::new([tail]) }, ptr), None => { - let unit = self.alloc_expr_desugared_with_ptr( - Expr::Tuple { exprs: Box::new([]), is_assignee_expr: false }, - ptr, - ); + let unit = + self.alloc_expr_desugared_with_ptr(Expr::Tuple { exprs: Box::new([]) }, ptr); self.alloc_expr_desugared_with_ptr( - Expr::Call { callee, args: Box::new([unit]), is_assignee_expr: false }, + Expr::Call { callee, args: Box::new([unit]) }, ptr, ) } @@ -851,11 +991,7 @@ impl ExprCollector<'_> { let head = self.collect_expr_opt(e.iterable()); let into_iter_fn_expr = self.alloc_expr(Expr::Path(into_iter_fn), syntax_ptr); let iterator = self.alloc_expr( - Expr::Call { - callee: into_iter_fn_expr, - args: Box::new([head]), - is_assignee_expr: false, - }, + Expr::Call { callee: into_iter_fn_expr, args: Box::new([head]) }, syntax_ptr, ); let none_arm = MatchArm { @@ -884,11 +1020,7 @@ impl ExprCollector<'_> { ); let iter_next_fn_expr = self.alloc_expr(Expr::Path(iter_next_fn), syntax_ptr); let iter_next_expr = self.alloc_expr( - Expr::Call { - callee: iter_next_fn_expr, - args: Box::new([iter_expr_mut]), - is_assignee_expr: false, - }, + Expr::Call { callee: iter_next_fn_expr, args: Box::new([iter_expr_mut]) }, syntax_ptr, ); let loop_inner = self.alloc_expr( @@ -942,10 +1074,8 @@ impl ExprCollector<'_> { }; let operand = self.collect_expr_opt(e.expr()); let try_branch = self.alloc_expr(Expr::Path(try_branch), syntax_ptr); - let expr = self.alloc_expr( - Expr::Call { callee: try_branch, args: Box::new([operand]), is_assignee_expr: false }, - syntax_ptr, - ); + let expr = self + .alloc_expr(Expr::Call { callee: try_branch, args: Box::new([operand]) }, syntax_ptr); let continue_name = Name::generate_new_name(self.body.bindings.len()); let continue_binding = self.alloc_binding(continue_name.clone(), BindingAnnotation::Unannotated); @@ -975,10 +1105,8 @@ impl ExprCollector<'_> { expr: { let it = self.alloc_expr(Expr::Path(Path::from(break_name)), syntax_ptr); let callee = self.alloc_expr(Expr::Path(try_from_residual), syntax_ptr); - let result = self.alloc_expr( - Expr::Call { callee, args: Box::new([it]), is_assignee_expr: false }, - syntax_ptr, - ); + let result = + self.alloc_expr(Expr::Call { callee, args: Box::new([it]) }, syntax_ptr); self.alloc_expr( match self.current_try_block_label { Some(label) => Expr::Break { expr: Some(result), label: Some(label) }, @@ -1723,10 +1851,8 @@ impl ExprCollector<'_> { } }) .collect(); - let lit_pieces = self.alloc_expr_desugared(Expr::Array(Array::ElementList { - elements: lit_pieces, - is_assignee_expr: false, - })); + let lit_pieces = + self.alloc_expr_desugared(Expr::Array(Array::ElementList { elements: lit_pieces })); let lit_pieces = self.alloc_expr_desugared(Expr::Ref { expr: lit_pieces, rawness: Rawness::Ref, @@ -1743,10 +1869,7 @@ impl ExprCollector<'_> { Some(self.make_format_spec(placeholder, &mut argmap)) }) .collect(); - let array = self.alloc_expr_desugared(Expr::Array(Array::ElementList { - elements, - is_assignee_expr: false, - })); + let array = self.alloc_expr_desugared(Expr::Array(Array::ElementList { elements })); self.alloc_expr_desugared(Expr::Ref { expr: array, rawness: Rawness::Ref, @@ -1756,10 +1879,8 @@ impl ExprCollector<'_> { let arguments = &*fmt.arguments.arguments; let args = if arguments.is_empty() { - let expr = self.alloc_expr_desugared(Expr::Array(Array::ElementList { - elements: Box::default(), - is_assignee_expr: false, - })); + let expr = self + .alloc_expr_desugared(Expr::Array(Array::ElementList { elements: Box::default() })); self.alloc_expr_desugared(Expr::Ref { expr, rawness: Rawness::Ref, @@ -1786,10 +1907,8 @@ impl ExprCollector<'_> { self.make_argument(arg, ty) }) .collect(); - let array = self.alloc_expr_desugared(Expr::Array(Array::ElementList { - elements: args, - is_assignee_expr: false, - })); + let array = + self.alloc_expr_desugared(Expr::Array(Array::ElementList { elements: args })); self.alloc_expr_desugared(Expr::Ref { expr: array, rawness: Rawness::Ref, @@ -1822,11 +1941,8 @@ impl ExprCollector<'_> { let new_v1_formatted = self.alloc_expr_desugared(Expr::Path(new_v1_formatted)); let unsafe_arg_new = self.alloc_expr_desugared(Expr::Path(unsafe_arg_new)); - let unsafe_arg_new = self.alloc_expr_desugared(Expr::Call { - callee: unsafe_arg_new, - args: Box::default(), - is_assignee_expr: false, - }); + let unsafe_arg_new = + self.alloc_expr_desugared(Expr::Call { callee: unsafe_arg_new, args: Box::default() }); let unsafe_arg_new = self.alloc_expr_desugared(Expr::Unsafe { id: None, // We collect the unused expressions here so that we still infer them instead of @@ -1843,7 +1959,6 @@ impl ExprCollector<'_> { Expr::Call { callee: new_v1_formatted, args: Box::new([lit_pieces, args, format_options, unsafe_arg_new]), - is_assignee_expr: false, }, syntax_ptr, ); @@ -1938,7 +2053,6 @@ impl ExprCollector<'_> { self.alloc_expr_desugared(Expr::Call { callee: format_placeholder_new, args: Box::new([position, fill, align, flags, precision, width]), - is_assignee_expr: false, }) } @@ -1980,11 +2094,7 @@ impl ExprCollector<'_> { Some(count_is) => self.alloc_expr_desugared(Expr::Path(count_is)), None => self.missing_expr(), }; - self.alloc_expr_desugared(Expr::Call { - callee: count_is, - args: Box::new([args]), - is_assignee_expr: false, - }) + self.alloc_expr_desugared(Expr::Call { callee: count_is, args: Box::new([args]) }) } Some(FormatCount::Argument(arg)) => { if let Ok(arg_index) = arg.index { @@ -2005,7 +2115,6 @@ impl ExprCollector<'_> { self.alloc_expr_desugared(Expr::Call { callee: count_param, args: Box::new([args]), - is_assignee_expr: false, }) } else { // FIXME: This drops arg causing it to potentially not be resolved/type checked @@ -2054,11 +2163,7 @@ impl ExprCollector<'_> { Some(new_fn) => self.alloc_expr_desugared(Expr::Path(new_fn)), None => self.missing_expr(), }; - self.alloc_expr_desugared(Expr::Call { - callee: new_fn, - args: Box::new([arg]), - is_assignee_expr: false, - }) + self.alloc_expr_desugared(Expr::Call { callee: new_fn, args: Box::new([arg]) }) } // endregion: format @@ -2110,6 +2215,10 @@ impl ExprCollector<'_> { binding } + fn alloc_pat_from_expr(&mut self, pat: Pat, _ptr: ExprPtr) -> PatId { + // FIXME: Insert into source map. + self.body.pats.alloc(pat) + } fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId { let src = self.expander.in_file(ptr); let id = self.body.pats.alloc(pat); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs index 37167fcb8155..2419862b7617 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs @@ -277,7 +277,7 @@ impl Printer<'_> { w!(self, "loop "); self.print_expr(*body); } - Expr::Call { callee, args, is_assignee_expr: _ } => { + Expr::Call { callee, args } => { self.print_expr(*callee); w!(self, "("); if !args.is_empty() { @@ -372,7 +372,7 @@ impl Printer<'_> { self.print_expr(*expr); } } - Expr::RecordLit { path, fields, spread, ellipsis, is_assignee_expr: _ } => { + Expr::RecordLit { path, fields, spread } => { match path { Some(path) => self.print_path(path), None => w!(self, "�"), @@ -391,9 +391,6 @@ impl Printer<'_> { p.print_expr(*spread); wln!(p); } - if *ellipsis { - wln!(p, ".."); - } }); w!(self, "}}"); } @@ -466,7 +463,7 @@ impl Printer<'_> { w!(self, ") "); } } - Expr::Index { base, index, is_assignee_expr: _ } => { + Expr::Index { base, index } => { self.print_expr(*base); w!(self, "["); self.print_expr(*index); @@ -507,7 +504,7 @@ impl Printer<'_> { self.whitespace(); self.print_expr(*body); } - Expr::Tuple { exprs, is_assignee_expr: _ } => { + Expr::Tuple { exprs } => { w!(self, "("); for expr in exprs.iter() { self.print_expr(*expr); @@ -519,7 +516,7 @@ impl Printer<'_> { w!(self, "["); if !matches!(arr, Array::ElementList { elements, .. } if elements.is_empty()) { self.indented(|p| match arr { - Array::ElementList { elements, is_assignee_expr: _ } => { + Array::ElementList { elements } => { for elem in elements.iter() { p.print_expr(*elem); w!(p, ", "); @@ -551,6 +548,11 @@ impl Printer<'_> { Expr::Const(id) => { w!(self, "const {{ /* {id:?} */ }}"); } + &Expr::Assignment { target, value } => { + self.print_pat(target); + w!(self, " = "); + self.print_expr(value); + } } } @@ -719,6 +721,9 @@ impl Printer<'_> { w!(self, "const "); self.print_expr(*c); } + Pat::Expr(expr) => { + self.print_expr(*expr); + } } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs index bf201ca83479..56d6ed233099 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs @@ -282,7 +282,7 @@ fn compute_expr_scopes( *scope = scopes.new_scope(*scope); scopes.add_pat_bindings(body, *scope, pat); } - e => e.walk_child_exprs(|e| compute_expr_scopes(scopes, e, scope)), + _ => body.walk_child_exprs(expr, |e| compute_expr_scopes(scopes, e, scope)), }; } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs index d9358a28822e..3c62b04f97ef 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs @@ -204,7 +204,6 @@ pub enum Expr { Call { callee: ExprId, args: Box<[ExprId]>, - is_assignee_expr: bool, }, MethodCall { receiver: ExprId, @@ -239,8 +238,6 @@ pub enum Expr { path: Option>, fields: Box<[RecordLitField]>, spread: Option, - ellipsis: bool, - is_assignee_expr: bool, }, Field { expr: ExprId, @@ -265,11 +262,17 @@ pub enum Expr { expr: ExprId, op: UnaryOp, }, + /// `op` cannot be bare `=` (but can be `op=`), these are lowered to `Assignment` instead. BinaryOp { lhs: ExprId, rhs: ExprId, op: Option, }, + // Assignments need a special treatment because of destructuring assignment. + Assignment { + target: PatId, + value: ExprId, + }, Range { lhs: Option, rhs: Option, @@ -278,7 +281,6 @@ pub enum Expr { Index { base: ExprId, index: ExprId, - is_assignee_expr: bool, }, Closure { args: Box<[PatId]>, @@ -290,7 +292,6 @@ pub enum Expr { }, Tuple { exprs: Box<[ExprId]>, - is_assignee_expr: bool, }, Array(Array), Literal(Literal), @@ -446,7 +447,7 @@ pub enum Movability { #[derive(Debug, Clone, Eq, PartialEq)] pub enum Array { - ElementList { elements: Box<[ExprId]>, is_assignee_expr: bool }, + ElementList { elements: Box<[ExprId]> }, Repeat { initializer: ExprId, repeat: ExprId }, } @@ -480,130 +481,6 @@ pub enum Statement { Item, } -impl Expr { - pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) { - match self { - Expr::Missing => {} - Expr::Path(_) | Expr::OffsetOf(_) => {} - Expr::InlineAsm(it) => it.operands.iter().for_each(|(_, op)| match op { - AsmOperand::In { expr, .. } - | AsmOperand::Out { expr: Some(expr), .. } - | AsmOperand::InOut { expr, .. } => f(*expr), - AsmOperand::SplitInOut { in_expr, out_expr, .. } => { - f(*in_expr); - if let Some(out_expr) = out_expr { - f(*out_expr); - } - } - AsmOperand::Out { expr: None, .. } - | AsmOperand::Const(_) - | AsmOperand::Label(_) - | AsmOperand::Sym(_) => (), - }), - Expr::If { condition, then_branch, else_branch } => { - f(*condition); - f(*then_branch); - if let &Some(else_branch) = else_branch { - f(else_branch); - } - } - Expr::Let { expr, .. } => { - f(*expr); - } - Expr::Const(_) => (), - Expr::Block { statements, tail, .. } - | Expr::Unsafe { statements, tail, .. } - | Expr::Async { statements, tail, .. } => { - for stmt in statements.iter() { - match stmt { - Statement::Let { initializer, else_branch, .. } => { - if let &Some(expr) = initializer { - f(expr); - } - if let &Some(expr) = else_branch { - f(expr); - } - } - Statement::Expr { expr: expression, .. } => f(*expression), - Statement::Item => (), - } - } - if let &Some(expr) = tail { - f(expr); - } - } - Expr::Loop { body, .. } => f(*body), - Expr::Call { callee, args, .. } => { - f(*callee); - args.iter().copied().for_each(f); - } - Expr::MethodCall { receiver, args, .. } => { - f(*receiver); - args.iter().copied().for_each(f); - } - Expr::Match { expr, arms } => { - f(*expr); - arms.iter().map(|arm| arm.expr).for_each(f); - } - Expr::Continue { .. } => {} - Expr::Break { expr, .. } - | Expr::Return { expr } - | Expr::Yield { expr } - | Expr::Yeet { expr } => { - if let &Some(expr) = expr { - f(expr); - } - } - Expr::Become { expr } => f(*expr), - Expr::RecordLit { fields, spread, .. } => { - for field in fields.iter() { - f(field.expr); - } - if let &Some(expr) = spread { - f(expr); - } - } - Expr::Closure { body, .. } => { - f(*body); - } - Expr::BinaryOp { lhs, rhs, .. } => { - f(*lhs); - f(*rhs); - } - Expr::Range { lhs, rhs, .. } => { - if let &Some(lhs) = rhs { - f(lhs); - } - if let &Some(rhs) = lhs { - f(rhs); - } - } - Expr::Index { base, index, .. } => { - f(*base); - f(*index); - } - Expr::Field { expr, .. } - | Expr::Await { expr } - | Expr::Cast { expr, .. } - | Expr::Ref { expr, .. } - | Expr::UnaryOp { expr, .. } - | Expr::Box { expr } => { - f(*expr); - } - Expr::Tuple { exprs, .. } => exprs.iter().copied().for_each(f), - Expr::Array(a) => match a { - Array::ElementList { elements, .. } => elements.iter().copied().for_each(f), - Array::Repeat { initializer, repeat } => { - f(*initializer); - f(*repeat) - } - }, - Expr::Literal(_) => {} - Expr::Underscore => {} - } - } -} - /// Explicit binding annotations given in the HIR for a binding. Note /// that this is not the final binding *mode* that we infer after type /// inference. @@ -665,18 +542,49 @@ pub struct RecordFieldPat { pub enum Pat { Missing, Wild, - Tuple { args: Box<[PatId]>, ellipsis: Option }, + Tuple { + args: Box<[PatId]>, + ellipsis: Option, + }, Or(Box<[PatId]>), - Record { path: Option>, args: Box<[RecordFieldPat]>, ellipsis: bool }, - Range { start: Option>, end: Option> }, - Slice { prefix: Box<[PatId]>, slice: Option, suffix: Box<[PatId]> }, + Record { + path: Option>, + args: Box<[RecordFieldPat]>, + ellipsis: bool, + }, + Range { + start: Option>, + end: Option>, + }, + Slice { + prefix: Box<[PatId]>, + slice: Option, + suffix: Box<[PatId]>, + }, + /// This might refer to a variable if a single segment path (specifically, on destructuring assignment). Path(Box), Lit(ExprId), - Bind { id: BindingId, subpat: Option }, - TupleStruct { path: Option>, args: Box<[PatId]>, ellipsis: Option }, - Ref { pat: PatId, mutability: Mutability }, - Box { inner: PatId }, + Bind { + id: BindingId, + subpat: Option, + }, + TupleStruct { + path: Option>, + args: Box<[PatId]>, + ellipsis: Option, + }, + Ref { + pat: PatId, + mutability: Mutability, + }, + Box { + inner: PatId, + }, ConstBlock(ExprId), + /// An expression inside a pattern. That can only occur inside assignments. + /// + /// E.g. in `(a, *b) = (1, &mut 2)`, `*b` is an expression. + Expr(ExprId), } impl Pat { @@ -687,7 +595,8 @@ impl Pat { | Pat::Path(..) | Pat::ConstBlock(..) | Pat::Wild - | Pat::Missing => {} + | Pat::Missing + | Pat::Expr(_) => {} Pat::Bind { subpat, .. } => { subpat.iter().copied().for_each(f); } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs index e41058aac2a9..6a8598884404 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs @@ -319,7 +319,7 @@ pub(crate) fn eval_to_const( return true; } let mut r = false; - body[expr].walk_child_exprs(|idx| r |= has_closure(body, idx)); + body.walk_child_exprs(expr, |idx| r |= has_closure(body, idx)); r } if has_closure(ctx.body, expr) { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs index f8b5c7d0ce2c..75dce7783163 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs @@ -546,10 +546,7 @@ pub fn record_literal_missing_fields( expr: &Expr, ) -> Option<(VariantId, Vec, /*exhaustive*/ bool)> { let (fields, exhaustive) = match expr { - Expr::RecordLit { fields, spread, ellipsis, is_assignee_expr, .. } => { - let exhaustive = if *is_assignee_expr { !*ellipsis } else { spread.is_none() }; - (fields, exhaustive) - } + Expr::RecordLit { fields, spread, .. } => (fields, spread.is_none()), _ => return None, }; diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs index bcfc37c86711..f610c9e96c8c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -117,14 +117,14 @@ fn walk_unsafe( } } Expr::Unsafe { .. } => { - return expr.walk_child_exprs(|child| { + return body.walk_child_exprs(current, |child| { walk_unsafe(db, infer, body, resolver, def, child, true, unsafe_expr_cb); }); } _ => {} } - expr.walk_child_exprs(|child| { + body.walk_child_exprs(current, |child| { walk_unsafe(db, infer, body, resolver, def, child, inside_unsafe_block, unsafe_expr_cb); }); } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index 88334b492d5a..f2c860c9eb73 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -228,7 +228,7 @@ pub enum InferenceDiagnostic { id: ExprOrPatId, }, UnresolvedIdent { - expr: ExprId, + id: ExprOrPatId, }, // FIXME: This should be emitted in body lowering BreakOutsideOfLoop { @@ -561,6 +561,9 @@ pub(crate) struct InferenceContext<'a> { diverges: Diverges, breakables: Vec, + /// Whether we are inside the pattern of a destructuring assignment. + inside_assignment: bool, + deferred_cast_checks: Vec, // fields related to closure capture @@ -656,6 +659,7 @@ impl<'a> InferenceContext<'a> { current_closure: None, deferred_closures: FxHashMap::default(), closure_dependencies: FxHashMap::default(), + inside_assignment: false, } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs index e9825cf09988..91ba2af85e9e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs @@ -11,11 +11,12 @@ use either::Either; use hir_def::{ data::adt::VariantData, hir::{ - Array, AsmOperand, BinaryOp, BindingId, CaptureBy, Expr, ExprId, Pat, PatId, Statement, - UnaryOp, + Array, AsmOperand, BinaryOp, BindingId, CaptureBy, Expr, ExprId, ExprOrPatId, Pat, PatId, + Statement, UnaryOp, }, lang_item::LangItem, - resolver::{resolver_for_expr, ResolveValueResult, ValueNs}, + path::Path, + resolver::ValueNs, DefWithBodyId, FieldId, HasModule, TupleFieldId, TupleId, VariantId, }; use hir_expand::name::Name; @@ -508,18 +509,37 @@ impl InferenceContext<'_> { apply_adjusts_to_place(&mut self.current_capture_span_stack, r, adjustments) } + /// Pushes the span into `current_capture_span_stack`, *without clearing it first*. + fn path_place(&mut self, path: &Path, id: ExprOrPatId) -> Option { + if path.type_anchor().is_some() { + return None; + } + let result = self.resolver.resolve_path_in_value_ns_fully(self.db.upcast(), path).and_then( + |result| match result { + ValueNs::LocalBinding(binding) => { + let mir_span = match id { + ExprOrPatId::ExprId(id) => MirSpan::ExprId(id), + ExprOrPatId::PatId(id) => MirSpan::PatId(id), + }; + self.current_capture_span_stack.push(mir_span); + Some(HirPlace { local: binding, projections: Vec::new() }) + } + _ => None, + }, + ); + result + } + /// Changes `current_capture_span_stack` to contain the stack of spans for this expr. fn place_of_expr_without_adjust(&mut self, tgt_expr: ExprId) -> Option { self.current_capture_span_stack.clear(); match &self.body[tgt_expr] { Expr::Path(p) => { - let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr); - if let Some(ResolveValueResult::ValueNs(ValueNs::LocalBinding(b), _)) = - resolver.resolve_path_in_value_ns(self.db.upcast(), p) - { - self.current_capture_span_stack.push(MirSpan::ExprId(tgt_expr)); - return Some(HirPlace { local: b, projections: vec![] }); - } + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, tgt_expr); + let result = self.path_place(p, tgt_expr.into()); + self.resolver.reset_to_guard(resolver_guard); + return result; } Expr::Field { expr, name: _ } => { let mut place = self.place_of_expr(*expr)?; @@ -590,6 +610,16 @@ impl InferenceContext<'_> { } } + fn mutate_path_pat(&mut self, path: &Path, id: PatId) { + if let Some(place) = self.path_place(path, id.into()) { + self.add_capture( + place, + CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::Default }), + ); + self.current_capture_span_stack.pop(); // Remove the pattern span. + } + } + fn mutate_expr(&mut self, expr: ExprId, place: Option) { if let Some(place) = place { self.add_capture( @@ -722,7 +752,7 @@ impl InferenceContext<'_> { self.consume_expr(*tail); } } - Expr::Call { callee, args, is_assignee_expr: _ } => { + Expr::Call { callee, args } => { self.consume_expr(*callee); self.consume_exprs(args.iter().copied()); } @@ -838,7 +868,7 @@ impl InferenceContext<'_> { self.consume_expr(expr); } } - Expr::Index { base, index, is_assignee_expr: _ } => { + Expr::Index { base, index } => { self.select_from_expr(*base); self.consume_expr(*index); } @@ -862,10 +892,30 @@ impl InferenceContext<'_> { })); self.current_captures = cc; } - Expr::Array(Array::ElementList { elements: exprs, is_assignee_expr: _ }) - | Expr::Tuple { exprs, is_assignee_expr: _ } => { + Expr::Array(Array::ElementList { elements: exprs }) | Expr::Tuple { exprs } => { self.consume_exprs(exprs.iter().copied()) } + &Expr::Assignment { target, value } => { + self.walk_expr(value); + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, tgt_expr); + match self.place_of_expr(value) { + Some(rhs_place) => { + self.inside_assignment = true; + self.consume_with_pat(rhs_place, target); + self.inside_assignment = false; + } + None => self.body.walk_pats(target, &mut |pat| match &self.body[pat] { + Pat::Path(path) => self.mutate_path_pat(path, pat), + &Pat::Expr(expr) => { + let place = self.place_of_expr(expr); + self.mutate_expr(expr, place); + } + _ => {} + }), + } + self.resolver.reset_to_guard(resolver_guard); + } Expr::Missing | Expr::Continue { .. } @@ -903,6 +953,7 @@ impl InferenceContext<'_> { | Pat::Missing | Pat::Wild | Pat::Tuple { .. } + | Pat::Expr(_) | Pat::Or(_) => (), Pat::TupleStruct { .. } | Pat::Record { .. } => { if let Some(variant) = self.result.variant_resolution_for_pat(p) { @@ -1122,11 +1173,15 @@ impl InferenceContext<'_> { } } } - Pat::Range { .. } - | Pat::Slice { .. } - | Pat::ConstBlock(_) - | Pat::Path(_) - | Pat::Lit(_) => self.consume_place(place), + Pat::Range { .. } | Pat::Slice { .. } | Pat::ConstBlock(_) | Pat::Lit(_) => { + self.consume_place(place) + } + Pat::Path(path) => { + if self.inside_assignment { + self.mutate_path_pat(path, tgt_pat); + } + self.consume_place(place); + } &Pat::Bind { id, subpat: _ } => { let mode = self.result.binding_modes[tgt_pat]; let capture_kind = match mode { @@ -1180,6 +1235,15 @@ impl InferenceContext<'_> { self.current_capture_span_stack.pop(); } Pat::Box { .. } => (), // not supported + &Pat::Expr(expr) => { + self.consume_place(place); + let pat_capture_span_stack = mem::take(&mut self.current_capture_span_stack); + let old_inside_assignment = mem::replace(&mut self.inside_assignment, false); + let lhs_place = self.place_of_expr(expr); + self.mutate_expr(expr, lhs_place); + self.inside_assignment = old_inside_assignment; + self.current_capture_span_stack = pat_capture_span_stack; + } } } self.current_capture_span_stack diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs index 657e4d779661..5c822fd22e1c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs @@ -9,8 +9,8 @@ use chalk_ir::{cast::Cast, fold::Shift, DebruijnIndex, Mutability, TyVariableKin use either::Either; use hir_def::{ hir::{ - ArithOp, Array, AsmOperand, AsmOptions, BinaryOp, ClosureKind, Expr, ExprId, LabelId, - Literal, Pat, PatId, Statement, UnaryOp, + ArithOp, Array, AsmOperand, AsmOptions, BinaryOp, ClosureKind, Expr, ExprId, ExprOrPatId, + LabelId, Literal, Pat, PatId, Statement, UnaryOp, }, lang_item::{LangItem, LangItemTarget}, path::{GenericArg, GenericArgs, Path}, @@ -188,6 +188,9 @@ impl InferenceContext<'_> { | Pat::ConstBlock(_) | Pat::Record { .. } | Pat::Missing => true, + Pat::Expr(_) => unreachable!( + "we don't call pat_guaranteed_to_constitute_read_for_never() with assignments" + ), } } @@ -223,6 +226,7 @@ impl InferenceContext<'_> { | Expr::Const(..) | Expr::UnaryOp { .. } | Expr::BinaryOp { .. } + | Expr::Assignment { .. } | Expr::Yield { .. } | Expr::Cast { .. } | Expr::Async { .. } @@ -609,23 +613,7 @@ impl InferenceContext<'_> { coerce.complete(self) } } - Expr::Path(p) => { - let g = self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, tgt_expr); - let ty = match self.infer_path(p, tgt_expr.into()) { - Some(ty) => ty, - None => { - if matches!(p, Path::Normal { mod_path, .. } if mod_path.is_ident() || mod_path.is_self()) - { - self.push_diagnostic(InferenceDiagnostic::UnresolvedIdent { - expr: tgt_expr, - }); - } - self.err_ty() - } - }; - self.resolver.reset_to_guard(g); - ty - } + Expr::Path(p) => self.infer_expr_path(p, tgt_expr.into(), tgt_expr), &Expr::Continue { label } => { if find_continuable(&mut self.breakables, label).is_none() { self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop { @@ -892,36 +880,6 @@ impl InferenceContext<'_> { } } Expr::BinaryOp { lhs, rhs, op } => match op { - Some(BinaryOp::Assignment { op: None }) => { - let lhs = *lhs; - let is_ordinary = match &self.body[lhs] { - Expr::Array(_) - | Expr::RecordLit { .. } - | Expr::Tuple { .. } - | Expr::Underscore => false, - Expr::Call { callee, .. } => !matches!(&self.body[*callee], Expr::Path(_)), - _ => true, - }; - - // In ordinary (non-destructuring) assignments, the type of - // `lhs` must be inferred first so that the ADT fields - // instantiations in RHS can be coerced to it. Note that this - // cannot happen in destructuring assignments because of how - // they are desugared. - if is_ordinary { - // LHS of assignment doesn't constitute reads. - let lhs_ty = self.infer_expr(lhs, &Expectation::none(), ExprIsRead::No); - self.infer_expr_coerce( - *rhs, - &Expectation::has_type(lhs_ty), - ExprIsRead::No, - ); - } else { - let rhs_ty = self.infer_expr(*rhs, &Expectation::none(), ExprIsRead::Yes); - self.infer_assignee_expr(lhs, &rhs_ty); - } - self.result.standard_types.unit.clone() - } Some(BinaryOp::LogicOp(_)) => { let bool_ty = self.result.standard_types.bool_.clone(); self.infer_expr_coerce( @@ -942,6 +900,35 @@ impl InferenceContext<'_> { Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr), _ => self.err_ty(), }, + &Expr::Assignment { target, value } => { + // In ordinary (non-destructuring) assignments, the type of + // `lhs` must be inferred first so that the ADT fields + // instantiations in RHS can be coerced to it. Note that this + // cannot happen in destructuring assignments because of how + // they are desugared. + let lhs_ty = match &self.body[target] { + // LHS of assignment doesn't constitute reads. + &Pat::Expr(expr) => { + Some(self.infer_expr(expr, &Expectation::none(), ExprIsRead::No)) + } + Pat::Path(path) => Some(self.infer_expr_path(path, target.into(), tgt_expr)), + _ => None, + }; + + if let Some(lhs_ty) = lhs_ty { + self.write_pat_ty(target, lhs_ty.clone()); + self.infer_expr_coerce(value, &Expectation::has_type(lhs_ty), ExprIsRead::No); + } else { + let rhs_ty = self.infer_expr(value, &Expectation::none(), ExprIsRead::Yes); + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, tgt_expr); + self.inside_assignment = true; + self.infer_top_pat(target, &rhs_ty); + self.inside_assignment = false; + self.resolver.reset_to_guard(resolver_guard); + } + self.result.standard_types.unit.clone() + } Expr::Range { lhs, rhs, range_type } => { let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none(), ExprIsRead::Yes)); @@ -981,7 +968,7 @@ impl InferenceContext<'_> { (RangeOp::Inclusive, _, None) => self.err_ty(), } } - Expr::Index { base, index, is_assignee_expr } => { + Expr::Index { base, index } => { let base_ty = self.infer_expr_inner(*base, &Expectation::none(), ExprIsRead::Yes); let index_ty = self.infer_expr(*index, &Expectation::none(), ExprIsRead::Yes); @@ -1017,23 +1004,11 @@ impl InferenceContext<'_> { self.write_method_resolution(tgt_expr, func, subst); } let assoc = self.resolve_ops_index_output(); - let res = self.resolve_associated_type_with_params( + self.resolve_associated_type_with_params( self_ty.clone(), assoc, &[index_ty.clone().cast(Interner)], - ); - - if *is_assignee_expr { - if let Some(index_trait) = self.resolve_lang_trait(LangItem::IndexMut) { - let trait_ref = TyBuilder::trait_ref(self.db, index_trait) - .push(self_ty) - .fill(|_| index_ty.clone().cast(Interner)) - .build(); - self.push_obligation(trait_ref.cast(Interner)); - } - } - - res + ) } else { self.err_ty() } @@ -1151,9 +1126,7 @@ impl InferenceContext<'_> { }, }, Expr::Underscore => { - // Underscore expressions may only appear in assignee expressions, - // which are handled by `infer_assignee_expr()`. - // Any other underscore expression is an error, we render a specialized diagnostic + // Underscore expression is an error, we render a specialized diagnostic // to let the user know what type is expected though. let expected = expected.to_option(&mut self.table).unwrap_or_else(|| self.err_ty()); self.push_diagnostic(InferenceDiagnostic::TypedHole { @@ -1232,6 +1205,22 @@ impl InferenceContext<'_> { ty } + fn infer_expr_path(&mut self, path: &Path, id: ExprOrPatId, scope_id: ExprId) -> Ty { + let g = self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, scope_id); + let ty = match self.infer_path(path, id) { + Some(ty) => ty, + None => { + if matches!(path, Path::Normal { mod_path, .. } if mod_path.is_ident() || mod_path.is_self()) + { + self.push_diagnostic(InferenceDiagnostic::UnresolvedIdent { id }); + } + self.err_ty() + } + }; + self.resolver.reset_to_guard(g); + ty + } + fn infer_async_block( &mut self, tgt_expr: ExprId, @@ -1482,107 +1471,6 @@ impl InferenceContext<'_> { } } - pub(super) fn infer_assignee_expr(&mut self, lhs: ExprId, rhs_ty: &Ty) -> Ty { - let is_rest_expr = |expr| { - matches!( - &self.body[expr], - Expr::Range { lhs: None, rhs: None, range_type: RangeOp::Exclusive }, - ) - }; - - let rhs_ty = self.resolve_ty_shallow(rhs_ty); - - let ty = match &self.body[lhs] { - Expr::Tuple { exprs, .. } => { - // We don't consider multiple ellipses. This is analogous to - // `hir_def::body::lower::ExprCollector::collect_tuple_pat()`. - let ellipsis = exprs.iter().position(|e| is_rest_expr(*e)).map(|it| it as u32); - let exprs: Vec<_> = exprs.iter().filter(|e| !is_rest_expr(**e)).copied().collect(); - - self.infer_tuple_pat_like(&rhs_ty, (), ellipsis, &exprs) - } - Expr::Call { callee, args, .. } => { - // Tuple structs - let path = match &self.body[*callee] { - Expr::Path(path) => Some(path), - _ => None, - }; - - // We don't consider multiple ellipses. This is analogous to - // `hir_def::body::lower::ExprCollector::collect_tuple_pat()`. - let ellipsis = args.iter().position(|e| is_rest_expr(*e)).map(|it| it as u32); - let args: Vec<_> = args.iter().filter(|e| !is_rest_expr(**e)).copied().collect(); - - self.infer_tuple_struct_pat_like(path, &rhs_ty, (), lhs, ellipsis, &args) - } - Expr::Array(Array::ElementList { elements, .. }) => { - let elem_ty = match rhs_ty.kind(Interner) { - TyKind::Array(st, _) => st.clone(), - _ => self.err_ty(), - }; - - // There's no need to handle `..` as it cannot be bound. - let sub_exprs = elements.iter().filter(|e| !is_rest_expr(**e)); - - for e in sub_exprs { - self.infer_assignee_expr(*e, &elem_ty); - } - - match rhs_ty.kind(Interner) { - TyKind::Array(_, _) => rhs_ty.clone(), - // Even when `rhs_ty` is not an array type, this assignee - // expression is inferred to be an array (of unknown element - // type and length). This should not be just an error type, - // because we are to compute the unifiability of this type and - // `rhs_ty` in the end of this function to issue type mismatches. - _ => TyKind::Array( - self.err_ty(), - crate::consteval::usize_const(self.db, None, self.resolver.krate()), - ) - .intern(Interner), - } - } - Expr::RecordLit { path, fields, .. } => { - let subs = fields.iter().map(|f| (f.name.clone(), f.expr)); - - self.infer_record_pat_like(path.as_deref(), &rhs_ty, (), lhs, subs) - } - Expr::Underscore => rhs_ty.clone(), - _ => { - // `lhs` is a place expression, a unit struct, or an enum variant. - // LHS of assignment doesn't constitute reads. - let lhs_ty = self.infer_expr_inner(lhs, &Expectation::none(), ExprIsRead::No); - - // This is the only branch where this function may coerce any type. - // We are returning early to avoid the unifiability check below. - let lhs_ty = self.insert_type_vars_shallow(lhs_ty); - let ty = match self.coerce(None, &rhs_ty, &lhs_ty, CoerceNever::Yes) { - Ok(ty) => ty, - Err(_) => { - self.result.type_mismatches.insert( - lhs.into(), - TypeMismatch { expected: rhs_ty.clone(), actual: lhs_ty.clone() }, - ); - // `rhs_ty` is returned so no further type mismatches are - // reported because of this mismatch. - rhs_ty - } - }; - self.write_expr_ty(lhs, ty.clone()); - return ty; - } - }; - - let ty = self.insert_type_vars_shallow(ty); - if !self.unify(&ty, &rhs_ty) { - self.result - .type_mismatches - .insert(lhs.into(), TypeMismatch { expected: rhs_ty.clone(), actual: ty.clone() }); - } - self.write_expr_ty(lhs, ty.clone()); - ty - } - fn infer_overloadable_binop( &mut self, lhs: ExprId, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs index 6a0daee6ea9f..9fef582d85de 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs @@ -4,7 +4,8 @@ use chalk_ir::{cast::Cast, Mutability}; use hir_def::{ hir::{ - Array, AsmOperand, BinaryOp, BindingAnnotation, Expr, ExprId, PatId, Statement, UnaryOp, + Array, AsmOperand, BinaryOp, BindingAnnotation, Expr, ExprId, Pat, PatId, Statement, + UnaryOp, }, lang_item::LangItem, }; @@ -96,7 +97,7 @@ impl InferenceContext<'_> { } } Expr::MethodCall { receiver: it, method_name: _, args, generic_args: _ } - | Expr::Call { callee: it, args, is_assignee_expr: _ } => { + | Expr::Call { callee: it, args } => { self.infer_mut_not_expr_iter(args.iter().copied().chain(Some(*it))); } Expr::Match { expr, arms } => { @@ -120,10 +121,10 @@ impl InferenceContext<'_> { Expr::Become { expr } => { self.infer_mut_expr(*expr, Mutability::Not); } - Expr::RecordLit { path: _, fields, spread, ellipsis: _, is_assignee_expr: _ } => { + Expr::RecordLit { path: _, fields, spread } => { self.infer_mut_not_expr_iter(fields.iter().map(|it| it.expr).chain(*spread)) } - &Expr::Index { base, index, is_assignee_expr } => { + &Expr::Index { base, index } => { if mutability == Mutability::Mut { if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) { if let Some(index_trait) = self @@ -148,11 +149,8 @@ impl InferenceContext<'_> { target, }) = base_adjustments { - // For assignee exprs `IndexMut` obligations are already applied - if !is_assignee_expr { - if let TyKind::Ref(_, _, ty) = target.kind(Interner) { - base_ty = Some(ty.clone()); - } + if let TyKind::Ref(_, _, ty) = target.kind(Interner) { + base_ty = Some(ty.clone()); } *mutability = Mutability::Mut; } @@ -233,6 +231,14 @@ impl InferenceContext<'_> { self.infer_mut_expr(*lhs, Mutability::Mut); self.infer_mut_expr(*rhs, Mutability::Not); } + &Expr::Assignment { target, value } => { + self.body.walk_pats(target, &mut |pat| match self.body[pat] { + Pat::Expr(expr) => self.infer_mut_expr(expr, Mutability::Mut), + Pat::ConstBlock(block) => self.infer_mut_expr(block, Mutability::Not), + _ => {} + }); + self.infer_mut_expr(value, Mutability::Not); + } Expr::Array(Array::Repeat { initializer: lhs, repeat: rhs }) | Expr::BinaryOp { lhs, rhs, op: _ } | Expr::Range { lhs: Some(lhs), rhs: Some(rhs), range_type: _ } => { @@ -242,8 +248,7 @@ impl InferenceContext<'_> { Expr::Closure { body, .. } => { self.infer_mut_expr(*body, Mutability::Not); } - Expr::Tuple { exprs, is_assignee_expr: _ } - | Expr::Array(Array::ElementList { elements: exprs, is_assignee_expr: _ }) => { + Expr::Tuple { exprs } | Expr::Array(Array::ElementList { elements: exprs }) => { self.infer_mut_not_expr_iter(exprs.iter().copied()); } // These don't need any action, as they don't have sub expressions diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs index fee6755408ea..50e761196ec1 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs @@ -4,7 +4,7 @@ use std::iter::repeat_with; use hir_def::{ body::Body, - hir::{Binding, BindingAnnotation, BindingId, Expr, ExprId, ExprOrPatId, Literal, Pat, PatId}, + hir::{Binding, BindingAnnotation, BindingId, Expr, ExprId, Literal, Pat, PatId}, path::Path, }; use hir_expand::name::Name; @@ -12,63 +12,28 @@ use stdx::TupleExt; use crate::{ consteval::{try_const_usize, usize_const}, - infer::{expr::ExprIsRead, BindingMode, Expectation, InferenceContext, TypeMismatch}, + infer::{ + coerce::CoerceNever, expr::ExprIsRead, BindingMode, Expectation, InferenceContext, + TypeMismatch, + }, lower::lower_to_chalk_mutability, primitive::UintTy, static_lifetime, InferenceDiagnostic, Interner, Mutability, Scalar, Substitution, Ty, TyBuilder, TyExt, TyKind, }; -/// Used to generalize patterns and assignee expressions. -pub(super) trait PatLike: Into + Copy { - type BindingMode: Copy; - - fn infer( - this: &mut InferenceContext<'_>, - id: Self, - expected_ty: &Ty, - default_bm: Self::BindingMode, - ) -> Ty; -} - -impl PatLike for ExprId { - type BindingMode = (); - - fn infer( - this: &mut InferenceContext<'_>, - id: Self, - expected_ty: &Ty, - (): Self::BindingMode, - ) -> Ty { - this.infer_assignee_expr(id, expected_ty) - } -} - -impl PatLike for PatId { - type BindingMode = BindingMode; - - fn infer( - this: &mut InferenceContext<'_>, - id: Self, - expected_ty: &Ty, - default_bm: Self::BindingMode, - ) -> Ty { - this.infer_pat(id, expected_ty, default_bm) - } -} - impl InferenceContext<'_> { /// Infers type for tuple struct pattern or its corresponding assignee expression. /// /// Ellipses found in the original pattern or expression must be filtered out. - pub(super) fn infer_tuple_struct_pat_like( + pub(super) fn infer_tuple_struct_pat_like( &mut self, path: Option<&Path>, expected: &Ty, - default_bm: T::BindingMode, - id: T, + default_bm: BindingMode, + id: PatId, ellipsis: Option, - subs: &[T], + subs: &[PatId], ) -> Ty { let (ty, def) = self.resolve_variant(path, true); let var_data = def.map(|it| it.variant_data(self.db.upcast())); @@ -127,13 +92,13 @@ impl InferenceContext<'_> { } }; - T::infer(self, subpat, &expected_ty, default_bm); + self.infer_pat(subpat, &expected_ty, default_bm); } } None => { let err_ty = self.err_ty(); for &inner in subs { - T::infer(self, inner, &err_ty, default_bm); + self.infer_pat(inner, &err_ty, default_bm); } } } @@ -142,13 +107,13 @@ impl InferenceContext<'_> { } /// Infers type for record pattern or its corresponding assignee expression. - pub(super) fn infer_record_pat_like( + pub(super) fn infer_record_pat_like( &mut self, path: Option<&Path>, expected: &Ty, - default_bm: T::BindingMode, - id: T, - subs: impl ExactSizeIterator, + default_bm: BindingMode, + id: PatId, + subs: impl ExactSizeIterator, ) -> Ty { let (ty, def) = self.resolve_variant(path, false); if let Some(variant) = def { @@ -197,13 +162,13 @@ impl InferenceContext<'_> { } }; - T::infer(self, inner, &expected_ty, default_bm); + self.infer_pat(inner, &expected_ty, default_bm); } } None => { let err_ty = self.err_ty(); for (_, inner) in subs { - T::infer(self, inner, &err_ty, default_bm); + self.infer_pat(inner, &err_ty, default_bm); } } } @@ -214,12 +179,12 @@ impl InferenceContext<'_> { /// Infers type for tuple pattern or its corresponding assignee expression. /// /// Ellipses found in the original pattern or expression must be filtered out. - pub(super) fn infer_tuple_pat_like( + pub(super) fn infer_tuple_pat_like( &mut self, expected: &Ty, - default_bm: T::BindingMode, + default_bm: BindingMode, ellipsis: Option, - subs: &[T], + subs: &[PatId], ) -> Ty { let expected = self.resolve_ty_shallow(expected); let expectations = match expected.as_tuple() { @@ -244,18 +209,20 @@ impl InferenceContext<'_> { // Process pre for (ty, pat) in inner_tys.iter_mut().zip(pre) { - *ty = T::infer(self, *pat, ty, default_bm); + *ty = self.infer_pat(*pat, ty, default_bm); } // Process post for (ty, pat) in inner_tys.iter_mut().skip(pre.len() + n_uncovered_patterns).zip(post) { - *ty = T::infer(self, *pat, ty, default_bm); + *ty = self.infer_pat(*pat, ty, default_bm); } TyKind::Tuple(inner_tys.len(), Substitution::from_iter(Interner, inner_tys)) .intern(Interner) } + /// The resolver needs to be updated to the surrounding expression when inside assignment + /// (because there, `Pat::Path` can refer to a variable). pub(super) fn infer_top_pat(&mut self, pat: PatId, expected: &Ty) { self.infer_pat(pat, expected, BindingMode::default()); } @@ -263,7 +230,14 @@ impl InferenceContext<'_> { fn infer_pat(&mut self, pat: PatId, expected: &Ty, mut default_bm: BindingMode) -> Ty { let mut expected = self.resolve_ty_shallow(expected); - if self.is_non_ref_pat(self.body, pat) { + if matches!(&self.body[pat], Pat::Ref { .. }) || self.inside_assignment { + cov_mark::hit!(match_ergonomics_ref); + // When you encounter a `&pat` pattern, reset to Move. + // This is so that `w` is by value: `let (_, &w) = &(1, &2);` + // Destructuring assignments also reset the binding mode and + // don't do match ergonomics. + default_bm = BindingMode::Move; + } else if self.is_non_ref_pat(self.body, pat) { let mut pat_adjustments = Vec::new(); while let Some((inner, _lifetime, mutability)) = expected.as_reference() { pat_adjustments.push(expected.clone()); @@ -279,11 +253,6 @@ impl InferenceContext<'_> { pat_adjustments.shrink_to_fit(); self.result.pat_adjustments.insert(pat, pat_adjustments); } - } else if let Pat::Ref { .. } = &self.body[pat] { - cov_mark::hit!(match_ergonomics_ref); - // When you encounter a `&pat` pattern, reset to Move. - // This is so that `w` is by value: `let (_, &w) = &(1, &2);` - default_bm = BindingMode::Move; } // Lose mutability. @@ -320,8 +289,34 @@ impl InferenceContext<'_> { self.infer_record_pat_like(p.as_deref(), &expected, default_bm, pat, subs) } Pat::Path(path) => { - // FIXME update resolver for the surrounding expression - self.infer_path(path, pat.into()).unwrap_or_else(|| self.err_ty()) + let ty = self.infer_path(path, pat.into()).unwrap_or_else(|| self.err_ty()); + let ty_inserted_vars = self.insert_type_vars_shallow(ty.clone()); + match self.table.coerce(&expected, &ty_inserted_vars, CoerceNever::Yes) { + Ok((adjustments, coerced_ty)) => { + if !adjustments.is_empty() { + self.result + .pat_adjustments + .entry(pat) + .or_default() + .extend(adjustments.into_iter().map(|adjust| adjust.target)); + } + self.write_pat_ty(pat, coerced_ty); + return self.pat_ty_after_adjustment(pat); + } + Err(_) => { + self.result.type_mismatches.insert( + pat.into(), + TypeMismatch { + expected: expected.clone(), + actual: ty_inserted_vars.clone(), + }, + ); + self.write_pat_ty(pat, ty); + // We return `expected` to prevent cascading errors. I guess an alternative is to + // not emit type mismatches for error types and emit an error type here. + return expected; + } + } } Pat::Bind { id, subpat } => { return self.infer_bind_pat(pat, *id, default_bm, *subpat, &expected); @@ -361,7 +356,40 @@ impl InferenceContext<'_> { None => self.err_ty(), }, Pat::ConstBlock(expr) => { - self.infer_expr(*expr, &Expectation::has_type(expected.clone()), ExprIsRead::Yes) + let old_inside_assign = std::mem::replace(&mut self.inside_assignment, false); + let result = self.infer_expr( + *expr, + &Expectation::has_type(expected.clone()), + ExprIsRead::Yes, + ); + self.inside_assignment = old_inside_assign; + result + } + Pat::Expr(expr) => { + let old_inside_assign = std::mem::replace(&mut self.inside_assignment, false); + // LHS of assignment doesn't constitute reads. + let result = self.infer_expr_coerce( + *expr, + &Expectation::has_type(expected.clone()), + ExprIsRead::No, + ); + // We are returning early to avoid the unifiability check below. + let lhs_ty = self.insert_type_vars_shallow(result); + let ty = match self.coerce(None, &expected, &lhs_ty, CoerceNever::Yes) { + Ok(ty) => ty, + Err(_) => { + self.result.type_mismatches.insert( + pat.into(), + TypeMismatch { expected: expected.clone(), actual: lhs_ty.clone() }, + ); + // `rhs_ty` is returned so no further type mismatches are + // reported because of this mismatch. + expected + } + }; + self.write_pat_ty(pat, ty.clone()); + self.inside_assignment = old_inside_assign; + return ty; } Pat::Missing => self.err_ty(), }; @@ -517,9 +545,12 @@ impl InferenceContext<'_> { body[*expr], Expr::Literal(Literal::String(..) | Literal::CString(..) | Literal::ByteString(..)) ), - Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Box { .. } | Pat::Missing => { - false - } + Pat::Wild + | Pat::Bind { .. } + | Pat::Ref { .. } + | Pat::Box { .. } + | Pat::Missing + | Pat::Expr(_) => false, } } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs index 16994cdd0c65..a8a927c2c5c7 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs @@ -13,7 +13,7 @@ use hir_def::{ }, lang_item::{LangItem, LangItemTarget}, path::Path, - resolver::{resolver_for_expr, HasResolver, ResolveValueResult, ValueNs}, + resolver::{HasResolver, ResolveValueResult, Resolver, ValueNs}, AdtId, DefWithBodyId, EnumVariantId, GeneralConstId, HasModule, ItemContainerId, LocalFieldId, Lookup, TraitId, TupleId, TypeOrConstParamId, }; @@ -76,6 +76,7 @@ struct MirLowerCtx<'a> { db: &'a dyn HirDatabase, body: &'a Body, infer: &'a InferenceResult, + resolver: Resolver, drop_scopes: Vec, } @@ -278,6 +279,7 @@ impl<'ctx> MirLowerCtx<'ctx> { owner, closures: vec![], }; + let resolver = owner.resolver(db.upcast()); MirLowerCtx { result: mir, @@ -285,6 +287,7 @@ impl<'ctx> MirLowerCtx<'ctx> { infer, body, owner, + resolver, current_loop_blocks: None, labeled_loop_blocks: Default::default(), discr_temp: None, @@ -410,43 +413,48 @@ impl<'ctx> MirLowerCtx<'ctx> { Err(MirLowerError::IncompleteExpr) } Expr::Path(p) => { - let pr = - if let Some((assoc, subst)) = self.infer.assoc_resolutions_for_expr(expr_id) { - match assoc { - hir_def::AssocItemId::ConstId(c) => { - self.lower_const( - c.into(), - current, - place, - subst, - expr_id.into(), - self.expr_ty_without_adjust(expr_id), - )?; - return Ok(Some(current)); - } - hir_def::AssocItemId::FunctionId(_) => { - // FnDefs are zero sized, no action is needed. - return Ok(Some(current)); - } - hir_def::AssocItemId::TypeAliasId(_) => { - // FIXME: If it is unreachable, use proper error instead of `not_supported`. - not_supported!("associated functions and types") - } + let pr = if let Some((assoc, subst)) = + self.infer.assoc_resolutions_for_expr(expr_id) + { + match assoc { + hir_def::AssocItemId::ConstId(c) => { + self.lower_const( + c.into(), + current, + place, + subst, + expr_id.into(), + self.expr_ty_without_adjust(expr_id), + )?; + return Ok(Some(current)); } - } else if let Some(variant) = self.infer.variant_resolution_for_expr(expr_id) { - match variant { - VariantId::EnumVariantId(e) => ValueNs::EnumVariantId(e), - VariantId::StructId(s) => ValueNs::StructId(s), - VariantId::UnionId(_) => implementation_error!("Union variant as path"), + hir_def::AssocItemId::FunctionId(_) => { + // FnDefs are zero sized, no action is needed. + return Ok(Some(current)); } - } else { - let unresolved_name = - || MirLowerError::unresolved_path(self.db, p, self.edition()); - let resolver = resolver_for_expr(self.db.upcast(), self.owner, expr_id); - resolver - .resolve_path_in_value_ns_fully(self.db.upcast(), p) - .ok_or_else(unresolved_name)? - }; + hir_def::AssocItemId::TypeAliasId(_) => { + // FIXME: If it is unreachable, use proper error instead of `not_supported`. + not_supported!("associated functions and types") + } + } + } else if let Some(variant) = self.infer.variant_resolution_for_expr(expr_id) { + match variant { + VariantId::EnumVariantId(e) => ValueNs::EnumVariantId(e), + VariantId::StructId(s) => ValueNs::StructId(s), + VariantId::UnionId(_) => implementation_error!("Union variant as path"), + } + } else { + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); + let result = self + .resolver + .resolve_path_in_value_ns_fully(self.db.upcast(), p) + .ok_or_else(|| { + MirLowerError::unresolved_path(self.db, p, self.edition()) + })?; + self.resolver.reset_to_guard(resolver_guard); + result + }; match pr { ValueNs::LocalBinding(_) | ValueNs::StaticId(_) => { let Some((temp, current)) = @@ -553,8 +561,11 @@ impl<'ctx> MirLowerCtx<'ctx> { return Ok(None); }; self.push_fake_read(current, cond_place, expr_id.into()); + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); let (then_target, else_target) = self.pattern_match(current, None, cond_place, *pat)?; + self.resolver.reset_to_guard(resolver_guard); self.write_bytes_to_place( then_target, place, @@ -688,6 +699,8 @@ impl<'ctx> MirLowerCtx<'ctx> { }; self.push_fake_read(current, cond_place, expr_id.into()); let mut end = None; + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); for MatchArm { pat, guard, expr } in arms.iter() { let (then, mut otherwise) = self.pattern_match(current, None, cond_place, *pat)?; @@ -721,6 +734,7 @@ impl<'ctx> MirLowerCtx<'ctx> { } } } + self.resolver.reset_to_guard(resolver_guard); if self.is_unterminated(current) { self.set_terminator(current, TerminatorKind::Unreachable, expr_id.into()); } @@ -795,7 +809,7 @@ impl<'ctx> MirLowerCtx<'ctx> { } Expr::Become { .. } => not_supported!("tail-calls"), Expr::Yield { .. } => not_supported!("yield"), - Expr::RecordLit { fields, path, spread, ellipsis: _, is_assignee_expr: _ } => { + Expr::RecordLit { fields, path, spread } => { let spread_place = match spread { &Some(it) => { let Some((p, c)) = self.lower_expr_as_place(current, it, true)? else { @@ -1010,35 +1024,28 @@ impl<'ctx> MirLowerCtx<'ctx> { ); } } - if let hir_def::hir::BinaryOp::Assignment { op } = op { - if let Some(op) = op { - // last adjustment is `&mut` which we don't want it. - let adjusts = self - .infer - .expr_adjustments - .get(lhs) - .and_then(|it| it.split_last()) - .map(|it| it.1) - .ok_or(MirLowerError::TypeError( - "adjustment of binary op was missing", - ))?; - let Some((lhs_place, current)) = - self.lower_expr_as_place_with_adjust(current, *lhs, false, adjusts)? - else { - return Ok(None); - }; - let Some((rhs_op, current)) = - self.lower_expr_to_some_operand(*rhs, current)? - else { - return Ok(None); - }; - let r_value = - Rvalue::CheckedBinaryOp(op.into(), Operand::Copy(lhs_place), rhs_op); - self.push_assignment(current, lhs_place, r_value, expr_id.into()); - return Ok(Some(current)); - } else { - return self.lower_assignment(current, *lhs, *rhs, expr_id.into()); - } + if let hir_def::hir::BinaryOp::Assignment { op: Some(op) } = op { + // last adjustment is `&mut` which we don't want it. + let adjusts = self + .infer + .expr_adjustments + .get(lhs) + .and_then(|it| it.split_last()) + .map(|it| it.1) + .ok_or(MirLowerError::TypeError("adjustment of binary op was missing"))?; + let Some((lhs_place, current)) = + self.lower_expr_as_place_with_adjust(current, *lhs, false, adjusts)? + else { + return Ok(None); + }; + let Some((rhs_op, current)) = self.lower_expr_to_some_operand(*rhs, current)? + else { + return Ok(None); + }; + let r_value = + Rvalue::CheckedBinaryOp(op.into(), Operand::Copy(lhs_place), rhs_op); + self.push_assignment(current, lhs_place, r_value, expr_id.into()); + return Ok(Some(current)); } let Some((lhs_op, current)) = self.lower_expr_to_some_operand(*lhs, current)? else { @@ -1097,6 +1104,18 @@ impl<'ctx> MirLowerCtx<'ctx> { ); Ok(Some(current)) } + &Expr::Assignment { target, value } => { + let Some((value, mut current)) = self.lower_expr_as_place(current, value, true)? + else { + return Ok(None); + }; + self.push_fake_read(current, value, expr_id.into()); + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); + current = self.pattern_match_assignment(current, value, target)?; + self.resolver.reset_to_guard(resolver_guard); + Ok(Some(current)) + } &Expr::Range { lhs, rhs, range_type: _ } => { let ty = self.expr_ty_without_adjust(expr_id); let Some((adt, subst)) = ty.as_adt() else { @@ -1213,7 +1232,7 @@ impl<'ctx> MirLowerCtx<'ctx> { ); Ok(Some(current)) } - Expr::Tuple { exprs, is_assignee_expr: _ } => { + Expr::Tuple { exprs } => { let Some(values) = exprs .iter() .map(|it| { @@ -1291,73 +1310,6 @@ impl<'ctx> MirLowerCtx<'ctx> { } } - fn lower_destructing_assignment( - &mut self, - mut current: BasicBlockId, - lhs: ExprId, - rhs: Place, - span: MirSpan, - ) -> Result> { - match &self.body.exprs[lhs] { - Expr::Tuple { exprs, is_assignee_expr: _ } => { - for (i, expr) in exprs.iter().enumerate() { - let rhs = rhs.project( - ProjectionElem::Field(Either::Right(TupleFieldId { - tuple: TupleId(!0), // Dummy this as its unused - index: i as u32, - })), - &mut self.result.projection_store, - ); - let Some(c) = self.lower_destructing_assignment(current, *expr, rhs, span)? - else { - return Ok(None); - }; - current = c; - } - Ok(Some(current)) - } - Expr::Underscore => Ok(Some(current)), - _ => { - let Some((lhs_place, current)) = self.lower_expr_as_place(current, lhs, false)? - else { - return Ok(None); - }; - self.push_assignment(current, lhs_place, Operand::Copy(rhs).into(), span); - Ok(Some(current)) - } - } - } - - fn lower_assignment( - &mut self, - current: BasicBlockId, - lhs: ExprId, - rhs: ExprId, - span: MirSpan, - ) -> Result> { - let Some((rhs_op, current)) = self.lower_expr_to_some_operand(rhs, current)? else { - return Ok(None); - }; - if matches!(&self.body.exprs[lhs], Expr::Underscore) { - self.push_fake_read_for_operand(current, rhs_op, span); - return Ok(Some(current)); - } - if matches!( - &self.body.exprs[lhs], - Expr::Tuple { .. } | Expr::RecordLit { .. } | Expr::Call { .. } - ) { - let temp = self.temp(self.expr_ty_after_adjustments(rhs), current, rhs.into())?; - let temp = Place::from(temp); - self.push_assignment(current, temp, rhs_op.into(), span); - return self.lower_destructing_assignment(current, lhs, temp, span); - } - let Some((lhs_place, current)) = self.lower_expr_as_place(current, lhs, false)? else { - return Ok(None); - }; - self.push_assignment(current, lhs_place, rhs_op.into(), span); - Ok(Some(current)) - } - fn placeholder_subst(&mut self) -> Substitution { match self.owner.as_generic_def_id(self.db.upcast()) { Some(it) => TyBuilder::placeholder_subst(self.db, it), @@ -1407,8 +1359,8 @@ impl<'ctx> MirLowerCtx<'ctx> { let edition = self.edition(); let unresolved_name = || MirLowerError::unresolved_path(self.db, c.as_ref(), edition); - let resolver = self.owner.resolver(self.db.upcast()); - let pr = resolver + let pr = self + .resolver .resolve_path_in_value_ns(self.db.upcast(), c.as_ref()) .ok_or_else(unresolved_name)?; match pr { @@ -1632,12 +1584,6 @@ impl<'ctx> MirLowerCtx<'ctx> { self.push_statement(block, StatementKind::FakeRead(p).with_span(span)); } - fn push_fake_read_for_operand(&mut self, block: BasicBlockId, operand: Operand, span: MirSpan) { - if let Operand::Move(p) | Operand::Copy(p) = operand { - self.push_fake_read(block, p, span); - } - } - fn push_assignment( &mut self, block: BasicBlockId, @@ -1791,8 +1737,16 @@ impl<'ctx> MirLowerCtx<'ctx> { }; current = c; self.push_fake_read(current, init_place, span); + // Using the initializer for the resolver scope is good enough for us, as it cannot create new declarations + // and has all declarations of the `let`. + let resolver_guard = self.resolver.update_to_inner_scope( + self.db.upcast(), + self.owner, + *expr_id, + ); (current, else_block) = self.pattern_match(current, None, init_place, *pat)?; + self.resolver.reset_to_guard(resolver_guard); match (else_block, else_branch) { (None, _) => (), (Some(else_block), None) => { @@ -2066,11 +2020,13 @@ pub fn mir_body_for_closure_query( let Some(sig) = ClosureSubst(substs).sig_ty().callable_sig(db) else { implementation_error!("closure has not callable sig"); }; + let resolver_guard = ctx.resolver.update_to_inner_scope(db.upcast(), owner, expr); let current = ctx.lower_params_and_bindings( args.iter().zip(sig.params().iter()).map(|(it, y)| (*it, y.clone())), None, |_| true, )?; + ctx.resolver.reset_to_guard(resolver_guard); if let Some(current) = ctx.lower_expr_to_place(*root, return_slot().into(), current)? { let current = ctx.pop_drop_scope_assert_finished(current, root.into())?; ctx.set_terminator(current, TerminatorKind::Return, (*root).into()); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs index 424ee1160c82..91086e805798 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs @@ -135,8 +135,11 @@ impl MirLowerCtx<'_> { }; match &self.body.exprs[expr_id] { Expr::Path(p) => { - let resolver = resolver_for_expr(self.db.upcast(), self.owner, expr_id); - let Some(pr) = resolver.resolve_path_in_value_ns_fully(self.db.upcast(), p) else { + let resolver_guard = + self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); + let resolved = self.resolver.resolve_path_in_value_ns_fully(self.db.upcast(), p); + self.resolver.reset_to_guard(resolver_guard); + let Some(pr) = resolved else { return try_rvalue(self); }; match pr { @@ -216,7 +219,7 @@ impl MirLowerCtx<'_> { self.push_field_projection(&mut r, expr_id)?; Ok(Some((r, current))) } - Expr::Index { base, index, is_assignee_expr: _ } => { + Expr::Index { base, index } => { let base_ty = self.expr_ty_after_adjustments(*base); let index_ty = self.expr_ty_after_adjustments(*index); if index_ty != TyBuilder::usize() diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs index b1c0d1f2b390..63bb3367771f 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -1,6 +1,6 @@ //! MIR lowering for patterns -use hir_def::{hir::LiteralOrConst, resolver::HasResolver, AssocItemId}; +use hir_def::{hir::LiteralOrConst, AssocItemId}; use crate::{ mir::{ @@ -46,6 +46,8 @@ enum MatchingMode { Check, /// Assume that this pattern matches, fill bindings Bind, + /// Assume that this pattern matches, assign to existing variables. + Assign, } impl MirLowerCtx<'_> { @@ -82,6 +84,17 @@ impl MirLowerCtx<'_> { Ok((current, current_else)) } + pub(super) fn pattern_match_assignment( + &mut self, + current: BasicBlockId, + value: Place, + pattern: PatId, + ) -> Result { + let (current, _) = + self.pattern_match_inner(current, None, value, pattern, MatchingMode::Assign)?; + Ok(current) + } + pub(super) fn match_self_param( &mut self, id: BindingId, @@ -155,14 +168,8 @@ impl MirLowerCtx<'_> { *pat, MatchingMode::Check, )?; - if mode == MatchingMode::Bind { - (next, _) = self.pattern_match_inner( - next, - None, - cond_place, - *pat, - MatchingMode::Bind, - )?; + if mode != MatchingMode::Check { + (next, _) = self.pattern_match_inner(next, None, cond_place, *pat, mode)?; } self.set_goto(next, then_target, pattern.into()); match next_else { @@ -176,11 +183,11 @@ impl MirLowerCtx<'_> { } } if !finished { - if mode == MatchingMode::Bind { - self.set_terminator(current, TerminatorKind::Unreachable, pattern.into()); - } else { + if mode == MatchingMode::Check { let ce = *current_else.get_or_insert_with(|| self.new_basic_block()); self.set_goto(current, ce, pattern.into()); + } else { + self.set_terminator(current, TerminatorKind::Unreachable, pattern.into()); } } (then_target, current_else) @@ -300,7 +307,7 @@ impl MirLowerCtx<'_> { self.pattern_match_inner(current, current_else, next_place, pat, mode)?; } if let &Some(slice) = slice { - if mode == MatchingMode::Bind { + if mode != MatchingMode::Check { if let Pat::Bind { id, subpat: _ } = self.body[slice] { let next_place = cond_place.project( ProjectionElem::Subslice { @@ -342,17 +349,34 @@ impl MirLowerCtx<'_> { mode, )?, None => { - // The path is not a variant, so it is a const + let unresolved_name = + || MirLowerError::unresolved_path(self.db, p, self.edition()); + let pr = self + .resolver + .resolve_path_in_value_ns(self.db.upcast(), p) + .ok_or_else(unresolved_name)?; + + if let ( + MatchingMode::Assign, + ResolveValueResult::ValueNs(ValueNs::LocalBinding(binding), _), + ) = (mode, &pr) + { + let local = self.binding_local(*binding)?; + self.push_match_assignment( + current, + local, + BindingMode::Move, + cond_place, + pattern.into(), + ); + return Ok((current, current_else)); + } + + // The path is not a variant or a local, so it is a const if mode != MatchingMode::Check { // A const don't bind anything. Only needs check. return Ok((current, current_else)); } - let unresolved_name = - || MirLowerError::unresolved_path(self.db, p, self.edition()); - let resolver = self.owner.resolver(self.db.upcast()); - let pr = resolver - .resolve_path_in_value_ns(self.db.upcast(), p) - .ok_or_else(unresolved_name)?; let (c, subst) = 'b: { if let Some(x) = self.infer.assoc_resolutions_for_pat(pattern) { if let AssocItemId::ConstId(c) = x.0 { @@ -415,7 +439,7 @@ impl MirLowerCtx<'_> { (current, current_else) = self.pattern_match_inner(current, current_else, cond_place, *subpat, mode)? } - if mode == MatchingMode::Bind { + if mode != MatchingMode::Check { let mode = self.infer.binding_modes[pattern]; self.pattern_match_binding( *id, @@ -448,6 +472,23 @@ impl MirLowerCtx<'_> { cond_place.project(ProjectionElem::Deref, &mut self.result.projection_store); self.pattern_match_inner(current, current_else, cond_place, *pat, mode)? } + &Pat::Expr(expr) => { + stdx::always!( + mode == MatchingMode::Assign, + "Pat::Expr can only come in destructuring assignments" + ); + let Some((lhs_place, current)) = self.lower_expr_as_place(current, expr, false)? + else { + return Ok((current, current_else)); + }; + self.push_assignment( + current, + lhs_place, + Operand::Copy(cond_place).into(), + expr.into(), + ); + (current, current_else) + } Pat::Box { .. } => not_supported!("box pattern"), Pat::ConstBlock(_) => not_supported!("const block pattern"), }) @@ -464,6 +505,18 @@ impl MirLowerCtx<'_> { ) -> Result<(BasicBlockId, Option)> { let target_place = self.binding_local(id)?; self.push_storage_live(id, current)?; + self.push_match_assignment(current, target_place, mode, cond_place, span); + Ok((current, current_else)) + } + + fn push_match_assignment( + &mut self, + current: BasicBlockId, + target_place: LocalId, + mode: BindingMode, + cond_place: Place, + span: MirSpan, + ) { self.push_assignment( current, target_place.into(), @@ -476,7 +529,6 @@ impl MirLowerCtx<'_> { }, span, ); - Ok((current, current_else)) } fn pattern_match_const( diff --git a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs index 0b3cdb2f3790..24c1b80bdf16 100644 --- a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs @@ -246,7 +246,7 @@ pub struct UnresolvedAssocItem { #[derive(Debug)] pub struct UnresolvedIdent { - pub expr: InFile>, + pub expr_or_pat: InFile>>, } #[derive(Debug)] @@ -541,6 +541,10 @@ impl AnyDiagnostic { let pat_syntax = |pat| { source_map.pat_syntax(pat).inspect_err(|_| tracing::error!("synthetic syntax")).ok() }; + let expr_or_pat_syntax = |id| match id { + ExprOrPatId::ExprId(expr) => expr_syntax(expr).map(|it| it.map(AstPtr::wrap_left)), + ExprOrPatId::PatId(pat) => pat_syntax(pat).map(|it| it.map(AstPtr::wrap_right)), + }; Some(match d { &InferenceDiagnostic::NoSuchField { field: expr, private, variant } => { let expr_or_pat = match expr { @@ -562,10 +566,7 @@ impl AnyDiagnostic { PrivateField { expr, field }.into() } &InferenceDiagnostic::PrivateAssocItem { id, item } => { - let expr_or_pat = match id { - ExprOrPatId::ExprId(expr) => expr_syntax(expr)?.map(AstPtr::wrap_left), - ExprOrPatId::PatId(pat) => pat_syntax(pat)?.map(AstPtr::wrap_right), - }; + let expr_or_pat = expr_or_pat_syntax(id)?; let item = item.into(); PrivateAssocItem { expr_or_pat, item }.into() } @@ -609,15 +610,12 @@ impl AnyDiagnostic { .into() } &InferenceDiagnostic::UnresolvedAssocItem { id } => { - let expr_or_pat = match id { - ExprOrPatId::ExprId(expr) => expr_syntax(expr)?.map(AstPtr::wrap_left), - ExprOrPatId::PatId(pat) => pat_syntax(pat)?.map(AstPtr::wrap_right), - }; + let expr_or_pat = expr_or_pat_syntax(id)?; UnresolvedAssocItem { expr_or_pat }.into() } - &InferenceDiagnostic::UnresolvedIdent { expr } => { - let expr = expr_syntax(expr)?; - UnresolvedIdent { expr }.into() + &InferenceDiagnostic::UnresolvedIdent { id } => { + let expr_or_pat = expr_or_pat_syntax(id)?; + UnresolvedIdent { expr_or_pat }.into() } &InferenceDiagnostic::BreakOutsideOfLoop { expr, is_break, bad_value_break } => { let expr = expr_syntax(expr)?; diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs index b982d1041fe3..dfd586402513 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -1275,4 +1275,19 @@ fn main() { "#, ); } + + #[test] + fn destructuring_assignment_needs_mut() { + check_diagnostics( + r#" +//- minicore: fn + +fn main() { + let mut var = 1; + let mut func = || (var,) = (2,); + func(); +} + "#, + ); + } } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_ident.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_ident.rs index 9a81682aaeba..68f14a97f594 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_ident.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_ident.rs @@ -11,7 +11,7 @@ pub(crate) fn unresolved_ident( ctx, DiagnosticCode::RustcHardError("E0425"), "no such value in this scope", - d.expr.map(Into::into), + d.expr_or_pat.map(Into::into), ) .experimental() } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/expr_ext.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/expr_ext.rs index 6ed205e2856f..f3053f59836f 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/expr_ext.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/expr_ext.rs @@ -232,6 +232,10 @@ impl ast::RangeExpr { Some((ix, token, bin_op)) }) } + + pub fn is_range_full(&self) -> bool { + support::children::(&self.syntax).next().is_none() + } } impl RangeItem for ast::RangeExpr { From fc5912bcee7c5b65a62d735eb6c723a45ba783b7 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 6 Oct 2024 22:52:56 +0300 Subject: [PATCH 063/366] Store patterns desugared from destructuring assignments in source map And few more fixups. I was worried this will lead to more memory usage since `ExprOrPatId` is double the size of `ExprId`, but this does not regress `analysis-stats .`. If this turns out to be a problem, we can easily use the high bit to encode this information. --- .../rust-analyzer/crates/hir-def/src/body.rs | 57 +++++++----- .../crates/hir-def/src/body/lower.rs | 50 ++++++----- .../crates/hir-def/src/body/scope.rs | 9 +- .../rust-analyzer/crates/hir-def/src/hir.rs | 16 ++++ .../crates/hir-def/src/test_db.rs | 5 +- .../hir-ty/src/diagnostics/unsafe_check.rs | 45 ++++++---- .../rust-analyzer/crates/hir-ty/src/infer.rs | 29 ++++++ .../crates/hir-ty/src/tests/simple.rs | 4 +- .../crates/hir/src/diagnostics.rs | 90 ++++++++----------- src/tools/rust-analyzer/crates/hir/src/lib.rs | 16 ++-- .../rust-analyzer/crates/hir/src/semantics.rs | 6 +- .../crates/hir/src/semantics/source_to_def.rs | 5 +- .../crates/hir/src/source_analyzer.rs | 84 ++++++++++------- .../src/handlers/missing_fields.rs | 5 ++ .../src/handlers/missing_unsafe.rs | 3 +- .../src/handlers/mutability_errors.rs | 30 +++++-- 16 files changed, 280 insertions(+), 174 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body.rs b/src/tools/rust-analyzer/crates/hir-def/src/body.rs index d843ac1cad24..684eaf1c3b08 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body.rs @@ -10,6 +10,7 @@ use std::ops::{Deref, Index}; use base_db::CrateId; use cfg::{CfgExpr, CfgOptions}; +use either::Either; use hir_expand::{name::Name, ExpandError, InFile}; use la_arena::{Arena, ArenaMap, Idx, RawIdx}; use rustc_hash::FxHashMap; @@ -22,8 +23,8 @@ use crate::{ db::DefDatabase, expander::Expander, hir::{ - dummy_expr_id, Array, AsmOperand, Binding, BindingId, Expr, ExprId, Label, LabelId, Pat, - PatId, RecordFieldPat, Statement, + dummy_expr_id, Array, AsmOperand, Binding, BindingId, Expr, ExprId, ExprOrPatId, Label, + LabelId, Pat, PatId, RecordFieldPat, Statement, }, item_tree::AttrOwner, nameres::DefMap, @@ -68,9 +69,12 @@ pub type LabelSource = InFile; pub type FieldPtr = AstPtr; pub type FieldSource = InFile; -pub type PatFieldPtr = AstPtr; +pub type PatFieldPtr = AstPtr>; pub type PatFieldSource = InFile; +pub type ExprOrPatPtr = AstPtr>; +pub type ExprOrPatSource = InFile; + /// An item body together with the mapping from syntax nodes to HIR expression /// IDs. This is needed to go from e.g. a position in a file to the HIR /// expression containing it; but for type inference etc., we want to operate on @@ -84,11 +88,13 @@ pub type PatFieldSource = InFile; /// this properly for macros. #[derive(Default, Debug, Eq, PartialEq)] pub struct BodySourceMap { - expr_map: FxHashMap, + // AST expressions can create patterns in destructuring assignments. Therefore, `ExprSource` can also map + // to `PatId`, and `PatId` can also map to `ExprSource` (the other way around is unaffected). + expr_map: FxHashMap, expr_map_back: ArenaMap, pat_map: FxHashMap, - pat_map_back: ArenaMap, + pat_map_back: ArenaMap, label_map: FxHashMap, label_map_back: ArenaMap, @@ -372,7 +378,7 @@ impl Body { if let &Some(expr) = else_branch { f(expr); } - walk_exprs_in_pat(self, *pat, &mut f); + self.walk_exprs_in_pat(*pat, &mut f); } Statement::Expr { expr: expression, .. } => f(*expression), Statement::Item => (), @@ -448,18 +454,18 @@ impl Body { } }, &Expr::Assignment { target, value } => { - walk_exprs_in_pat(self, target, &mut f); + self.walk_exprs_in_pat(target, &mut f); f(value); } } + } - fn walk_exprs_in_pat(this: &Body, pat_id: PatId, f: &mut impl FnMut(ExprId)) { - this.walk_pats(pat_id, &mut |pat| { - if let Pat::Expr(expr) | Pat::ConstBlock(expr) = this[pat] { - f(expr); - } - }); - } + pub fn walk_exprs_in_pat(&self, pat_id: PatId, f: &mut impl FnMut(ExprId)) { + self.walk_pats(pat_id, &mut |pat| { + if let Pat::Expr(expr) | Pat::ConstBlock(expr) = self[pat] { + f(expr); + } + }); } } @@ -514,11 +520,18 @@ impl Index for Body { // FIXME: Change `node_` prefix to something more reasonable. // Perhaps `expr_syntax` and `expr_id`? impl BodySourceMap { + pub fn expr_or_pat_syntax(&self, id: ExprOrPatId) -> Result { + match id { + ExprOrPatId::ExprId(id) => self.expr_syntax(id).map(|it| it.map(AstPtr::wrap_left)), + ExprOrPatId::PatId(id) => self.pat_syntax(id), + } + } + pub fn expr_syntax(&self, expr: ExprId) -> Result { self.expr_map_back.get(expr).cloned().ok_or(SyntheticSyntax) } - pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option { + pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option { let src = node.map(AstPtr::new); self.expr_map.get(&src).cloned() } @@ -534,7 +547,7 @@ impl BodySourceMap { self.expansions.iter().map(|(&a, &b)| (a, b)) } - pub fn pat_syntax(&self, pat: PatId) -> Result { + pub fn pat_syntax(&self, pat: PatId) -> Result { self.pat_map_back.get(pat).cloned().ok_or(SyntheticSyntax) } @@ -567,7 +580,7 @@ impl BodySourceMap { self.pat_field_map_back[&pat] } - pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroExpr>) -> Option { + pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroExpr>) -> Option { let src = node.map(AstPtr::new).map(AstPtr::upcast::).map(AstPtr::upcast); self.expr_map.get(&src).copied() } @@ -583,7 +596,11 @@ impl BodySourceMap { node: InFile<&ast::FormatArgsExpr>, ) -> Option<&[(syntax::TextRange, Name)]> { let src = node.map(AstPtr::new).map(AstPtr::upcast::); - self.template_map.as_ref()?.0.get(self.expr_map.get(&src)?).map(std::ops::Deref::deref) + self.template_map + .as_ref()? + .0 + .get(&self.expr_map.get(&src)?.as_expr()?) + .map(std::ops::Deref::deref) } pub fn asm_template_args( @@ -591,8 +608,8 @@ impl BodySourceMap { node: InFile<&ast::AsmExpr>, ) -> Option<(ExprId, &[Vec<(syntax::TextRange, usize)>])> { let src = node.map(AstPtr::new).map(AstPtr::upcast::); - let expr = self.expr_map.get(&src)?; - Some(*expr).zip(self.template_map.as_ref()?.1.get(expr).map(std::ops::Deref::deref)) + let expr = self.expr_map.get(&src)?.as_expr()?; + Some(expr).zip(self.template_map.as_ref()?.1.get(&expr).map(std::ops::Deref::deref)) } /// Get a reference to the body source map's diagnostics. diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index 3dff6ecd756c..4b74028b83a6 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -424,7 +424,7 @@ impl ExprCollector<'_> { let inner = self.collect_expr_opt(e.expr()); // make the paren expr point to the inner expression as well for IDE resolution let src = self.expander.in_file(syntax_ptr); - self.source_map.expr_map.insert(src, inner); + self.source_map.expr_map.insert(src, inner.into()); inner } ast::Expr::ReturnExpr(e) => { @@ -660,7 +660,7 @@ impl ExprCollector<'_> { // Make the macro-call point to its expanded expression so we can query // semantics on syntax pointers to the macro let src = self.expander.in_file(syntax_ptr); - self.source_map.expr_map.insert(src, id); + self.source_map.expr_map.insert(src, id.into()); id } None => self.alloc_expr(Expr::Missing, syntax_ptr), @@ -686,9 +686,12 @@ impl ExprCollector<'_> { fn collect_expr_as_pat(&mut self, expr: ast::Expr) -> PatId { self.maybe_collect_expr_as_pat(&expr).unwrap_or_else(|| { - let syntax_ptr = AstPtr::new(&expr); + let src = self.expander.in_file(AstPtr::new(&expr).wrap_left()); let expr = self.collect_expr(expr); - self.alloc_pat_from_expr(Pat::Expr(expr), syntax_ptr) + // Do not use `alloc_pat_from_expr()` here, it will override the entry in `expr_map`. + let id = self.body.pats.alloc(Pat::Expr(expr)); + self.source_map.pat_map_back.insert(id, src); + id }) } @@ -743,16 +746,12 @@ impl ExprCollector<'_> { ast::Expr::MacroExpr(e) => { let e = e.macro_call()?; let macro_ptr = AstPtr::new(&e); + let src = self.expander.in_file(AstPtr::new(expr)); let id = self.collect_macro_call(e, macro_ptr, true, |this, expansion| { - expansion.map(|it| this.collect_expr_as_pat(it)) + this.collect_expr_as_pat_opt(expansion) }); - match id { - Some(id) => { - // FIXME: Insert pat into source map. - id - } - None => self.alloc_pat_from_expr(Pat::Missing, syntax_ptr), - } + self.source_map.expr_map.insert(src, id.into()); + id } ast::Expr::RecordExpr(e) => { let path = @@ -767,9 +766,8 @@ impl ExprCollector<'_> { let field_expr = f.expr()?; let pat = self.collect_expr_as_pat(field_expr); let name = f.field_name()?.as_name(); - // FIXME: Enable this. - // let src = self.expander.in_file(AstPtr::new(&f)); - // self.source_map.pat_field_map_back.insert(pat, src); + let src = self.expander.in_file(AstPtr::new(&f).wrap_left()); + self.source_map.pat_field_map_back.insert(pat, src); Some(RecordFieldPat { name, pat }) }) .collect(); @@ -813,7 +811,10 @@ impl ExprCollector<'_> { None => Either::Left(this.missing_pat()), }, ); - // FIXME: Insert pat into source map. + if let Either::Left(pat) = pat { + let src = this.expander.in_file(AstPtr::new(&expr).wrap_left()); + this.source_map.pat_map_back.insert(pat, src); + } pat } None => { @@ -1236,7 +1237,7 @@ impl ExprCollector<'_> { // Make the macro-call point to its expanded expression so we can query // semantics on syntax pointers to the macro let src = self.expander.in_file(syntax_ptr); - self.source_map.expr_map.insert(src, tail); + self.source_map.expr_map.insert(src, tail.into()); }) } @@ -1500,7 +1501,7 @@ impl ExprCollector<'_> { let ast_pat = f.pat()?; let pat = self.collect_pat(ast_pat, binding_list); let name = f.field_name()?.as_name(); - let src = self.expander.in_file(AstPtr::new(&f)); + let src = self.expander.in_file(AstPtr::new(&f).wrap_right()); self.source_map.pat_field_map_back.insert(pat, src); Some(RecordFieldPat { name, pat }) }) @@ -2187,7 +2188,7 @@ impl ExprCollector<'_> { let src = self.expander.in_file(ptr); let id = self.body.exprs.alloc(expr); self.source_map.expr_map_back.insert(id, src); - self.source_map.expr_map.insert(src, id); + self.source_map.expr_map.insert(src, id.into()); id } // FIXME: desugared exprs don't have ptr, that's wrong and should be fixed. @@ -2215,14 +2216,17 @@ impl ExprCollector<'_> { binding } - fn alloc_pat_from_expr(&mut self, pat: Pat, _ptr: ExprPtr) -> PatId { - // FIXME: Insert into source map. - self.body.pats.alloc(pat) + fn alloc_pat_from_expr(&mut self, pat: Pat, ptr: ExprPtr) -> PatId { + let src = self.expander.in_file(ptr); + let id = self.body.pats.alloc(pat); + self.source_map.expr_map.insert(src, id.into()); + self.source_map.pat_map_back.insert(id, src.map(AstPtr::wrap_left)); + id } fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId { let src = self.expander.in_file(ptr); let id = self.body.pats.alloc(pat); - self.source_map.pat_map_back.insert(id, src); + self.source_map.pat_map_back.insert(id, src.map(AstPtr::wrap_right)); self.source_map.pat_map.insert(src, id); id } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs index 56d6ed233099..c6967961b33f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs @@ -333,6 +333,8 @@ mod tests { let expr_id = source_map .node_expr(InFile { file_id: file_id.into(), value: &marker.into() }) + .unwrap() + .as_expr() .unwrap(); let scope = scopes.scope_for(expr_id); @@ -488,8 +490,11 @@ fn foo() { let expr_scope = { let expr_ast = name_ref.syntax().ancestors().find_map(ast::Expr::cast).unwrap(); - let expr_id = - source_map.node_expr(InFile { file_id: file_id.into(), value: &expr_ast }).unwrap(); + let expr_id = source_map + .node_expr(InFile { file_id: file_id.into(), value: &expr_ast }) + .unwrap() + .as_expr() + .unwrap(); scopes.scope_for(expr_id).unwrap() }; diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs index 3c62b04f97ef..a575a2d19913 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs @@ -48,6 +48,22 @@ pub enum ExprOrPatId { ExprId(ExprId), PatId(PatId), } + +impl ExprOrPatId { + pub fn as_expr(self) -> Option { + match self { + Self::ExprId(v) => Some(v), + _ => None, + } + } + + pub fn as_pat(self) -> Option { + match self { + Self::PatId(v) => Some(v), + _ => None, + } + } +} stdx::impl_from!(ExprId, PatId for ExprOrPatId); #[derive(Debug, Clone, Eq, PartialEq)] diff --git a/src/tools/rust-analyzer/crates/hir-def/src/test_db.rs b/src/tools/rust-analyzer/crates/hir-def/src/test_db.rs index 4db21eb46bd5..0c36c88fb093 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/test_db.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/test_db.rs @@ -198,7 +198,10 @@ impl TestDB { .filter_map(|node| { let block = ast::BlockExpr::cast(node)?; let expr = ast::Expr::from(block); - let expr_id = source_map.node_expr(InFile::new(position.file_id.into(), &expr))?; + let expr_id = source_map + .node_expr(InFile::new(position.file_id.into(), &expr))? + .as_expr() + .unwrap(); let scope = scopes.scope_for(expr_id).unwrap(); Some(scope) }); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs index f610c9e96c8c..492262c7a4cf 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -3,7 +3,7 @@ use hir_def::{ body::Body, - hir::{Expr, ExprId, UnaryOp}, + hir::{Expr, ExprId, ExprOrPatId, Pat, UnaryOp}, resolver::{resolver_for_expr, ResolveValueResult, Resolver, ValueNs}, type_ref::Rawness, DefWithBodyId, @@ -16,7 +16,7 @@ use crate::{ /// Returns `(unsafe_exprs, fn_is_unsafe)`. /// /// If `fn_is_unsafe` is false, `unsafe_exprs` are hard errors. If true, they're `unsafe_op_in_unsafe_fn`. -pub fn missing_unsafe(db: &dyn HirDatabase, def: DefWithBodyId) -> (Vec, bool) { +pub fn missing_unsafe(db: &dyn HirDatabase, def: DefWithBodyId) -> (Vec, bool) { let _p = tracing::info_span!("missing_unsafe").entered(); let mut res = Vec::new(); @@ -32,7 +32,7 @@ pub fn missing_unsafe(db: &dyn HirDatabase, def: DefWithBodyId) -> (Vec, let infer = db.infer(def); unsafe_expressions(db, &infer, def, &body, body.body_expr, &mut |expr| { if !expr.inside_unsafe_block { - res.push(expr.expr); + res.push(expr.node); } }); @@ -40,7 +40,7 @@ pub fn missing_unsafe(db: &dyn HirDatabase, def: DefWithBodyId) -> (Vec, } pub struct UnsafeExpr { - pub expr: ExprId, + pub node: ExprOrPatId, pub inside_unsafe_block: bool, } @@ -75,26 +75,28 @@ fn walk_unsafe( inside_unsafe_block: bool, unsafe_expr_cb: &mut dyn FnMut(UnsafeExpr), ) { + let mut mark_unsafe_path = |path, node| { + let g = resolver.update_to_inner_scope(db.upcast(), def, current); + let value_or_partial = resolver.resolve_path_in_value_ns(db.upcast(), path); + if let Some(ResolveValueResult::ValueNs(ValueNs::StaticId(id), _)) = value_or_partial { + let static_data = db.static_data(id); + if static_data.mutable || (static_data.is_extern && !static_data.has_safe_kw) { + unsafe_expr_cb(UnsafeExpr { node, inside_unsafe_block }); + } + } + resolver.reset_to_guard(g); + }; + let expr = &body.exprs[current]; match expr { &Expr::Call { callee, .. } => { if let Some(func) = infer[callee].as_fn_def(db) { if is_fn_unsafe_to_call(db, func) { - unsafe_expr_cb(UnsafeExpr { expr: current, inside_unsafe_block }); + unsafe_expr_cb(UnsafeExpr { node: current.into(), inside_unsafe_block }); } } } - Expr::Path(path) => { - let g = resolver.update_to_inner_scope(db.upcast(), def, current); - let value_or_partial = resolver.resolve_path_in_value_ns(db.upcast(), path); - if let Some(ResolveValueResult::ValueNs(ValueNs::StaticId(id), _)) = value_or_partial { - let static_data = db.static_data(id); - if static_data.mutable || (static_data.is_extern && !static_data.has_safe_kw) { - unsafe_expr_cb(UnsafeExpr { expr: current, inside_unsafe_block }); - } - } - resolver.reset_to_guard(g); - } + Expr::Path(path) => mark_unsafe_path(path, current.into()), Expr::Ref { expr, rawness: Rawness::RawPtr, mutability: _ } => { if let Expr::Path(_) = body.exprs[*expr] { // Do not report unsafe for `addr_of[_mut]!(EXTERN_OR_MUT_STATIC)`, @@ -108,12 +110,12 @@ fn walk_unsafe( .map(|(func, _)| is_fn_unsafe_to_call(db, func)) .unwrap_or(false) { - unsafe_expr_cb(UnsafeExpr { expr: current, inside_unsafe_block }); + unsafe_expr_cb(UnsafeExpr { node: current.into(), inside_unsafe_block }); } } Expr::UnaryOp { expr, op: UnaryOp::Deref } => { if let TyKind::Raw(..) = &infer[*expr].kind(Interner) { - unsafe_expr_cb(UnsafeExpr { expr: current, inside_unsafe_block }); + unsafe_expr_cb(UnsafeExpr { node: current.into(), inside_unsafe_block }); } } Expr::Unsafe { .. } => { @@ -121,6 +123,13 @@ fn walk_unsafe( walk_unsafe(db, infer, body, resolver, def, child, true, unsafe_expr_cb); }); } + &Expr::Assignment { target, value: _ } => { + body.walk_pats(target, &mut |pat| { + if let Pat::Path(path) = &body[pat] { + mark_unsafe_path(path, pat.into()); + } + }); + } _ => {} } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index f2c860c9eb73..db16899d9f94 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -482,12 +482,27 @@ impl InferenceResult { pub fn variant_resolution_for_pat(&self, id: PatId) -> Option { self.variant_resolutions.get(&id.into()).copied() } + pub fn variant_resolution_for_expr_or_pat(&self, id: ExprOrPatId) -> Option { + match id { + ExprOrPatId::ExprId(id) => self.variant_resolution_for_expr(id), + ExprOrPatId::PatId(id) => self.variant_resolution_for_pat(id), + } + } pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<(AssocItemId, Substitution)> { self.assoc_resolutions.get(&id.into()).cloned() } pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<(AssocItemId, Substitution)> { self.assoc_resolutions.get(&id.into()).cloned() } + pub fn assoc_resolutions_for_expr_or_pat( + &self, + id: ExprOrPatId, + ) -> Option<(AssocItemId, Substitution)> { + match id { + ExprOrPatId::ExprId(id) => self.assoc_resolutions_for_expr(id), + ExprOrPatId::PatId(id) => self.assoc_resolutions_for_pat(id), + } + } pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { self.type_mismatches.get(&expr.into()) } @@ -506,6 +521,12 @@ impl InferenceResult { pub fn closure_info(&self, closure: &ClosureId) -> &(Vec, FnTrait) { self.closure_info.get(closure).unwrap() } + pub fn type_of_expr_or_pat(&self, id: ExprOrPatId) -> Option<&Ty> { + match id { + ExprOrPatId::ExprId(id) => self.type_of_expr.get(id), + ExprOrPatId::PatId(id) => self.type_of_pat.get(id), + } + } } impl Index for InferenceResult { @@ -524,6 +545,14 @@ impl Index for InferenceResult { } } +impl Index for InferenceResult { + type Output = Ty; + + fn index(&self, id: ExprOrPatId) -> &Ty { + self.type_of_expr_or_pat(id).unwrap_or(&self.standard_types.unknown) + } +} + impl Index for InferenceResult { type Output = Ty; diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs b/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs index a8170b606060..e6ef56b80d93 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs @@ -3418,11 +3418,11 @@ struct TS(usize); fn main() { let x; [x,] = &[1,]; - //^^^^expected &'? [i32; 1], got [{unknown}; _] + //^^^^expected &'? [i32; 1], got [{unknown}] let x; [(x,),] = &[(1,),]; - //^^^^^^^expected &'? [(i32,); 1], got [{unknown}; _] + //^^^^^^^expected &'? [(i32,); 1], got [{unknown}] let x; ((x,),) = &((1,),); diff --git a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs index 24c1b80bdf16..2fedffe047db 100644 --- a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs @@ -257,7 +257,7 @@ pub struct PrivateField { #[derive(Debug)] pub struct MissingUnsafe { - pub expr: InFile>, + pub expr: InFile>>, /// If true, the diagnostics is an `unsafe_op_in_unsafe_fn` lint instead of a hard error. pub only_lint: bool, } @@ -398,56 +398,46 @@ impl AnyDiagnostic { .map(|idx| variant_data.fields()[idx].name.clone()) .collect(); - match record { - Either::Left(record_expr) => match source_map.expr_syntax(record_expr) { - Ok(source_ptr) => { - let root = source_ptr.file_syntax(db.upcast()); - if let ast::Expr::RecordExpr(record_expr) = - source_ptr.value.to_node(&root) - { - if record_expr.record_expr_field_list().is_some() { - let field_list_parent_path = - record_expr.path().map(|path| AstPtr::new(&path)); - return Some( - MissingFields { - file: source_ptr.file_id, - field_list_parent: AstPtr::new(&Either::Left( - record_expr, - )), - field_list_parent_path, - missed_fields, - } - .into(), - ); + let record = match record { + Either::Left(record_expr) => { + source_map.expr_syntax(record_expr).ok()?.map(AstPtr::wrap_left) + } + Either::Right(record_pat) => source_map.pat_syntax(record_pat).ok()?, + }; + let file = record.file_id; + let root = record.file_syntax(db.upcast()); + match record.value.to_node(&root) { + Either::Left(ast::Expr::RecordExpr(record_expr)) => { + if record_expr.record_expr_field_list().is_some() { + let field_list_parent_path = + record_expr.path().map(|path| AstPtr::new(&path)); + return Some( + MissingFields { + file, + field_list_parent: AstPtr::new(&Either::Left(record_expr)), + field_list_parent_path, + missed_fields, } - } + .into(), + ); } - Err(SyntheticSyntax) => (), - }, - Either::Right(record_pat) => match source_map.pat_syntax(record_pat) { - Ok(source_ptr) => { - if let Some(ptr) = source_ptr.value.cast::() { - let root = source_ptr.file_syntax(db.upcast()); - let record_pat = ptr.to_node(&root); - if record_pat.record_pat_field_list().is_some() { - let field_list_parent_path = - record_pat.path().map(|path| AstPtr::new(&path)); - return Some( - MissingFields { - file: source_ptr.file_id, - field_list_parent: AstPtr::new(&Either::Right( - record_pat, - )), - field_list_parent_path, - missed_fields, - } - .into(), - ); + } + Either::Right(ast::Pat::RecordPat(record_pat)) => { + if record_pat.record_pat_field_list().is_some() { + let field_list_parent_path = + record_pat.path().map(|path| AstPtr::new(&path)); + return Some( + MissingFields { + file, + field_list_parent: AstPtr::new(&Either::Right(record_pat)), + field_list_parent_path, + missed_fields, } - } + .into(), + ); } - Err(SyntheticSyntax) => (), - }, + } + _ => {} } } BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => { @@ -543,7 +533,7 @@ impl AnyDiagnostic { }; let expr_or_pat_syntax = |id| match id { ExprOrPatId::ExprId(expr) => expr_syntax(expr).map(|it| it.map(AstPtr::wrap_left)), - ExprOrPatId::PatId(pat) => pat_syntax(pat).map(|it| it.map(AstPtr::wrap_right)), + ExprOrPatId::PatId(pat) => pat_syntax(pat), }; Some(match d { &InferenceDiagnostic::NoSuchField { field: expr, private, variant } => { @@ -551,9 +541,7 @@ impl AnyDiagnostic { ExprOrPatId::ExprId(expr) => { source_map.field_syntax(expr).map(AstPtr::wrap_left) } - ExprOrPatId::PatId(pat) => { - source_map.pat_field_syntax(pat).map(AstPtr::wrap_right) - } + ExprOrPatId::PatId(pat) => source_map.pat_field_syntax(pat), }; NoSuchField { field: expr_or_pat, private, variant }.into() } diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index 30e023e1a472..4a18795e7d62 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -1885,7 +1885,7 @@ impl DefWithBody { let (unafe_exprs, only_lint) = hir_ty::diagnostics::missing_unsafe(db, self.into()); for expr in unafe_exprs { - match source_map.expr_syntax(expr) { + match source_map.expr_or_pat_syntax(expr) { Ok(expr) => acc.push(MissingUnsafe { expr, only_lint }.into()), Err(SyntheticSyntax) => { // FIXME: Here and elsewhere in this file, the `expr` was @@ -3481,7 +3481,7 @@ impl Local { LocalSource { local: self, source: src.map(|ast| match ast.to_node(&root) { - ast::Pat::IdentPat(it) => Either::Left(it), + Either::Right(ast::Pat::IdentPat(it)) => Either::Left(it), _ => unreachable!("local with non ident-pattern"), }), } @@ -3510,7 +3510,7 @@ impl Local { LocalSource { local: self, source: src.map(|ast| match ast.to_node(&root) { - ast::Pat::IdentPat(it) => Either::Left(it), + Either::Right(ast::Pat::IdentPat(it)) => Either::Left(it), _ => unreachable!("local with non ident-pattern"), }), } @@ -4235,10 +4235,7 @@ impl CaptureUsages { } mir::MirSpan::PatId(pat) => { if let Ok(pat) = source_map.pat_syntax(pat) { - result.push(CaptureUsageSource { - is_ref, - source: pat.map(AstPtr::wrap_right), - }); + result.push(CaptureUsageSource { is_ref, source: pat }); } } mir::MirSpan::BindingId(binding) => result.extend( @@ -4246,10 +4243,7 @@ impl CaptureUsages { .patterns_for_binding(binding) .iter() .filter_map(|&pat| source_map.pat_syntax(pat).ok()) - .map(|pat| CaptureUsageSource { - is_ref, - source: pat.map(AstPtr::wrap_right), - }), + .map(|pat| CaptureUsageSource { is_ref, source: pat }), ), mir::MirSpan::SelfParam | mir::MirSpan::Unknown => { unreachable!("invalid capture usage span") diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index b27f1fbb5db1..d210c2671435 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -11,7 +11,7 @@ use std::{ use either::Either; use hir_def::{ - hir::Expr, + hir::{Expr, ExprOrPatId}, lower::LowerCtx, nameres::{MacroSubNs, ModuleOrigin}, path::ModPath, @@ -1755,7 +1755,9 @@ impl<'db> SemanticsImpl<'db> { } if let Some(parent) = ast::Expr::cast(parent.clone()) { - if let Some(expr_id) = source_map.node_expr(InFile { file_id, value: &parent }) { + if let Some(ExprOrPatId::ExprId(expr_id)) = + source_map.node_expr(InFile { file_id, value: &parent }) + { if let Expr::Unsafe { .. } = body[expr_id] { break true; } diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs b/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs index fd6d52d6c9df..e53a7da7edb3 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs @@ -306,7 +306,7 @@ impl SourceToDefCtx<'_, '_> { .position(|it| it == *src.value)?; let container = self.find_pat_or_label_container(src.syntax_ref())?; let (_, source_map) = self.db.body_with_source_map(container); - let expr = source_map.node_expr(src.with_value(&ast::Expr::AsmExpr(asm)))?; + let expr = source_map.node_expr(src.with_value(&ast::Expr::AsmExpr(asm)))?.as_expr()?; Some(InlineAsmOperand { owner: container, expr, index }) } @@ -350,7 +350,8 @@ impl SourceToDefCtx<'_, '_> { let break_or_continue = ast::Expr::cast(src.value.syntax().parent()?)?; let container = self.find_pat_or_label_container(src.syntax_ref())?; let (body, source_map) = self.db.body_with_source_map(container); - let break_or_continue = source_map.node_expr(src.with_value(&break_or_continue))?; + let break_or_continue = + source_map.node_expr(src.with_value(&break_or_continue))?.as_expr()?; let (Expr::Break { label, .. } | Expr::Continue { label }) = body[break_or_continue] else { return None; }; diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 3da67ae23f83..f2f27517fd66 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -13,7 +13,7 @@ use hir_def::{ scope::{ExprScopes, ScopeId}, Body, BodySourceMap, }, - hir::{BindingId, ExprId, Pat, PatId}, + hir::{BindingId, ExprId, ExprOrPatId, Pat, PatId}, lang_item::LangItem, lower::LowerCtx, nameres::MacroSubNs, @@ -120,7 +120,7 @@ impl SourceAnalyzer { self.def.as_ref().map(|(_, body, _)| &**body) } - fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option { + fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option { let src = match expr { ast::Expr::MacroExpr(expr) => { self.expand_expr(db, InFile::new(self.file_id, expr.macro_call()?))?.into() @@ -174,7 +174,9 @@ impl SourceAnalyzer { db: &dyn HirDatabase, expr: &ast::Expr, ) -> Option<&[Adjustment]> { - let expr_id = self.expr_id(db, expr)?; + // It is safe to omit destructuring assignments here because they have no adjustments (neither + // expressions nor patterns). + let expr_id = self.expr_id(db, expr)?.as_expr()?; let infer = self.infer.as_ref()?; infer.expr_adjustments.get(&expr_id).map(|v| &**v) } @@ -186,9 +188,9 @@ impl SourceAnalyzer { ) -> Option<(Type, Option)> { let expr_id = self.expr_id(db, expr)?; let infer = self.infer.as_ref()?; - let coerced = infer - .expr_adjustments - .get(&expr_id) + let coerced = expr_id + .as_expr() + .and_then(|expr_id| infer.expr_adjustments.get(&expr_id)) .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone())); let ty = infer[expr_id].clone(); let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty); @@ -268,7 +270,7 @@ impl SourceAnalyzer { db: &dyn HirDatabase, call: &ast::MethodCallExpr, ) -> Option { - let expr_id = self.expr_id(db, &call.clone().into())?; + let expr_id = self.expr_id(db, &call.clone().into())?.as_expr()?; let (func, substs) = self.infer.as_ref()?.method_resolution(expr_id)?; let ty = db.value_ty(func.into())?.substitute(Interner, &substs); let ty = Type::new_with_resolver(db, &self.resolver, ty); @@ -282,7 +284,7 @@ impl SourceAnalyzer { db: &dyn HirDatabase, call: &ast::MethodCallExpr, ) -> Option { - let expr_id = self.expr_id(db, &call.clone().into())?; + let expr_id = self.expr_id(db, &call.clone().into())?.as_expr()?; let (f_in_trait, substs) = self.infer.as_ref()?.method_resolution(expr_id)?; Some(self.resolve_impl_method_or_trait_def(db, f_in_trait, substs).into()) @@ -293,7 +295,7 @@ impl SourceAnalyzer { db: &dyn HirDatabase, call: &ast::MethodCallExpr, ) -> Option> { - let expr_id = self.expr_id(db, &call.clone().into())?; + let expr_id = self.expr_id(db, &call.clone().into())?.as_expr()?; let inference_result = self.infer.as_ref()?; match inference_result.method_resolution(expr_id) { Some((f_in_trait, substs)) => Some(Either::Left( @@ -322,7 +324,7 @@ impl SourceAnalyzer { field: &ast::FieldExpr, ) -> Option> { let &(def, ..) = self.def.as_ref()?; - let expr_id = self.expr_id(db, &field.clone().into())?; + let expr_id = self.expr_id(db, &field.clone().into())?.as_expr()?; self.infer.as_ref()?.field_resolution(expr_id).map(|it| { it.map_either(Into::into, |f| TupleField { owner: def, tuple: f.tuple, index: f.index }) }) @@ -334,7 +336,7 @@ impl SourceAnalyzer { field: &ast::FieldExpr, ) -> Option, Function>> { let &(def, ..) = self.def.as_ref()?; - let expr_id = self.expr_id(db, &field.clone().into())?; + let expr_id = self.expr_id(db, &field.clone().into())?.as_expr()?; let inference_result = self.infer.as_ref()?; match inference_result.field_resolution(expr_id) { Some(field) => Some(Either::Left(field.map_either(Into::into, |f| TupleField { @@ -403,7 +405,7 @@ impl SourceAnalyzer { self.infer .as_ref() .and_then(|infer| { - let expr = self.expr_id(db, &prefix_expr.clone().into())?; + let expr = self.expr_id(db, &prefix_expr.clone().into())?.as_expr()?; let (func, _) = infer.method_resolution(expr)?; let (deref_mut_trait, deref_mut) = self.lang_trait_fn( db, @@ -449,7 +451,7 @@ impl SourceAnalyzer { .infer .as_ref() .and_then(|infer| { - let expr = self.expr_id(db, &index_expr.clone().into())?; + let expr = self.expr_id(db, &index_expr.clone().into())?.as_expr()?; let (func, _) = infer.method_resolution(expr)?; let (index_mut_trait, index_mut_fn) = self.lang_trait_fn( db, @@ -537,8 +539,8 @@ impl SourceAnalyzer { _ => None, } }; - let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?; - let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?; + let (_, subst) = self.infer.as_ref()?.type_of_expr_or_pat(expr_id)?.as_adt()?; + let variant = self.infer.as_ref()?.variant_resolution_for_expr_or_pat(expr_id)?; let variant_data = variant.variant_data(db.upcast()); let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? }; let field_ty = @@ -606,10 +608,10 @@ impl SourceAnalyzer { let infer = self.infer.as_deref()?; if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) { let expr_id = self.expr_id(db, &path_expr.into())?; - if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr(expr_id) { + if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr_or_pat(expr_id) { let assoc = match assoc { AssocItemId::FunctionId(f_in_trait) => { - match infer.type_of_expr.get(expr_id) { + match infer.type_of_expr_or_pat(expr_id) { None => assoc, Some(func_ty) => { if let TyKind::FnDef(_fn_def, subs) = func_ty.kind(Interner) { @@ -634,7 +636,7 @@ impl SourceAnalyzer { return Some(PathResolution::Def(AssocItem::from(assoc).into())); } if let Some(VariantId::EnumVariantId(variant)) = - infer.variant_resolution_for_expr(expr_id) + infer.variant_resolution_for_expr_or_pat(expr_id) { return Some(PathResolution::Def(ModuleDef::Variant(variant.into()))); } @@ -658,7 +660,7 @@ impl SourceAnalyzer { } else if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) { let expr_id = self.expr_id(db, &rec_lit.into())?; if let Some(VariantId::EnumVariantId(variant)) = - infer.variant_resolution_for_expr(expr_id) + infer.variant_resolution_for_expr_or_pat(expr_id) { return Some(PathResolution::Def(ModuleDef::Variant(variant.into()))); } @@ -790,10 +792,16 @@ impl SourceAnalyzer { let infer = self.infer.as_ref()?; let expr_id = self.expr_id(db, &literal.clone().into())?; - let substs = infer.type_of_expr[expr_id].as_adt()?.1; + let substs = infer[expr_id].as_adt()?.1; - let (variant, missing_fields, _exhaustive) = - record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?; + let (variant, missing_fields, _exhaustive) = match expr_id { + ExprOrPatId::ExprId(expr_id) => { + record_literal_missing_fields(db, infer, expr_id, &body[expr_id])? + } + ExprOrPatId::PatId(pat_id) => { + record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])? + } + }; let res = self.missing_fields(db, substs, variant, missing_fields); Some(res) } @@ -856,7 +864,7 @@ impl SourceAnalyzer { ) -> Option { let infer = self.infer.as_ref()?; let expr_id = self.expr_id(db, &record_lit.into())?; - infer.variant_resolution_for_expr(expr_id) + infer.variant_resolution_for_expr_or_pat(expr_id) } pub(crate) fn is_unsafe_macro_call_expr( @@ -867,14 +875,24 @@ impl SourceAnalyzer { if let (Some((def, body, sm)), Some(infer)) = (&self.def, &self.infer) { if let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr) { let mut is_unsafe = false; - unsafe_expressions( - db, - infer, - *def, - body, - expanded_expr, - &mut |UnsafeExpr { inside_unsafe_block, .. }| is_unsafe |= !inside_unsafe_block, - ); + let mut walk_expr = |expr_id| { + unsafe_expressions( + db, + infer, + *def, + body, + expr_id, + &mut |UnsafeExpr { inside_unsafe_block, .. }| { + is_unsafe |= !inside_unsafe_block + }, + ) + }; + match expanded_expr { + ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr), + ExprOrPatId::PatId(expanded_pat) => { + body.walk_exprs_in_pat(expanded_pat, &mut walk_expr) + } + } return is_unsafe; } } @@ -991,7 +1009,7 @@ impl SourceAnalyzer { } fn ty_of_expr(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<&Ty> { - self.infer.as_ref()?.type_of_expr.get(self.expr_id(db, expr)?) + self.infer.as_ref()?.type_of_expr_or_pat(self.expr_id(db, expr)?) } } @@ -1004,7 +1022,7 @@ fn scope_for( node.ancestors_with_macros(db.upcast()) .take_while(|it| !ast::Item::can_cast(it.kind()) || ast::MacroCall::can_cast(it.kind())) .filter_map(|it| it.map(ast::Expr::cast).transpose()) - .filter_map(|it| source_map.node_expr(it.as_ref())) + .filter_map(|it| source_map.node_expr(it.as_ref())?.as_expr()) .find_map(|it| scopes.scope_for(it)) } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs index 86c237f7b5ec..3a622c69681e 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -308,22 +308,27 @@ struct T(S); fn regular(a: S) { let s; S { s, .. } = a; + _ = s; } fn nested(a: S2) { let s; S2 { s: S { s, .. }, .. } = a; + _ = s; } fn in_tuple(a: (S,)) { let s; (S { s, .. },) = a; + _ = s; } fn in_array(a: [S;1]) { let s; [S { s, .. },] = a; + _ = s; } fn in_tuple_struct(a: T) { let s; T(S { s, .. }) = a; + _ = s; } ", ); diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs index cc0f4bfccc9a..98063bf4fef8 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs @@ -32,7 +32,8 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingUnsafe) -> Option, d: &hir::NeedMut) -> Option { + let root = ctx.sema.db.parse_or_expand(d.span.file_id); + let node = d.span.value.to_node(&root); + let mut span = d.span; + if let Some(parent) = node.parent() { + if ast::BinExpr::can_cast(parent.kind()) { + // In case of an assignment, the diagnostic is provided on the variable name. + // We want to expand it to include the whole assignment, but only when this + // is an ordinary assignment, not a destructuring assignment. So, the direct + // parent is an assignment expression. + span = d.span.with_value(SyntaxNodePtr::new(&parent)); + } + }; + let fixes = (|| { if d.local.is_ref(ctx.sema.db) { // There is no simple way to add `mut` to `ref x` and `ref mut x` return None; } - let file_id = d.span.file_id.file_id()?; + let file_id = span.file_id.file_id()?; let mut edit_builder = TextEdit::builder(); - let use_range = d.span.value.text_range(); + let use_range = span.value.text_range(); for source in d.local.sources(ctx.sema.db) { let Some(ast) = source.name() else { continue }; // FIXME: macros @@ -29,6 +43,7 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Option use_range, )]) })(); + Some( Diagnostic::new_with_syntax_node_ptr( ctx, @@ -38,7 +53,7 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Option "cannot mutate immutable variable `{}`", d.local.name(ctx.sema.db).display(ctx.sema.db, ctx.edition) ), - d.span, + span, ) .with_fixes(fixes), ) @@ -929,7 +944,6 @@ fn fn_once(mut x: impl FnOnce(u8) -> u8) -> u8 { #[test] fn closure() { - // FIXME: Diagnostic spans are inconsistent inside and outside closure check_diagnostics( r#" //- minicore: copy, fn @@ -942,11 +956,11 @@ fn fn_once(mut x: impl FnOnce(u8) -> u8) -> u8 { fn f() { let x = 5; let closure1 = || { x = 2; }; - //^ 💡 error: cannot mutate immutable variable `x` + //^^^^^ 💡 error: cannot mutate immutable variable `x` let _ = closure1(); //^^^^^^^^ 💡 error: cannot mutate immutable variable `closure1` let closure2 = || { x = x; }; - //^ 💡 error: cannot mutate immutable variable `x` + //^^^^^ 💡 error: cannot mutate immutable variable `x` let closure3 = || { let x = 2; x = 5; @@ -988,7 +1002,7 @@ fn f() { || { let x = 2; || { || { x = 5; } } - //^ 💡 error: cannot mutate immutable variable `x` + //^^^^^ 💡 error: cannot mutate immutable variable `x` } } }; From 8183f6b4739884b9cce0e29eaaf5d42643e5f540 Mon Sep 17 00:00:00 2001 From: roife Date: Mon, 21 Oct 2024 02:56:21 +0800 Subject: [PATCH 064/366] fix: classify `safe` as a contextual kw --- src/tools/rust-analyzer/crates/hir-ty/src/utils.rs | 2 +- .../ide-diagnostics/src/handlers/missing_unsafe.rs | 4 ++-- .../rust-analyzer/crates/parser/src/grammar/items.rs | 4 ++-- .../crates/parser/src/syntax_kind/generated.rs | 10 +++++----- .../rust-analyzer/xtask/src/codegen/grammar/ast_src.rs | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs index 10252ce6f3e4..620bba2d75c1 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs @@ -273,7 +273,7 @@ pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool { !data.attrs.by_key(&sym::rustc_safe_intrinsic).exists() } else { // Extern items without `safe` modifier are always unsafe - !db.function_data(func).is_safe() + !data.is_safe() } } _ => false, diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs index cc0f4bfccc9a..44be53b87ca5 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_unsafe.rs @@ -554,7 +554,7 @@ fn main() { r#" //- /ed2021.rs crate:ed2021 edition:2021 #[rustc_deprecated_safe_2024] -unsafe fn safe_fn() -> u8 { +unsafe fn safe() -> u8 { 0 } //- /ed2024.rs crate:ed2024 edition:2024 @@ -564,7 +564,7 @@ unsafe fn not_safe() -> u8 { } //- /main.rs crate:main deps:ed2021,ed2024 fn main() { - ed2021::safe_fn(); + ed2021::safe(); ed2024::not_safe(); //^^^^^^^^^^^^^^^^^^💡 error: this operation is unsafe and requires an unsafe function or block } diff --git a/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs b/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs index 5f46093da523..c4dce0daa5b1 100644 --- a/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs +++ b/src/tools/rust-analyzer/crates/parser/src/grammar/items.rs @@ -135,8 +135,8 @@ pub(super) fn opt_item(p: &mut Parser<'_>, m: Marker) -> Result<(), Marker> { has_mods = true; } - if p.at(T![safe]) { - p.eat(T![safe]); + if p.at_contextual_kw(T![safe]) { + p.eat_contextual_kw(T![safe]); has_mods = true; } diff --git a/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs b/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs index 39d9d7e340b1..8da338c0a2c5 100644 --- a/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs +++ b/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs @@ -94,7 +94,6 @@ pub enum SyntaxKind { PUB_KW, REF_KW, RETURN_KW, - SAFE_KW, SELF_KW, STATIC_KW, STRUCT_KW, @@ -137,6 +136,7 @@ pub enum SyntaxKind { PURE_KW, RAW_KW, READONLY_KW, + SAFE_KW, SYM_KW, TRY_KW, UNION_KW, @@ -365,7 +365,6 @@ impl SyntaxKind { | PUB_KW | REF_KW | RETURN_KW - | SAFE_KW | SELF_KW | STATIC_KW | STRUCT_KW @@ -418,6 +417,7 @@ impl SyntaxKind { PURE_KW => true, RAW_KW => true, READONLY_KW => true, + SAFE_KW => true, SYM_KW => true, UNION_KW => true, YEET_KW => true, @@ -460,7 +460,6 @@ impl SyntaxKind { | PUB_KW | REF_KW | RETURN_KW - | SAFE_KW | SELF_KW | STATIC_KW | STRUCT_KW @@ -506,6 +505,7 @@ impl SyntaxKind { PURE_KW => true, RAW_KW => true, READONLY_KW => true, + SAFE_KW => true, SYM_KW => true, UNION_KW => true, YEET_KW => true, @@ -617,7 +617,6 @@ impl SyntaxKind { "pub" => PUB_KW, "ref" => REF_KW, "return" => RETURN_KW, - "safe" => SAFE_KW, "self" => SELF_KW, "static" => STATIC_KW, "struct" => STRUCT_KW, @@ -668,6 +667,7 @@ impl SyntaxKind { "pure" => PURE_KW, "raw" => RAW_KW, "readonly" => READONLY_KW, + "safe" => SAFE_KW, "sym" => SYM_KW, "union" => UNION_KW, "yeet" => YEET_KW, @@ -711,4 +711,4 @@ impl SyntaxKind { } } #[macro_export] -macro_rules ! T { [$] => { $ crate :: SyntaxKind :: DOLLAR } ; [;] => { $ crate :: SyntaxKind :: SEMICOLON } ; [,] => { $ crate :: SyntaxKind :: COMMA } ; ['('] => { $ crate :: SyntaxKind :: L_PAREN } ; [')'] => { $ crate :: SyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: SyntaxKind :: L_CURLY } ; ['}'] => { $ crate :: SyntaxKind :: R_CURLY } ; ['['] => { $ crate :: SyntaxKind :: L_BRACK } ; [']'] => { $ crate :: SyntaxKind :: R_BRACK } ; [<] => { $ crate :: SyntaxKind :: L_ANGLE } ; [>] => { $ crate :: SyntaxKind :: R_ANGLE } ; [@] => { $ crate :: SyntaxKind :: AT } ; [#] => { $ crate :: SyntaxKind :: POUND } ; [~] => { $ crate :: SyntaxKind :: TILDE } ; [?] => { $ crate :: SyntaxKind :: QUESTION } ; [&] => { $ crate :: SyntaxKind :: AMP } ; [|] => { $ crate :: SyntaxKind :: PIPE } ; [+] => { $ crate :: SyntaxKind :: PLUS } ; [*] => { $ crate :: SyntaxKind :: STAR } ; [/] => { $ crate :: SyntaxKind :: SLASH } ; [^] => { $ crate :: SyntaxKind :: CARET } ; [%] => { $ crate :: SyntaxKind :: PERCENT } ; [_] => { $ crate :: SyntaxKind :: UNDERSCORE } ; [.] => { $ crate :: SyntaxKind :: DOT } ; [..] => { $ crate :: SyntaxKind :: DOT2 } ; [...] => { $ crate :: SyntaxKind :: DOT3 } ; [..=] => { $ crate :: SyntaxKind :: DOT2EQ } ; [:] => { $ crate :: SyntaxKind :: COLON } ; [::] => { $ crate :: SyntaxKind :: COLON2 } ; [=] => { $ crate :: SyntaxKind :: EQ } ; [==] => { $ crate :: SyntaxKind :: EQ2 } ; [=>] => { $ crate :: SyntaxKind :: FAT_ARROW } ; [!] => { $ crate :: SyntaxKind :: BANG } ; [!=] => { $ crate :: SyntaxKind :: NEQ } ; [-] => { $ crate :: SyntaxKind :: MINUS } ; [->] => { $ crate :: SyntaxKind :: THIN_ARROW } ; [<=] => { $ crate :: SyntaxKind :: LTEQ } ; [>=] => { $ crate :: SyntaxKind :: GTEQ } ; [+=] => { $ crate :: SyntaxKind :: PLUSEQ } ; [-=] => { $ crate :: SyntaxKind :: MINUSEQ } ; [|=] => { $ crate :: SyntaxKind :: PIPEEQ } ; [&=] => { $ crate :: SyntaxKind :: AMPEQ } ; [^=] => { $ crate :: SyntaxKind :: CARETEQ } ; [/=] => { $ crate :: SyntaxKind :: SLASHEQ } ; [*=] => { $ crate :: SyntaxKind :: STAREQ } ; [%=] => { $ crate :: SyntaxKind :: PERCENTEQ } ; [&&] => { $ crate :: SyntaxKind :: AMP2 } ; [||] => { $ crate :: SyntaxKind :: PIPE2 } ; [<<] => { $ crate :: SyntaxKind :: SHL } ; [>>] => { $ crate :: SyntaxKind :: SHR } ; [<<=] => { $ crate :: SyntaxKind :: SHLEQ } ; [>>=] => { $ crate :: SyntaxKind :: SHREQ } ; [Self] => { $ crate :: SyntaxKind :: SELF_TYPE_KW } ; [abstract] => { $ crate :: SyntaxKind :: ABSTRACT_KW } ; [as] => { $ crate :: SyntaxKind :: AS_KW } ; [become] => { $ crate :: SyntaxKind :: BECOME_KW } ; [box] => { $ crate :: SyntaxKind :: BOX_KW } ; [break] => { $ crate :: SyntaxKind :: BREAK_KW } ; [const] => { $ crate :: SyntaxKind :: CONST_KW } ; [continue] => { $ crate :: SyntaxKind :: CONTINUE_KW } ; [crate] => { $ crate :: SyntaxKind :: CRATE_KW } ; [do] => { $ crate :: SyntaxKind :: DO_KW } ; [else] => { $ crate :: SyntaxKind :: ELSE_KW } ; [enum] => { $ crate :: SyntaxKind :: ENUM_KW } ; [extern] => { $ crate :: SyntaxKind :: EXTERN_KW } ; [false] => { $ crate :: SyntaxKind :: FALSE_KW } ; [final] => { $ crate :: SyntaxKind :: FINAL_KW } ; [fn] => { $ crate :: SyntaxKind :: FN_KW } ; [for] => { $ crate :: SyntaxKind :: FOR_KW } ; [if] => { $ crate :: SyntaxKind :: IF_KW } ; [impl] => { $ crate :: SyntaxKind :: IMPL_KW } ; [in] => { $ crate :: SyntaxKind :: IN_KW } ; [let] => { $ crate :: SyntaxKind :: LET_KW } ; [loop] => { $ crate :: SyntaxKind :: LOOP_KW } ; [macro] => { $ crate :: SyntaxKind :: MACRO_KW } ; [match] => { $ crate :: SyntaxKind :: MATCH_KW } ; [mod] => { $ crate :: SyntaxKind :: MOD_KW } ; [move] => { $ crate :: SyntaxKind :: MOVE_KW } ; [mut] => { $ crate :: SyntaxKind :: MUT_KW } ; [override] => { $ crate :: SyntaxKind :: OVERRIDE_KW } ; [priv] => { $ crate :: SyntaxKind :: PRIV_KW } ; [pub] => { $ crate :: SyntaxKind :: PUB_KW } ; [ref] => { $ crate :: SyntaxKind :: REF_KW } ; [return] => { $ crate :: SyntaxKind :: RETURN_KW } ; [safe] => { $ crate :: SyntaxKind :: SAFE_KW } ; [self] => { $ crate :: SyntaxKind :: SELF_KW } ; [static] => { $ crate :: SyntaxKind :: STATIC_KW } ; [struct] => { $ crate :: SyntaxKind :: STRUCT_KW } ; [super] => { $ crate :: SyntaxKind :: SUPER_KW } ; [trait] => { $ crate :: SyntaxKind :: TRAIT_KW } ; [true] => { $ crate :: SyntaxKind :: TRUE_KW } ; [type] => { $ crate :: SyntaxKind :: TYPE_KW } ; [typeof] => { $ crate :: SyntaxKind :: TYPEOF_KW } ; [unsafe] => { $ crate :: SyntaxKind :: UNSAFE_KW } ; [unsized] => { $ crate :: SyntaxKind :: UNSIZED_KW } ; [use] => { $ crate :: SyntaxKind :: USE_KW } ; [virtual] => { $ crate :: SyntaxKind :: VIRTUAL_KW } ; [where] => { $ crate :: SyntaxKind :: WHERE_KW } ; [while] => { $ crate :: SyntaxKind :: WHILE_KW } ; [yield] => { $ crate :: SyntaxKind :: YIELD_KW } ; [asm] => { $ crate :: SyntaxKind :: ASM_KW } ; [att_syntax] => { $ crate :: SyntaxKind :: ATT_SYNTAX_KW } ; [auto] => { $ crate :: SyntaxKind :: AUTO_KW } ; [builtin] => { $ crate :: SyntaxKind :: BUILTIN_KW } ; [clobber_abi] => { $ crate :: SyntaxKind :: CLOBBER_ABI_KW } ; [default] => { $ crate :: SyntaxKind :: DEFAULT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [format_args] => { $ crate :: SyntaxKind :: FORMAT_ARGS_KW } ; [inlateout] => { $ crate :: SyntaxKind :: INLATEOUT_KW } ; [inout] => { $ crate :: SyntaxKind :: INOUT_KW } ; [label] => { $ crate :: SyntaxKind :: LABEL_KW } ; [lateout] => { $ crate :: SyntaxKind :: LATEOUT_KW } ; [macro_rules] => { $ crate :: SyntaxKind :: MACRO_RULES_KW } ; [may_unwind] => { $ crate :: SyntaxKind :: MAY_UNWIND_KW } ; [nomem] => { $ crate :: SyntaxKind :: NOMEM_KW } ; [noreturn] => { $ crate :: SyntaxKind :: NORETURN_KW } ; [nostack] => { $ crate :: SyntaxKind :: NOSTACK_KW } ; [offset_of] => { $ crate :: SyntaxKind :: OFFSET_OF_KW } ; [options] => { $ crate :: SyntaxKind :: OPTIONS_KW } ; [out] => { $ crate :: SyntaxKind :: OUT_KW } ; [preserves_flags] => { $ crate :: SyntaxKind :: PRESERVES_FLAGS_KW } ; [pure] => { $ crate :: SyntaxKind :: PURE_KW } ; [raw] => { $ crate :: SyntaxKind :: RAW_KW } ; [readonly] => { $ crate :: SyntaxKind :: READONLY_KW } ; [sym] => { $ crate :: SyntaxKind :: SYM_KW } ; [union] => { $ crate :: SyntaxKind :: UNION_KW } ; [yeet] => { $ crate :: SyntaxKind :: YEET_KW } ; [async] => { $ crate :: SyntaxKind :: ASYNC_KW } ; [await] => { $ crate :: SyntaxKind :: AWAIT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [gen] => { $ crate :: SyntaxKind :: GEN_KW } ; [try] => { $ crate :: SyntaxKind :: TRY_KW } ; [lifetime_ident] => { $ crate :: SyntaxKind :: LIFETIME_IDENT } ; [int_number] => { $ crate :: SyntaxKind :: INT_NUMBER } ; [ident] => { $ crate :: SyntaxKind :: IDENT } ; [string] => { $ crate :: SyntaxKind :: STRING } ; [shebang] => { $ crate :: SyntaxKind :: SHEBANG } ; } +macro_rules ! T { [$] => { $ crate :: SyntaxKind :: DOLLAR } ; [;] => { $ crate :: SyntaxKind :: SEMICOLON } ; [,] => { $ crate :: SyntaxKind :: COMMA } ; ['('] => { $ crate :: SyntaxKind :: L_PAREN } ; [')'] => { $ crate :: SyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: SyntaxKind :: L_CURLY } ; ['}'] => { $ crate :: SyntaxKind :: R_CURLY } ; ['['] => { $ crate :: SyntaxKind :: L_BRACK } ; [']'] => { $ crate :: SyntaxKind :: R_BRACK } ; [<] => { $ crate :: SyntaxKind :: L_ANGLE } ; [>] => { $ crate :: SyntaxKind :: R_ANGLE } ; [@] => { $ crate :: SyntaxKind :: AT } ; [#] => { $ crate :: SyntaxKind :: POUND } ; [~] => { $ crate :: SyntaxKind :: TILDE } ; [?] => { $ crate :: SyntaxKind :: QUESTION } ; [&] => { $ crate :: SyntaxKind :: AMP } ; [|] => { $ crate :: SyntaxKind :: PIPE } ; [+] => { $ crate :: SyntaxKind :: PLUS } ; [*] => { $ crate :: SyntaxKind :: STAR } ; [/] => { $ crate :: SyntaxKind :: SLASH } ; [^] => { $ crate :: SyntaxKind :: CARET } ; [%] => { $ crate :: SyntaxKind :: PERCENT } ; [_] => { $ crate :: SyntaxKind :: UNDERSCORE } ; [.] => { $ crate :: SyntaxKind :: DOT } ; [..] => { $ crate :: SyntaxKind :: DOT2 } ; [...] => { $ crate :: SyntaxKind :: DOT3 } ; [..=] => { $ crate :: SyntaxKind :: DOT2EQ } ; [:] => { $ crate :: SyntaxKind :: COLON } ; [::] => { $ crate :: SyntaxKind :: COLON2 } ; [=] => { $ crate :: SyntaxKind :: EQ } ; [==] => { $ crate :: SyntaxKind :: EQ2 } ; [=>] => { $ crate :: SyntaxKind :: FAT_ARROW } ; [!] => { $ crate :: SyntaxKind :: BANG } ; [!=] => { $ crate :: SyntaxKind :: NEQ } ; [-] => { $ crate :: SyntaxKind :: MINUS } ; [->] => { $ crate :: SyntaxKind :: THIN_ARROW } ; [<=] => { $ crate :: SyntaxKind :: LTEQ } ; [>=] => { $ crate :: SyntaxKind :: GTEQ } ; [+=] => { $ crate :: SyntaxKind :: PLUSEQ } ; [-=] => { $ crate :: SyntaxKind :: MINUSEQ } ; [|=] => { $ crate :: SyntaxKind :: PIPEEQ } ; [&=] => { $ crate :: SyntaxKind :: AMPEQ } ; [^=] => { $ crate :: SyntaxKind :: CARETEQ } ; [/=] => { $ crate :: SyntaxKind :: SLASHEQ } ; [*=] => { $ crate :: SyntaxKind :: STAREQ } ; [%=] => { $ crate :: SyntaxKind :: PERCENTEQ } ; [&&] => { $ crate :: SyntaxKind :: AMP2 } ; [||] => { $ crate :: SyntaxKind :: PIPE2 } ; [<<] => { $ crate :: SyntaxKind :: SHL } ; [>>] => { $ crate :: SyntaxKind :: SHR } ; [<<=] => { $ crate :: SyntaxKind :: SHLEQ } ; [>>=] => { $ crate :: SyntaxKind :: SHREQ } ; [Self] => { $ crate :: SyntaxKind :: SELF_TYPE_KW } ; [abstract] => { $ crate :: SyntaxKind :: ABSTRACT_KW } ; [as] => { $ crate :: SyntaxKind :: AS_KW } ; [become] => { $ crate :: SyntaxKind :: BECOME_KW } ; [box] => { $ crate :: SyntaxKind :: BOX_KW } ; [break] => { $ crate :: SyntaxKind :: BREAK_KW } ; [const] => { $ crate :: SyntaxKind :: CONST_KW } ; [continue] => { $ crate :: SyntaxKind :: CONTINUE_KW } ; [crate] => { $ crate :: SyntaxKind :: CRATE_KW } ; [do] => { $ crate :: SyntaxKind :: DO_KW } ; [else] => { $ crate :: SyntaxKind :: ELSE_KW } ; [enum] => { $ crate :: SyntaxKind :: ENUM_KW } ; [extern] => { $ crate :: SyntaxKind :: EXTERN_KW } ; [false] => { $ crate :: SyntaxKind :: FALSE_KW } ; [final] => { $ crate :: SyntaxKind :: FINAL_KW } ; [fn] => { $ crate :: SyntaxKind :: FN_KW } ; [for] => { $ crate :: SyntaxKind :: FOR_KW } ; [if] => { $ crate :: SyntaxKind :: IF_KW } ; [impl] => { $ crate :: SyntaxKind :: IMPL_KW } ; [in] => { $ crate :: SyntaxKind :: IN_KW } ; [let] => { $ crate :: SyntaxKind :: LET_KW } ; [loop] => { $ crate :: SyntaxKind :: LOOP_KW } ; [macro] => { $ crate :: SyntaxKind :: MACRO_KW } ; [match] => { $ crate :: SyntaxKind :: MATCH_KW } ; [mod] => { $ crate :: SyntaxKind :: MOD_KW } ; [move] => { $ crate :: SyntaxKind :: MOVE_KW } ; [mut] => { $ crate :: SyntaxKind :: MUT_KW } ; [override] => { $ crate :: SyntaxKind :: OVERRIDE_KW } ; [priv] => { $ crate :: SyntaxKind :: PRIV_KW } ; [pub] => { $ crate :: SyntaxKind :: PUB_KW } ; [ref] => { $ crate :: SyntaxKind :: REF_KW } ; [return] => { $ crate :: SyntaxKind :: RETURN_KW } ; [self] => { $ crate :: SyntaxKind :: SELF_KW } ; [static] => { $ crate :: SyntaxKind :: STATIC_KW } ; [struct] => { $ crate :: SyntaxKind :: STRUCT_KW } ; [super] => { $ crate :: SyntaxKind :: SUPER_KW } ; [trait] => { $ crate :: SyntaxKind :: TRAIT_KW } ; [true] => { $ crate :: SyntaxKind :: TRUE_KW } ; [type] => { $ crate :: SyntaxKind :: TYPE_KW } ; [typeof] => { $ crate :: SyntaxKind :: TYPEOF_KW } ; [unsafe] => { $ crate :: SyntaxKind :: UNSAFE_KW } ; [unsized] => { $ crate :: SyntaxKind :: UNSIZED_KW } ; [use] => { $ crate :: SyntaxKind :: USE_KW } ; [virtual] => { $ crate :: SyntaxKind :: VIRTUAL_KW } ; [where] => { $ crate :: SyntaxKind :: WHERE_KW } ; [while] => { $ crate :: SyntaxKind :: WHILE_KW } ; [yield] => { $ crate :: SyntaxKind :: YIELD_KW } ; [asm] => { $ crate :: SyntaxKind :: ASM_KW } ; [att_syntax] => { $ crate :: SyntaxKind :: ATT_SYNTAX_KW } ; [auto] => { $ crate :: SyntaxKind :: AUTO_KW } ; [builtin] => { $ crate :: SyntaxKind :: BUILTIN_KW } ; [clobber_abi] => { $ crate :: SyntaxKind :: CLOBBER_ABI_KW } ; [default] => { $ crate :: SyntaxKind :: DEFAULT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [format_args] => { $ crate :: SyntaxKind :: FORMAT_ARGS_KW } ; [inlateout] => { $ crate :: SyntaxKind :: INLATEOUT_KW } ; [inout] => { $ crate :: SyntaxKind :: INOUT_KW } ; [label] => { $ crate :: SyntaxKind :: LABEL_KW } ; [lateout] => { $ crate :: SyntaxKind :: LATEOUT_KW } ; [macro_rules] => { $ crate :: SyntaxKind :: MACRO_RULES_KW } ; [may_unwind] => { $ crate :: SyntaxKind :: MAY_UNWIND_KW } ; [nomem] => { $ crate :: SyntaxKind :: NOMEM_KW } ; [noreturn] => { $ crate :: SyntaxKind :: NORETURN_KW } ; [nostack] => { $ crate :: SyntaxKind :: NOSTACK_KW } ; [offset_of] => { $ crate :: SyntaxKind :: OFFSET_OF_KW } ; [options] => { $ crate :: SyntaxKind :: OPTIONS_KW } ; [out] => { $ crate :: SyntaxKind :: OUT_KW } ; [preserves_flags] => { $ crate :: SyntaxKind :: PRESERVES_FLAGS_KW } ; [pure] => { $ crate :: SyntaxKind :: PURE_KW } ; [raw] => { $ crate :: SyntaxKind :: RAW_KW } ; [readonly] => { $ crate :: SyntaxKind :: READONLY_KW } ; [safe] => { $ crate :: SyntaxKind :: SAFE_KW } ; [sym] => { $ crate :: SyntaxKind :: SYM_KW } ; [union] => { $ crate :: SyntaxKind :: UNION_KW } ; [yeet] => { $ crate :: SyntaxKind :: YEET_KW } ; [async] => { $ crate :: SyntaxKind :: ASYNC_KW } ; [await] => { $ crate :: SyntaxKind :: AWAIT_KW } ; [dyn] => { $ crate :: SyntaxKind :: DYN_KW } ; [gen] => { $ crate :: SyntaxKind :: GEN_KW } ; [try] => { $ crate :: SyntaxKind :: TRY_KW } ; [lifetime_ident] => { $ crate :: SyntaxKind :: LIFETIME_IDENT } ; [int_number] => { $ crate :: SyntaxKind :: INT_NUMBER } ; [ident] => { $ crate :: SyntaxKind :: IDENT } ; [string] => { $ crate :: SyntaxKind :: STRING } ; [shebang] => { $ crate :: SyntaxKind :: SHEBANG } ; } diff --git a/src/tools/rust-analyzer/xtask/src/codegen/grammar/ast_src.rs b/src/tools/rust-analyzer/xtask/src/codegen/grammar/ast_src.rs index f1a96e0c6a2d..9269d1542353 100644 --- a/src/tools/rust-analyzer/xtask/src/codegen/grammar/ast_src.rs +++ b/src/tools/rust-analyzer/xtask/src/codegen/grammar/ast_src.rs @@ -111,7 +111,7 @@ const RESERVED: &[&str] = &[ // keywords that are keywords only in specific parse contexts #[doc(alias = "WEAK_KEYWORDS")] const CONTEXTUAL_KEYWORDS: &[&str] = - &["macro_rules", "union", "default", "raw", "dyn", "auto", "yeet"]; + &["macro_rules", "union", "default", "raw", "dyn", "auto", "yeet", "safe"]; // keywords we use for special macro expansions const CONTEXTUAL_BUILTIN_KEYWORDS: &[&str] = &[ "asm", From 73a37a165e209df530d759bea0a6c4979165a5b6 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 20 Oct 2024 14:12:45 +0000 Subject: [PATCH 065/366] tweak hybrid preds --- .../src/check/compare_impl_item.rs | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 75956165e873..610311f40582 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -194,16 +194,6 @@ fn compare_method_predicate_entailment<'tcx>( let impl_m_predicates = tcx.predicates_of(impl_m.def_id); let trait_m_predicates = tcx.predicates_of(trait_m.def_id); - // Create obligations for each predicate declared by the impl - // definition in the context of the trait's parameter - // environment. We can't just use `impl_env.caller_bounds`, - // however, because we want to replace all late-bound regions with - // region variables. - let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap()); - let mut hybrid_preds = impl_predicates.instantiate_identity(tcx); - - debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds); - // This is the only tricky bit of the new way we check implementation methods // We need to build a set of predicates where only the method-level bounds // are from the trait and we assume all other bounds from the implementation @@ -211,7 +201,9 @@ fn compare_method_predicate_entailment<'tcx>( // // We then register the obligations from the impl_m and check to see // if all constraints hold. - hybrid_preds.predicates.extend( + let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap()); + let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates; + hybrid_preds.extend( trait_m_predicates .instantiate_own(tcx, trait_to_placeholder_args) .map(|(predicate, _)| predicate), @@ -221,7 +213,7 @@ fn compare_method_predicate_entailment<'tcx>( // The key step here is to update the caller_bounds's predicates to be // the new hybrid bounds we computed. let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id); - let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds.predicates), Reveal::UserFacing); + let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause); let infcx = &tcx.infer_ctxt().build(); @@ -229,6 +221,10 @@ fn compare_method_predicate_entailment<'tcx>( debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds()); + // Create obligations for each predicate declared by the impl + // definition in the context of the hybrid param-env. This makes + // sure that the impl's method's where clauses are not more + // restrictive than the trait's method (and the impl itself). let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_args); for (predicate, span) in impl_m_own_bounds { let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); @@ -1759,14 +1755,14 @@ fn compare_const_predicate_entailment<'tcx>( // The predicates declared by the impl definition, the trait and the // associated const in the trait are assumed. let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap()); - let mut hybrid_preds = impl_predicates.instantiate_identity(tcx); - hybrid_preds.predicates.extend( + let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates; + hybrid_preds.extend( trait_ct_predicates .instantiate_own(tcx, trait_to_impl_args) .map(|(predicate, _)| predicate), ); - let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds.predicates), Reveal::UserFacing); + let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error( tcx, param_env, @@ -1892,8 +1888,8 @@ fn compare_type_predicate_entailment<'tcx>( // The predicates declared by the impl definition, the trait and the // associated type in the trait are assumed. let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap()); - let mut hybrid_preds = impl_predicates.instantiate_identity(tcx); - hybrid_preds.predicates.extend( + let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates; + hybrid_preds.extend( trait_ty_predicates .instantiate_own(tcx, trait_to_impl_args) .map(|(predicate, _)| predicate), @@ -1903,7 +1899,7 @@ fn compare_type_predicate_entailment<'tcx>( let impl_ty_span = tcx.def_span(impl_ty_def_id); let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id); - let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds.predicates), Reveal::UserFacing); + let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause); let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new_with_diagnostics(&infcx); From 4dd2af5113c975f865da460f166ea0809cf51c3b Mon Sep 17 00:00:00 2001 From: Daan Sieben Date: Mon, 21 Oct 2024 10:58:54 +0200 Subject: [PATCH 066/366] feat: support initializeStopped setting --- src/tools/rust-analyzer/editors/code/package.json | 5 +++++ src/tools/rust-analyzer/editors/code/src/config.ts | 4 ++++ src/tools/rust-analyzer/editors/code/src/main.ts | 9 ++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index 6c7f402dc5f9..8005527d2fa1 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -349,6 +349,11 @@ "markdownDescription": "Whether to show the test explorer.", "default": false, "type": "boolean" + }, + "rust-analyzer.initializeStopped": { + "markdownDescription": "Do not start rust-analyzer server when the extension is activated.", + "default": false, + "type": "boolean" } } }, diff --git a/src/tools/rust-analyzer/editors/code/src/config.ts b/src/tools/rust-analyzer/editors/code/src/config.ts index abb4099f9f5e..67bc72f1e126 100644 --- a/src/tools/rust-analyzer/editors/code/src/config.ts +++ b/src/tools/rust-analyzer/editors/code/src/config.ts @@ -330,6 +330,10 @@ export class Config { get statusBarClickAction() { return this.get("statusBar.clickAction"); } + + get initializeStopped() { + return this.get("initializeStopped"); + } } export function prepareVSCodeConfig(resp: T): T { diff --git a/src/tools/rust-analyzer/editors/code/src/main.ts b/src/tools/rust-analyzer/editors/code/src/main.ts index 0ddc5619e994..fdf43f66f949 100644 --- a/src/tools/rust-analyzer/editors/code/src/main.ts +++ b/src/tools/rust-analyzer/editors/code/src/main.ts @@ -107,7 +107,14 @@ async function activateServer(ctx: Ctx): Promise { initializeDebugSessionTrackingAndRebuild(ctx); } - await ctx.start(); + if (ctx.config.initializeStopped) { + ctx.setServerStatus({ + health: "stopped", + }); + } else { + await ctx.start(); + } + return ctx; } From 657a9257106c2439ce8adb1ee4e933ace1763ed7 Mon Sep 17 00:00:00 2001 From: Noratrieb <48135649+Noratrieb@users.noreply.github.com> Date: Sun, 25 Aug 2024 00:32:25 +0200 Subject: [PATCH 067/366] Update rustc-hash to version 2 This brings in the new optimized algorithm that was shown to have small performance benefits for rustc. --- src/tools/rust-analyzer/Cargo.lock | 54 ++++++++++--------- src/tools/rust-analyzer/Cargo.toml | 2 +- .../rust-analyzer/crates/hir-ty/src/lib.rs | 7 +-- .../rust-analyzer/crates/ra-salsa/Cargo.toml | 2 +- 4 files changed, 34 insertions(+), 31 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index da65d8804949..951c7f8bbacc 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -73,7 +73,7 @@ dependencies = [ "intern", "la-arena 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "lz4_flex", - "rustc-hash", + "rustc-hash 2.0.0", "salsa", "semver", "span", @@ -161,7 +161,7 @@ dependencies = [ "expect-test", "intern", "oorandom", - "rustc-hash", + "rustc-hash 2.0.0", "syntax", "syntax-bridge", "tt", @@ -216,7 +216,7 @@ dependencies = [ "chalk-derive", "chalk-ir", "chalk-solve", - "rustc-hash", + "rustc-hash 1.1.0", "tracing", ] @@ -232,7 +232,7 @@ dependencies = [ "indexmap", "itertools", "petgraph", - "rustc-hash", + "rustc-hash 1.1.0", "tracing", ] @@ -513,7 +513,7 @@ dependencies = [ "hir-ty", "intern", "itertools", - "rustc-hash", + "rustc-hash 2.0.0", "smallvec", "span", "stdx", @@ -547,7 +547,7 @@ dependencies = [ "mbe", "ra-ap-rustc_abi", "ra-ap-rustc_parse_format", - "rustc-hash", + "rustc-hash 2.0.0", "rustc_apfloat", "smallvec", "span", @@ -577,7 +577,7 @@ dependencies = [ "limit", "mbe", "parser", - "rustc-hash", + "rustc-hash 2.0.0", "smallvec", "span", "stdx", @@ -616,7 +616,7 @@ dependencies = [ "ra-ap-rustc_abi", "ra-ap-rustc_index", "ra-ap-rustc_pattern_analysis", - "rustc-hash", + "rustc-hash 2.0.0", "rustc_apfloat", "scoped-tls", "smallvec", @@ -737,7 +737,7 @@ dependencies = [ "parser", "profile", "rayon", - "rustc-hash", + "rustc-hash 2.0.0", "span", "stdx", "syntax", @@ -834,7 +834,7 @@ version = "0.0.0" dependencies = [ "dashmap", "hashbrown", - "rustc-hash", + "rustc-hash 2.0.0", "sptr", "triomphe", ] @@ -1051,7 +1051,7 @@ dependencies = [ "intern", "parser", "ra-ap-rustc_lexer", - "rustc-hash", + "rustc-hash 2.0.0", "smallvec", "span", "stdx", @@ -1345,7 +1345,7 @@ dependencies = [ "indexmap", "intern", "paths", - "rustc-hash", + "rustc-hash 2.0.0", "serde", "serde_json", "span", @@ -1435,7 +1435,7 @@ dependencies = [ "itertools", "la-arena 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "paths", - "rustc-hash", + "rustc-hash 2.0.0", "semver", "serde", "serde_json", @@ -1555,7 +1555,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "273d5f72926a58c7eea27aebc898d1d5b32d23d2342f692a94a2cf8746aa4a2f" dependencies = [ "ra-ap-rustc_index", - "rustc-hash", + "rustc-hash 1.1.0", "rustc_apfloat", "smallvec", "tracing", @@ -1640,7 +1640,7 @@ dependencies = [ "countme", "hashbrown", "memoffset", - "rustc-hash", + "rustc-hash 1.1.0", "text-size", ] @@ -1680,7 +1680,7 @@ dependencies = [ "profile", "project-model", "rayon", - "rustc-hash", + "rustc-hash 2.0.0", "scip", "semver", "serde", @@ -1717,6 +1717,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +[[package]] +name = "rustc-hash" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152" + [[package]] name = "rustc_apfloat" version = "0.2.1+llvm-462a31f5a5ab" @@ -1746,7 +1752,7 @@ dependencies = [ "oorandom", "parking_lot", "rand", - "rustc-hash", + "rustc-hash 2.0.0", "salsa-macros", "smallvec", "tracing", @@ -1898,7 +1904,7 @@ version = "0.0.0" dependencies = [ "hashbrown", "la-arena 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-hash", + "rustc-hash 2.0.0", "salsa", "stdx", "syntax", @@ -1967,7 +1973,7 @@ dependencies = [ "ra-ap-rustc_lexer", "rayon", "rowan", - "rustc-hash", + "rustc-hash 2.0.0", "rustc_apfloat", "smol_str", "stdx", @@ -1983,7 +1989,7 @@ version = "0.0.0" dependencies = [ "intern", "parser", - "rustc-hash", + "rustc-hash 2.0.0", "span", "stdx", "syntax", @@ -2000,7 +2006,7 @@ dependencies = [ "cfg", "hir-expand", "intern", - "rustc-hash", + "rustc-hash 2.0.0", "span", "stdx", "test-utils", @@ -2014,7 +2020,7 @@ dependencies = [ "dissimilar", "paths", "profile", - "rustc-hash", + "rustc-hash 2.0.0", "stdx", "text-size", "tracing", @@ -2361,7 +2367,7 @@ dependencies = [ "indexmap", "nohash-hasher", "paths", - "rustc-hash", + "rustc-hash 2.0.0", "stdx", "tracing", ] @@ -2374,7 +2380,7 @@ dependencies = [ "notify", "paths", "rayon", - "rustc-hash", + "rustc-hash 2.0.0", "stdx", "tracing", "vfs", diff --git a/src/tools/rust-analyzer/Cargo.toml b/src/tools/rust-analyzer/Cargo.toml index 17cefe941e57..397c68319de4 100644 --- a/src/tools/rust-analyzer/Cargo.toml +++ b/src/tools/rust-analyzer/Cargo.toml @@ -136,7 +136,7 @@ process-wrap = { version = "8.0.2", features = ["std"] } pulldown-cmark-to-cmark = "10.0.4" pulldown-cmark = { version = "0.9.0", default-features = false } rayon = "1.8.0" -rustc-hash = "1.1.0" +rustc-hash = "2.0.0" semver = "1.0.14" serde = { version = "1.0.192", features = ["derive"] } serde_json = "1.0.108" diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs index 649cf88bb8da..70e580eeae90 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs @@ -51,10 +51,7 @@ mod test_db; #[cfg(test)] mod tests; -use std::{ - collections::hash_map::Entry, - hash::{BuildHasherDefault, Hash}, -}; +use std::{collections::hash_map::Entry, hash::Hash}; use base_db::ra_salsa::InternValueTrivial; use chalk_ir::{ @@ -245,7 +242,7 @@ impl MemoryMap { match self { MemoryMap::Empty => Ok(Default::default()), MemoryMap::Simple(m) => transform((&0, m)).map(|(addr, val)| { - let mut map = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default()); + let mut map = FxHashMap::with_capacity_and_hasher(1, rustc_hash::FxBuildHasher); map.insert(addr, val); map }), diff --git a/src/tools/rust-analyzer/crates/ra-salsa/Cargo.toml b/src/tools/rust-analyzer/crates/ra-salsa/Cargo.toml index b81e780337fd..f8a3156fe407 100644 --- a/src/tools/rust-analyzer/crates/ra-salsa/Cargo.toml +++ b/src/tools/rust-analyzer/crates/ra-salsa/Cargo.toml @@ -17,7 +17,7 @@ indexmap = "2.1.0" lock_api = "0.4" tracing = "0.1" parking_lot = "0.12.1" -rustc-hash = "1.0" +rustc-hash = "2.0.0" smallvec = "1.0.0" oorandom = "11" triomphe = "0.1.11" From bbaeeb82623d1a8503efa59cb0cb10537c8d9500 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 3 Sep 2024 12:50:24 +0200 Subject: [PATCH 068/366] Fix recursive_adt fixture --- .../rust-analyzer/crates/hir-ty/src/consteval/tests.rs | 7 ++++--- src/tools/rust-analyzer/crates/hir-ty/src/lib.rs | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/consteval/tests.rs b/src/tools/rust-analyzer/crates/hir-ty/src/consteval/tests.rs index 7093fcadcb03..0a8bfaa70f86 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/consteval/tests.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/consteval/tests.rs @@ -95,7 +95,8 @@ fn check_answer(ra_fixture: &str, check: impl FnOnce(&[u8], &MemoryMap)) { fn pretty_print_err(e: ConstEvalError, db: TestDB) -> String { let mut err = String::new(); let span_formatter = |file, range| format!("{file:?} {range:?}"); - let edition = db.crate_graph()[db.test_crate()].edition; + let edition = + db.crate_graph()[*db.crate_graph().crates_in_topological_order().last().unwrap()].edition; match e { ConstEvalError::MirLowerError(e) => e.pretty_print(&mut err, &db, span_formatter, edition), ConstEvalError::MirEvalError(e) => e.pretty_print(&mut err, &db, span_formatter, edition), @@ -2896,7 +2897,7 @@ fn recursive_adt() { { const VARIANT_TAG_TREE: TagTree = TagTree::Choice( &[ - TagTree::Leaf, + TAG_TREE, ], ); VARIANT_TAG_TREE @@ -2905,6 +2906,6 @@ fn recursive_adt() { TAG_TREE }; "#, - |e| matches!(e, ConstEvalError::MirEvalError(MirEvalError::StackOverflow)), + |e| matches!(e, ConstEvalError::MirLowerError(MirLowerError::Loop)), ); } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs index 70e580eeae90..9c1d8bcf36f0 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lib.rs @@ -51,7 +51,7 @@ mod test_db; #[cfg(test)] mod tests; -use std::{collections::hash_map::Entry, hash::Hash}; +use std::hash::Hash; use base_db::ra_salsa::InternValueTrivial; use chalk_ir::{ @@ -62,10 +62,11 @@ use chalk_ir::{ use either::Either; use hir_def::{hir::ExprId, type_ref::Rawness, CallableDefId, GeneralConstId, TypeOrConstParamId}; use hir_expand::name::Name; +use indexmap::{map::Entry, IndexMap}; use intern::{sym, Symbol}; use la_arena::{Arena, Idx}; use mir::{MirEvalError, VTableMap}; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; use span::Edition; use syntax::ast::{make, ConstArg}; use traits::FnTrait; @@ -196,7 +197,7 @@ pub enum MemoryMap { #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct ComplexMemoryMap { - memory: FxHashMap>, + memory: IndexMap, FxBuildHasher>, vtable: VTableMap, } From e9da1dce058e9e2f9c66203f4b467e42aa4c45ad Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 3 Sep 2024 13:22:37 +0200 Subject: [PATCH 069/366] Update ide tests --- .../ide-assists/src/handlers/bool_to_enum.rs | 3 +- .../crates/ide-completion/src/render.rs | 2 +- .../crates/ide/src/annotations.rs | 274 +++++++++--------- .../rust-analyzer/crates/ide/src/runnables.rs | 12 +- .../test_data/highlight_rainbow.html | 12 +- .../rust-analyzer/crates/mbe/src/benchmark.rs | 2 +- .../docs/user/generated_config.adoc | 44 +-- .../rust-analyzer/editors/code/package.json | 44 +-- 8 files changed, 197 insertions(+), 196 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/bool_to_enum.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/bool_to_enum.rs index cd5fe0f86269..c035c59ffca6 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/bool_to_enum.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/bool_to_enum.rs @@ -1095,6 +1095,7 @@ fn main() { #[test] fn field_enum_cross_file() { + // FIXME: The import is missing check_assist( bool_to_enum, r#" @@ -1132,7 +1133,7 @@ fn foo() { } //- /main.rs -use foo::{Bool, Foo}; +use foo::Foo; mod foo; diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render.rs index f2e9de9382c6..4dd171142f9c 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render.rs @@ -1853,8 +1853,8 @@ fn f() { A { bar: b$0 }; } expect![[r#" fn bar() [type+name] fn baz() [type] - ex baz() [type] ex bar() [type] + ex baz() [type] st A [] fn f() [] "#]], diff --git a/src/tools/rust-analyzer/crates/ide/src/annotations.rs b/src/tools/rust-analyzer/crates/ide/src/annotations.rs index 8e0166a4a76c..121a463c9f15 100644 --- a/src/tools/rust-analyzer/crates/ide/src/annotations.rs +++ b/src/tools/rust-analyzer/crates/ide/src/annotations.rs @@ -286,6 +286,20 @@ fn main() { ), }, }, + Annotation { + range: 53..57, + kind: HasReferences { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 53, + }, + data: Some( + [], + ), + }, + }, Annotation { range: 53..57, kind: Runnable( @@ -305,20 +319,6 @@ fn main() { }, ), }, - Annotation { - range: 53..57, - kind: HasReferences { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 53, - }, - data: Some( - [], - ), - }, - }, ] "#]], ); @@ -336,6 +336,20 @@ fn main() { "#, expect![[r#" [ + Annotation { + range: 7..11, + kind: HasImpls { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 7, + }, + data: Some( + [], + ), + }, + }, Annotation { range: 7..11, kind: HasReferences { @@ -358,13 +372,13 @@ fn main() { }, }, Annotation { - range: 7..11, - kind: HasImpls { + range: 17..21, + kind: HasReferences { pos: FilePositionWrapper { file_id: FileId( 0, ), - offset: 7, + offset: 17, }, data: Some( [], @@ -390,20 +404,6 @@ fn main() { }, ), }, - Annotation { - range: 17..21, - kind: HasReferences { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 17, - }, - data: Some( - [], - ), - }, - }, ] "#]], ); @@ -425,6 +425,30 @@ fn main() { "#, expect![[r#" [ + Annotation { + range: 7..11, + kind: HasImpls { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 7, + }, + data: Some( + [ + NavigationTarget { + file_id: FileId( + 0, + ), + full_range: 36..64, + focus_range: 57..61, + name: "impl", + kind: Impl, + }, + ], + ), + }, + }, Annotation { range: 7..11, kind: HasReferences { @@ -452,30 +476,6 @@ fn main() { ), }, }, - Annotation { - range: 7..11, - kind: HasImpls { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 7, - }, - data: Some( - [ - NavigationTarget { - file_id: FileId( - 0, - ), - full_range: 36..64, - focus_range: 57..61, - name: "impl", - kind: Impl, - }, - ], - ), - }, - }, Annotation { range: 20..31, kind: HasImpls { @@ -521,20 +521,6 @@ fn main() { ), }, }, - Annotation { - range: 69..73, - kind: HasReferences { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 69, - }, - data: Some( - [], - ), - }, - }, Annotation { range: 69..73, kind: Runnable( @@ -554,6 +540,20 @@ fn main() { }, ), }, + Annotation { + range: 69..73, + kind: HasReferences { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 69, + }, + data: Some( + [], + ), + }, + }, ] "#]], ); @@ -567,6 +567,20 @@ fn main() {} "#, expect![[r#" [ + Annotation { + range: 3..7, + kind: HasReferences { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 3, + }, + data: Some( + [], + ), + }, + }, Annotation { range: 3..7, kind: Runnable( @@ -586,20 +600,6 @@ fn main() {} }, ), }, - Annotation { - range: 3..7, - kind: HasReferences { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 3, - }, - data: Some( - [], - ), - }, - }, ] "#]], ); @@ -621,6 +621,30 @@ fn main() { "#, expect![[r#" [ + Annotation { + range: 7..11, + kind: HasImpls { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 7, + }, + data: Some( + [ + NavigationTarget { + file_id: FileId( + 0, + ), + full_range: 14..56, + focus_range: 19..23, + name: "impl", + kind: Impl, + }, + ], + ), + }, + }, Annotation { range: 7..11, kind: HasReferences { @@ -648,30 +672,6 @@ fn main() { ), }, }, - Annotation { - range: 7..11, - kind: HasImpls { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 7, - }, - data: Some( - [ - NavigationTarget { - file_id: FileId( - 0, - ), - full_range: 14..56, - focus_range: 19..23, - name: "impl", - kind: Impl, - }, - ], - ), - }, - }, Annotation { range: 33..44, kind: HasReferences { @@ -693,20 +693,6 @@ fn main() { ), }, }, - Annotation { - range: 61..65, - kind: HasReferences { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 61, - }, - data: Some( - [], - ), - }, - }, Annotation { range: 61..65, kind: Runnable( @@ -726,6 +712,20 @@ fn main() { }, ), }, + Annotation { + range: 61..65, + kind: HasReferences { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 61, + }, + data: Some( + [], + ), + }, + }, ] "#]], ); @@ -744,20 +744,6 @@ mod tests { "#, expect![[r#" [ - Annotation { - range: 3..7, - kind: HasReferences { - pos: FilePositionWrapper { - file_id: FileId( - 0, - ), - offset: 3, - }, - data: Some( - [], - ), - }, - }, Annotation { range: 3..7, kind: Runnable( @@ -777,6 +763,20 @@ mod tests { }, ), }, + Annotation { + range: 3..7, + kind: HasReferences { + pos: FilePositionWrapper { + file_id: FileId( + 0, + ), + offset: 3, + }, + data: Some( + [], + ), + }, + }, Annotation { range: 18..23, kind: Runnable( @@ -876,7 +876,7 @@ struct Foo; [ Annotation { range: 0..71, - kind: HasReferences { + kind: HasImpls { pos: FilePositionWrapper { file_id: FileId( 0, @@ -890,7 +890,7 @@ struct Foo; }, Annotation { range: 0..71, - kind: HasImpls { + kind: HasReferences { pos: FilePositionWrapper { file_id: FileId( 0, diff --git a/src/tools/rust-analyzer/crates/ide/src/runnables.rs b/src/tools/rust-analyzer/crates/ide/src/runnables.rs index 38dc522789d7..3bbbd36c1b1a 100644 --- a/src/tools/rust-analyzer/crates/ide/src/runnables.rs +++ b/src/tools/rust-analyzer/crates/ide/src/runnables.rs @@ -1350,18 +1350,18 @@ mod tests { file_id: FileId( 0, ), - full_range: 121..185, - focus_range: 136..145, - name: "foo2_test", + full_range: 52..115, + focus_range: 67..75, + name: "foo_test", kind: Function, }, NavigationTarget { file_id: FileId( 0, ), - full_range: 52..115, - focus_range: 67..75, - name: "foo_test", + full_range: 121..185, + focus_range: 136..145, + name: "foo2_test", kind: Function, }, ] diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_rainbow.html b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_rainbow.html index 5d51b1497895..a4449b5d8d8e 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_rainbow.html +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_rainbow.html @@ -46,14 +46,14 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd .unresolved_reference { color: #FC5555; text-decoration: wavy underline; }

fn main() {
-    let hello = "hello";
-    let x = hello.to_string();
-    let y = hello.to_string();
+    let hello = "hello";
+    let x = hello.to_string();
+    let y = hello.to_string();
 
-    let x = "other color please!";
-    let y = x.to_string();
+    let x = "other color please!";
+    let y = x.to_string();
 }
 
 fn bar() {
-    let mut hello = "hello";
+    let mut hello = "hello";
 }
\ No newline at end of file diff --git a/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs b/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs index 9e4ef1407408..8ebdf1daa6c2 100644 --- a/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs +++ b/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs @@ -55,7 +55,7 @@ fn benchmark_expand_macro_rules() { }) .sum() }; - assert_eq!(hash, 69413); + assert_eq!(hash, 76353); } fn macro_rules_fixtures() -> FxHashMap { diff --git a/src/tools/rust-analyzer/docs/user/generated_config.adoc b/src/tools/rust-analyzer/docs/user/generated_config.adoc index babeb4272be6..463718835b91 100644 --- a/src/tools/rust-analyzer/docs/user/generated_config.adoc +++ b/src/tools/rust-analyzer/docs/user/generated_config.adoc @@ -95,8 +95,8 @@ avoid checking unnecessary things. Default: ---- { - "debug_assertions": null, - "miri": null + "miri": null, + "debug_assertions": null } ---- List of cfg options to enable with the given values. @@ -321,18 +321,10 @@ Enables completions of private items and fields that are defined in the current Default: ---- { - "Arc::new": { - "postfix": "arc", - "body": "Arc::new(${receiver})", - "requires": "std::sync::Arc", - "description": "Put the expression into an `Arc`", - "scope": "expr" - }, - "Rc::new": { - "postfix": "rc", - "body": "Rc::new(${receiver})", - "requires": "std::rc::Rc", - "description": "Put the expression into an `Rc`", + "Ok": { + "postfix": "ok", + "body": "Ok(${receiver})", + "description": "Wrap the expression in a `Result::Ok`", "scope": "expr" }, "Box::pin": { @@ -342,10 +334,11 @@ Default: "description": "Put the expression into a pinned `Box`", "scope": "expr" }, - "Err": { - "postfix": "err", - "body": "Err(${receiver})", - "description": "Wrap the expression in a `Result::Err`", + "Arc::new": { + "postfix": "arc", + "body": "Arc::new(${receiver})", + "requires": "std::sync::Arc", + "description": "Put the expression into an `Arc`", "scope": "expr" }, "Some": { @@ -354,10 +347,17 @@ Default: "description": "Wrap the expression in an `Option::Some`", "scope": "expr" }, - "Ok": { - "postfix": "ok", - "body": "Ok(${receiver})", - "description": "Wrap the expression in a `Result::Ok`", + "Err": { + "postfix": "err", + "body": "Err(${receiver})", + "description": "Wrap the expression in a `Result::Err`", + "scope": "expr" + }, + "Rc::new": { + "postfix": "rc", + "body": "Rc::new(${receiver})", + "requires": "std::rc::Rc", + "description": "Put the expression into an `Rc`", "scope": "expr" } } diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index 6c7f402dc5f9..70bb5f2447a2 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -728,8 +728,8 @@ "rust-analyzer.cargo.cfgs": { "markdownDescription": "List of cfg options to enable with the given values.", "default": { - "debug_assertions": null, - "miri": null + "miri": null, + "debug_assertions": null }, "type": "object" } @@ -1152,18 +1152,10 @@ "rust-analyzer.completion.snippets.custom": { "markdownDescription": "Custom completion snippets.", "default": { - "Arc::new": { - "postfix": "arc", - "body": "Arc::new(${receiver})", - "requires": "std::sync::Arc", - "description": "Put the expression into an `Arc`", - "scope": "expr" - }, - "Rc::new": { - "postfix": "rc", - "body": "Rc::new(${receiver})", - "requires": "std::rc::Rc", - "description": "Put the expression into an `Rc`", + "Ok": { + "postfix": "ok", + "body": "Ok(${receiver})", + "description": "Wrap the expression in a `Result::Ok`", "scope": "expr" }, "Box::pin": { @@ -1173,10 +1165,11 @@ "description": "Put the expression into a pinned `Box`", "scope": "expr" }, - "Err": { - "postfix": "err", - "body": "Err(${receiver})", - "description": "Wrap the expression in a `Result::Err`", + "Arc::new": { + "postfix": "arc", + "body": "Arc::new(${receiver})", + "requires": "std::sync::Arc", + "description": "Put the expression into an `Arc`", "scope": "expr" }, "Some": { @@ -1185,10 +1178,17 @@ "description": "Wrap the expression in an `Option::Some`", "scope": "expr" }, - "Ok": { - "postfix": "ok", - "body": "Ok(${receiver})", - "description": "Wrap the expression in a `Result::Ok`", + "Err": { + "postfix": "err", + "body": "Err(${receiver})", + "description": "Wrap the expression in a `Result::Err`", + "scope": "expr" + }, + "Rc::new": { + "postfix": "rc", + "body": "Rc::new(${receiver})", + "requires": "std::rc::Rc", + "description": "Put the expression into an `Rc`", "scope": "expr" } }, From 2adc6c33c9bb2a42a8d06ddcc719f2a2a7e56825 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Mon, 21 Oct 2024 11:34:19 +0200 Subject: [PATCH 070/366] fix: FIx mbe bench tests being iteration order dependent --- src/tools/rust-analyzer/crates/mbe/src/benchmark.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs b/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs index 8ebdf1daa6c2..270bc05a4ee2 100644 --- a/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs +++ b/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs @@ -3,6 +3,7 @@ use intern::Symbol; use rustc_hash::FxHashMap; use span::{Edition, Span}; +use stdx::itertools::Itertools; use syntax::{ ast::{self, HasName}, AstNode, @@ -27,9 +28,10 @@ fn benchmark_parse_macro_rules() { let hash: usize = { let _pt = bench("mbe parse macro rules"); rules - .values() - .map(|it| { - DeclarativeMacro::parse_macro_rules(it, |_| span::Edition::CURRENT).rules.len() + .into_iter() + .sorted_by_key(|(id, _)| id.clone()) + .map(|(_, it)| { + DeclarativeMacro::parse_macro_rules(&it, |_| span::Edition::CURRENT).rules.len() }) .sum() }; @@ -55,12 +57,13 @@ fn benchmark_expand_macro_rules() { }) .sum() }; - assert_eq!(hash, 76353); + assert_eq!(hash, 65720); } fn macro_rules_fixtures() -> FxHashMap { macro_rules_fixtures_tt() .into_iter() + .sorted_by_key(|(id, _)| id.clone()) .map(|(id, tt)| (id, DeclarativeMacro::parse_macro_rules(&tt, |_| span::Edition::CURRENT))) .collect() } @@ -93,7 +96,7 @@ fn invocation_fixtures( let mut seed = 123456789; let mut res = Vec::new(); - for (name, it) in rules { + for (name, it) in rules.iter().sorted_by_key(|&(id, _)| id) { for rule in it.rules.iter() { // Generate twice for _ in 0..2 { From 8b4a94f261d77683684dbf4b9f4b1eac0dc5956a Mon Sep 17 00:00:00 2001 From: Khanh Duong Quoc Date: Sat, 19 Oct 2024 20:22:36 +0900 Subject: [PATCH 071/366] fix: private items are shown in completions for modules in fn body --- .../crates/hir-def/src/visibility.rs | 6 ++---- .../crates/ide-completion/src/tests/pattern.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs b/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs index 11d91513f127..3aeb88047a0d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs @@ -139,13 +139,11 @@ impl Visibility { let def_map_block = def_map.block_id(); loop { match (to_module.block, def_map_block) { - // to_module is not a block, so there is no parent def map to use + // `to_module` is not a block, so there is no parent def map to use. (None, _) => (), + // `to_module` is at `def_map`'s block, no need to move further. (Some(a), Some(b)) if a == b => { cov_mark::hit!(is_visible_from_same_block_def_map); - if let Some(parent) = def_map.parent() { - to_module = parent; - } } _ => { if let Some(parent) = to_module.def_map(db).parent() { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/tests/pattern.rs b/src/tools/rust-analyzer/crates/ide-completion/src/tests/pattern.rs index bd3e7c72bcd6..a5eb0369b142 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/tests/pattern.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/tests/pattern.rs @@ -923,3 +923,21 @@ fn foo() { "#]], ); } + +#[test] +fn private_item_in_module_in_function_body() { + check_empty( + r#" +fn main() { + mod foo { + struct Private; + pub struct Public; + } + foo::$0 +} +"#, + expect![[r#" + st Public Public + "#]], + ); +} From e2dd95feb5b01caf030606cd50334b37fcc82250 Mon Sep 17 00:00:00 2001 From: roife Date: Mon, 21 Oct 2024 21:58:39 +0800 Subject: [PATCH 072/366] refactor add_keywords in ide-completions for clarity --- .../src/completions/item_list.rs | 107 ++++++++++-------- 1 file changed, 58 insertions(+), 49 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs index 188337740833..83c994726a1e 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs @@ -75,73 +75,82 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option let in_item_list = matches!(kind, Some(ItemListKind::SourceFile | ItemListKind::Module) | None); let in_assoc_non_trait_impl = matches!(kind, Some(ItemListKind::Impl | ItemListKind::Trait)); + let in_extern_block = matches!(kind, Some(ItemListKind::ExternBlock)); let in_trait = matches!(kind, Some(ItemListKind::Trait)); let in_trait_impl = matches!(kind, Some(ItemListKind::TraitImpl(_))); let in_inherent_impl = matches!(kind, Some(ItemListKind::Impl)); - let no_vis_qualifiers = ctx.qualifier_ctx.vis_node.is_none(); let in_block = kind.is_none(); - let missing_qualifiers = [ - ctx.qualifier_ctx.unsafe_tok.is_none().then_some(("unsafe", "unsafe $0")), - ctx.qualifier_ctx.async_tok.is_none().then_some(("async", "async $0")), - ]; + let no_vis_qualifiers = ctx.qualifier_ctx.vis_node.is_none(); + let has_unsafe_kw = ctx.qualifier_ctx.unsafe_tok.is_some(); + let has_async_kw = ctx.qualifier_ctx.async_tok.is_some(); - if !in_trait_impl { - // handle qualifier tokens - if missing_qualifiers.iter().any(Option::is_none) { - // only complete missing qualifiers - missing_qualifiers.iter().filter_map(|x| *x).for_each(|(kw, snippet)| { - add_keyword(kw, snippet); - }); + // We handle completions for trait-impls in [`item_list::trait_impl`] + if in_trait_impl { + return; + } - if in_item_list || in_assoc_non_trait_impl { - add_keyword("fn", "fn $1($2) {\n $0\n}"); - } - - if ctx.qualifier_ctx.unsafe_tok.is_some() && in_item_list { - add_keyword("trait", "trait $1 {\n $0\n}"); - if no_vis_qualifiers { - add_keyword("impl", "impl $1 {\n $0\n}"); - } - } - - return; + // Some keywords are invalid after non-vis qualifiers, so we handle them first. + if has_unsafe_kw || has_async_kw { + if !has_unsafe_kw { + add_keyword("unsafe", "unsafe $0"); + } + if !has_async_kw { + add_keyword("async", "async $0"); } - if in_item_list { - add_keyword("enum", "enum $1 {\n $0\n}"); - add_keyword("mod", "mod $0"); - add_keyword("static", "static $0"); - add_keyword("struct", "struct $0"); + if in_item_list || in_assoc_non_trait_impl { + add_keyword("fn", "fn $1($2) {\n $0\n}"); + } + + if has_unsafe_kw && in_item_list { add_keyword("trait", "trait $1 {\n $0\n}"); - add_keyword("union", "union $1 {\n $0\n}"); - add_keyword("use", "use $0"); if no_vis_qualifiers { add_keyword("impl", "impl $1 {\n $0\n}"); } } - if !in_trait && !in_block && no_vis_qualifiers { - add_keyword("pub(crate)", "pub(crate) $0"); - add_keyword("pub(super)", "pub(super) $0"); - add_keyword("pub", "pub $0"); - } + return; + } - if in_extern_block { - add_keyword("fn", "fn $1($2);"); - } else { - if !in_inherent_impl { - if !in_trait { - add_keyword("extern", "extern $0"); - } - add_keyword("type", "type $0"); - } + // ...and the rest deals with cases without any non-vis qualifiers. - add_keyword("fn", "fn $1($2) {\n $0\n}"); - add_keyword("unsafe", "unsafe $0"); - add_keyword("const", "const $0"); - add_keyword("async", "async $0"); + // Visibility qualifiers + if !in_trait && !in_block && no_vis_qualifiers { + add_keyword("pub(crate)", "pub(crate) $0"); + add_keyword("pub(super)", "pub(super) $0"); + add_keyword("pub", "pub $0"); + } + + // Keywords that are valid in `item_list` + if in_item_list { + add_keyword("enum", "enum $1 {\n $0\n}"); + add_keyword("mod", "mod $0"); + add_keyword("static", "static $0"); + add_keyword("struct", "struct $0"); + add_keyword("trait", "trait $1 {\n $0\n}"); + add_keyword("union", "union $1 {\n $0\n}"); + add_keyword("use", "use $0"); + if no_vis_qualifiers { + add_keyword("impl", "impl $1 {\n $0\n}"); } } + + if in_extern_block { + add_keyword("fn", "fn $1($2);"); + add_keyword("static", "static $1: $2;"); + } else { + if !in_inherent_impl { + if !in_trait { + add_keyword("extern", "extern $0"); + } + add_keyword("type", "type $0"); + } + + add_keyword("fn", "fn $1($2) {\n $0\n}"); + add_keyword("unsafe", "unsafe $0"); + add_keyword("const", "const $0"); + add_keyword("async", "async $0"); + } } From ba3b7c7961d3f08885b1734beb27f7fbd2d68246 Mon Sep 17 00:00:00 2001 From: roife Date: Mon, 21 Oct 2024 22:13:09 +0800 Subject: [PATCH 073/366] feat: better completions for extern blcoks --- .../src/completions/item_list.rs | 48 +++++++++++----- .../ide-completion/src/completions/keyword.rs | 1 + .../crates/ide-completion/src/context.rs | 8 ++- .../ide-completion/src/context/analysis.rs | 10 +++- .../ide-completion/src/tests/item_list.rs | 55 +++++++++++++++++++ 5 files changed, 104 insertions(+), 18 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs index 83c994726a1e..2c4a880eb334 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs @@ -76,7 +76,10 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option let in_item_list = matches!(kind, Some(ItemListKind::SourceFile | ItemListKind::Module) | None); let in_assoc_non_trait_impl = matches!(kind, Some(ItemListKind::Impl | ItemListKind::Trait)); - let in_extern_block = matches!(kind, Some(ItemListKind::ExternBlock)); + let in_extern_block = matches!(kind, Some(ItemListKind::ExternBlock { .. })); + let in_unsafe_extern_block = + matches!(kind, Some(ItemListKind::ExternBlock { is_unsafe: true })); + let in_trait = matches!(kind, Some(ItemListKind::Trait)); let in_trait_impl = matches!(kind, Some(ItemListKind::TraitImpl(_))); let in_inherent_impl = matches!(kind, Some(ItemListKind::Impl)); @@ -85,6 +88,7 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option let no_vis_qualifiers = ctx.qualifier_ctx.vis_node.is_none(); let has_unsafe_kw = ctx.qualifier_ctx.unsafe_tok.is_some(); let has_async_kw = ctx.qualifier_ctx.async_tok.is_some(); + let has_safe_kw = ctx.qualifier_ctx.safe_tok.is_some(); // We handle completions for trait-impls in [`item_list::trait_impl`] if in_trait_impl { @@ -92,22 +96,31 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option } // Some keywords are invalid after non-vis qualifiers, so we handle them first. - if has_unsafe_kw || has_async_kw { - if !has_unsafe_kw { - add_keyword("unsafe", "unsafe $0"); - } - if !has_async_kw { - add_keyword("async", "async $0"); - } + if has_unsafe_kw || has_async_kw || has_safe_kw { + if in_extern_block { + add_keyword("fn", "fn $1($2);"); + add_keyword("static", "static $1: $2;"); + } else { + if !has_unsafe_kw { + add_keyword("unsafe", "unsafe $0"); + } + if !has_async_kw { + add_keyword("async", "async $0"); + } - if in_item_list || in_assoc_non_trait_impl { - add_keyword("fn", "fn $1($2) {\n $0\n}"); - } + if in_item_list || in_assoc_non_trait_impl { + add_keyword("fn", "fn $1($2) {\n $0\n}"); + } - if has_unsafe_kw && in_item_list { - add_keyword("trait", "trait $1 {\n $0\n}"); - if no_vis_qualifiers { - add_keyword("impl", "impl $1 {\n $0\n}"); + if has_unsafe_kw && in_item_list { + add_keyword("trait", "trait $1 {\n $0\n}"); + if no_vis_qualifiers { + add_keyword("impl", "impl $1 {\n $0\n}"); + } + } + + if !has_async_kw && no_vis_qualifiers && in_item_list { + add_keyword("extern", "extern $0"); } } @@ -138,6 +151,11 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option } if in_extern_block { + add_keyword("unsafe", "unsafe $0"); + if in_unsafe_extern_block { + add_keyword("safe", "safe $0"); + } + add_keyword("fn", "fn $1($2);"); add_keyword("static", "static $1: $2;"); } else { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/keyword.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/keyword.rs index 0acb87872f5e..71ca6e99494e 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/keyword.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/keyword.rs @@ -58,6 +58,7 @@ mod tests { r"fn my_fn() { unsafe $0 }", expect![[r#" kw async + kw extern kw fn kw impl kw trait diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs index e49a9e3b0640..0e1302ff2ef4 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs @@ -48,12 +48,16 @@ pub(crate) struct QualifierCtx { // TODO: Add try_tok and default_tok pub(crate) async_tok: Option, pub(crate) unsafe_tok: Option, + pub(crate) safe_tok: Option, pub(crate) vis_node: Option, } impl QualifierCtx { pub(crate) fn none(&self) -> bool { - self.async_tok.is_none() && self.unsafe_tok.is_none() && self.vis_node.is_none() + self.async_tok.is_none() + && self.unsafe_tok.is_none() + && self.safe_tok.is_none() + && self.vis_node.is_none() } } @@ -229,7 +233,7 @@ pub(crate) enum ItemListKind { Impl, TraitImpl(Option), Trait, - ExternBlock, + ExternBlock { is_unsafe: bool }, } #[derive(Debug)] diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs index 1f9e3edf625d..468ad81ad2f8 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs @@ -1108,7 +1108,14 @@ fn classify_name_ref( }, None => return None, } }, - ast::ExternItemList(_) => PathKind::Item { kind: ItemListKind::ExternBlock }, + ast::ExternItemList(it) => { + let exn_blk = it.syntax().parent().and_then(ast::ExternBlock::cast); + PathKind::Item { + kind: ItemListKind::ExternBlock { + is_unsafe: exn_blk.and_then(|it| it.unsafe_token()).is_some(), + } + } + }, ast::SourceFile(_) => PathKind::Item { kind: ItemListKind::SourceFile }, _ => return None, } @@ -1310,6 +1317,7 @@ fn classify_name_ref( match token.kind() { SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token), SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token), + SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token), _ => {} } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/tests/item_list.rs b/src/tools/rust-analyzer/crates/ide-completion/src/tests/item_list.rs index 532d4928eff9..dfef8fa472dd 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/tests/item_list.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/tests/item_list.rs @@ -124,6 +124,7 @@ fn after_unsafe_token() { r#"unsafe $0"#, expect![[r#" kw async + kw extern kw fn kw impl kw trait @@ -495,3 +496,57 @@ type O = $0; ", ) } + +#[test] +fn inside_extern_blocks() { + // Should suggest `fn`, `static`, `unsafe` + check( + r#"extern { $0 }"#, + expect![[r#" + ma makro!(…) macro_rules! makro + md module + kw crate:: + kw fn + kw pub + kw pub(crate) + kw pub(super) + kw self:: + kw static + kw unsafe + "#]], + ); + + // Should suggest `fn`, `static`, `safe`, `unsafe` + check( + r#"unsafe extern { $0 }"#, + expect![[r#" + ma makro!(…) macro_rules! makro + md module + kw crate:: + kw fn + kw pub + kw pub(crate) + kw pub(super) + kw safe + kw self:: + kw static + kw unsafe + "#]], + ); + + check( + r#"unsafe extern { pub safe $0 }"#, + expect![[r#" + kw fn + kw static + "#]], + ); + + check( + r#"unsafe extern { pub unsafe $0 }"#, + expect![[r#" + kw fn + kw static + "#]], + ) +} From ea03a064110de6837f70e9795a9660991e588d03 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Mon, 21 Oct 2024 16:58:34 +0200 Subject: [PATCH 074/366] fix: Fix token downmapping failing for include! inputs --- .../crates/hir-expand/src/builtin/fn_macro.rs | 25 ++++----- .../rust-analyzer/crates/hir/src/semantics.rs | 52 +++++++++++-------- .../crates/hir/src/semantics/source_to_def.rs | 28 ++++++++-- .../crates/ide/src/goto_definition.rs | 38 ++++++++++++++ .../crates/ide/src/references.rs | 21 ++++++++ .../rust-analyzer/crates/syntax/src/ptr.rs | 2 +- 6 files changed, 125 insertions(+), 41 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs b/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs index d04225b87227..4894c7a93112 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs @@ -5,19 +5,20 @@ use cfg::CfgExpr; use either::Either; use intern::{sym, Symbol}; use mbe::{expect_fragment, DelimiterKind}; -use span::{Edition, EditionedFileId, Span, SpanAnchor, SyntaxContextId, ROOT_ERASED_FILE_AST_ID}; +use span::{Edition, EditionedFileId, Span}; use stdx::format_to; use syntax::{ format_smolstr, unescape::{unescape_byte, unescape_char, unescape_unicode, Mode}, }; -use syntax_bridge::parse_to_token_tree; +use syntax_bridge::syntax_node_to_token_tree; use crate::{ builtin::quote::{dollar_crate, quote}, db::ExpandDatabase, hygiene::{span_with_call_site_ctxt, span_with_def_site_ctxt}, name, + span_map::SpanMap, tt::{self, DelimSpan}, ExpandError, ExpandResult, HirFileIdExt, Lookup as _, MacroCallId, }; @@ -739,18 +740,14 @@ fn include_expand( return ExpandResult::new(tt::Subtree::empty(DelimSpan { open: span, close: span }), e) } }; - match parse_to_token_tree( - file_id.edition(), - SpanAnchor { file_id, ast_id: ROOT_ERASED_FILE_AST_ID }, - SyntaxContextId::ROOT, - &db.file_text(file_id.file_id()), - ) { - Some(it) => ExpandResult::ok(it), - None => ExpandResult::new( - tt::Subtree::empty(DelimSpan { open: span, close: span }), - ExpandError::other(span, "failed to parse included file"), - ), - } + let span_map = db.real_span_map(file_id); + // FIXME: Parse errors + ExpandResult::ok(syntax_node_to_token_tree( + &db.parse(file_id).syntax_node(), + SpanMap::RealSpanMap(span_map), + span, + syntax_bridge::DocCommentDesugarMode::ProcMacro, + )) } pub fn include_input_to_file_id( diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index b27f1fbb5db1..3eac33ce9909 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -892,29 +892,8 @@ impl<'db> SemanticsImpl<'db> { f: &mut dyn FnMut(InFile, SyntaxContextId) -> ControlFlow, ) -> Option { let _p = tracing::info_span!("descend_into_macros_impl").entered(); - let (sa, span, file_id) = token - .parent() - .and_then(|parent| { - self.analyze_impl(InRealFile::new(file_id, &parent).into(), None, false) - }) - .and_then(|sa| { - let file_id = sa.file_id.file_id()?; - Some(( - sa, - self.db.real_span_map(file_id).span_for_range(token.text_range()), - HirFileId::from(file_id), - )) - })?; - let mut m_cache = self.macro_call_cache.borrow_mut(); - let def_map = sa.resolver.def_map(); - - // A stack of tokens to process, along with the file they came from - // These are tracked to know which macro calls we still have to look into - // the tokens themselves aren't that interesting as the span that is being used to map - // things down never changes. - let mut stack: Vec<(_, SmallVec<[_; 2]>)> = - vec![(file_id, smallvec![(token, SyntaxContextId::ROOT)])]; + let span = self.db.real_span_map(file_id).span_for_range(token.text_range()); // Process the expansion of a call, pushing all tokens with our span in the expansion back onto our stack let process_expansion_for_token = |stack: &mut Vec<_>, macro_file| { @@ -926,7 +905,6 @@ impl<'db> SemanticsImpl<'db> { .map(SmallVec::<[_; 2]>::from_iter), ) })?; - // we have found a mapping for the token if the vec is non-empty let res = mapped_tokens.is_empty().not().then_some(()); // requeue the tokens we got from mapping our current token down @@ -934,6 +912,33 @@ impl<'db> SemanticsImpl<'db> { res }; + // A stack of tokens to process, along with the file they came from + // These are tracked to know which macro calls we still have to look into + // the tokens themselves aren't that interesting as the span that is being used to map + // things down never changes. + let mut stack: Vec<(_, SmallVec<[_; 2]>)> = vec![]; + let include = self.s2d_cache.borrow_mut().get_or_insert_include_for(self.db, file_id); + match include { + Some(include) => { + // include! inputs are always from real files, so they only need to be handled once upfront + process_expansion_for_token(&mut stack, include)?; + } + None => { + stack.push((file_id.into(), smallvec![(token, SyntaxContextId::ROOT)])); + } + } + + let (file_id, tokens) = stack.first()?; + // make sure we pick the token in the expanded include if we encountered an include, + // otherwise we'll get the wrong semantics + let sa = + tokens.first()?.0.parent().and_then(|parent| { + self.analyze_impl(InFile::new(*file_id, &parent), None, false) + })?; + + let mut m_cache = self.macro_call_cache.borrow_mut(); + let def_map = sa.resolver.def_map(); + // Filters out all tokens that contain the given range (usually the macro call), any such // token is redundant as the corresponding macro call has already been processed let filter_duplicates = |tokens: &mut SmallVec<_>, range: TextRange| { @@ -1011,6 +1016,7 @@ impl<'db> SemanticsImpl<'db> { ) { call.as_macro_file() } else { + // FIXME: This is wrong, the SourceAnalyzer might be invalid here sa.expand(self.db, mcall.as_ref())? }; m_cache.insert(mcall, it); diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs b/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs index fd6d52d6c9df..389778b44ed9 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs @@ -104,7 +104,7 @@ use hir_expand::{ }; use rustc_hash::FxHashMap; use smallvec::SmallVec; -use span::{FileId, MacroFileId}; +use span::{EditionedFileId, FileId, MacroFileId}; use stdx::impl_from; use syntax::{ ast::{self, HasName}, @@ -118,9 +118,27 @@ pub(super) struct SourceToDefCache { pub(super) dynmap_cache: FxHashMap<(ChildContainer, HirFileId), DynMap>, expansion_info_cache: FxHashMap, pub(super) file_to_def_cache: FxHashMap>, + pub(super) included_file_cache: FxHashMap>, } impl SourceToDefCache { + pub(super) fn get_or_insert_include_for( + &mut self, + db: &dyn HirDatabase, + file: EditionedFileId, + ) -> Option { + if let Some(&m) = self.included_file_cache.get(&file) { + return m; + } + self.included_file_cache.insert(file, None); + for &crate_id in db.relevant_crates(file.into()).iter() { + db.include_macro_invoc(crate_id).iter().for_each(|&(macro_call_id, file_id)| { + self.included_file_cache.insert(file_id, Some(MacroFileId { macro_call_id })); + }); + } + self.included_file_cache.get(&file).copied().flatten() + } + pub(super) fn get_or_insert_expansion( &mut self, sema: &SemanticsImpl<'_>, @@ -163,9 +181,13 @@ impl SourceToDefCtx<'_, '_> { .include_macro_invoc(crate_id) .iter() .filter(|&&(_, file_id)| file_id == file) - .flat_map(|(call, _)| { + .flat_map(|&(macro_call_id, file_id)| { + self.cache + .included_file_cache + .insert(file_id, Some(MacroFileId { macro_call_id })); modules( - call.lookup(self.db.upcast()) + macro_call_id + .lookup(self.db.upcast()) .kind .file_id() .original_file(self.db.upcast()) diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index c61b2ba84f2e..4cbcb6ed050f 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -497,6 +497,44 @@ fn func_in_include() { //^^^^^^^^^^^^^^^ } +fn foo() { + func_in_include$0(); +} +"#, + ); + } + + #[test] + fn goto_def_in_included_file_inside_mod() { + check( + r#" +//- minicore:include +//- /main.rs +mod a { + include!("b.rs"); +} +//- /b.rs +fn func_in_include() { + //^^^^^^^^^^^^^^^ +} +fn foo() { + func_in_include$0(); +} +"#, + ); + + check( + r#" +//- minicore:include +//- /main.rs +mod a { + include!("a.rs"); +} +//- /a.rs +fn func_in_include() { + //^^^^^^^^^^^^^^^ +} + fn foo() { func_in_include$0(); } diff --git a/src/tools/rust-analyzer/crates/ide/src/references.rs b/src/tools/rust-analyzer/crates/ide/src/references.rs index 64d717f88ddd..e7cb8a253f40 100644 --- a/src/tools/rust-analyzer/crates/ide/src/references.rs +++ b/src/tools/rust-analyzer/crates/ide/src/references.rs @@ -2750,4 +2750,25 @@ impl Foo { "#]], ); } + + #[test] + fn goto_ref_on_included_file() { + check( + r#" +//- minicore:include +//- /lib.rs +include!("foo.rs"); +fn howdy() { + let _ = FOO; +} +//- /foo.rs +const FOO$0: i32 = 0; +"#, + expect![[r#" + FOO Const FileId(1) 0..19 6..9 + + FileId(0) 45..48 + "#]], + ); + } } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ptr.rs b/src/tools/rust-analyzer/crates/syntax/src/ptr.rs index ed4894f9b9c3..11b79e4e0ed7 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ptr.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ptr.rs @@ -27,7 +27,7 @@ pub struct AstPtr { _ty: PhantomData N>, } -impl std::fmt::Debug for AstPtr { +impl std::fmt::Debug for AstPtr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("AstPtr").field(&self.raw).finish() } From e46ea16fd83d751c487e994c0ab6a86c43659538 Mon Sep 17 00:00:00 2001 From: duncanproctor Date: Mon, 21 Oct 2024 11:29:05 -0400 Subject: [PATCH 075/366] GotoDefinition on a Range or InclusiveRange operator will link to the struct definition --- .../crates/ide-db/src/famous_defs.rs | 17 +++++- .../crates/ide/src/goto_definition.rs | 55 ++++++++++++++++++- 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs index ba6e50abf658..9b4273ab103e 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs @@ -1,7 +1,7 @@ //! See [`FamousDefs`]. use base_db::{CrateOrigin, LangCrateOrigin, SourceDatabase}; -use hir::{Crate, Enum, Function, Macro, Module, ScopeDef, Semantics, Trait}; +use hir::{Crate, Enum, Function, Macro, Module, ScopeDef, Semantics, Struct, Trait}; use crate::RootDatabase; @@ -102,6 +102,14 @@ impl FamousDefs<'_, '_> { self.find_trait("core:ops:Drop") } + pub fn core_ops_Range(&self) -> Option { + self.find_struct("core:ops:Range") + } + + pub fn core_ops_RangeInclusive(&self) -> Option { + self.find_struct("core:ops:RangeInclusive") + } + pub fn core_marker_Copy(&self) -> Option { self.find_trait("core:marker:Copy") } @@ -137,6 +145,13 @@ impl FamousDefs<'_, '_> { .flatten() } + fn find_struct(&self, path: &str) -> Option { + match self.find_def(path)? { + hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Struct(it))) => Some(it), + _ => None, + } + } + fn find_trait(&self, path: &str) -> Option { match self.find_def(path)? { hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it), diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index c61b2ba84f2e..3ac7cc823ef2 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -5,7 +5,7 @@ use crate::{ navigation_target::{self, ToNav}, FilePosition, NavigationTarget, RangeInfo, TryToNav, UpmappingResult, }; -use hir::{AsAssocItem, AssocItem, FileRange, InFile, MacroFileIdExt, ModuleDef, Semantics}; +use hir::{Adt, AsAssocItem, AssocItem, FileRange, InFile, MacroFileIdExt, ModuleDef, Semantics}; use ide_db::{ base_db::{AnchoredPath, FileLoader, SourceDatabase}, defs::{Definition, IdentClass}, @@ -13,7 +13,7 @@ use ide_db::{ RootDatabase, SymbolKind, }; use itertools::Itertools; - +use ide_db::famous_defs::FamousDefs; use span::{Edition, FileId}; use syntax::{ ast::{self, HasLoopBody}, @@ -41,6 +41,22 @@ pub(crate) fn goto_definition( ) -> Option>> { let sema = &Semantics::new(db); let file = sema.parse_guess_edition(file_id).syntax().clone(); + + if let syntax::TokenAtOffset::Single(tok) = file.token_at_offset(offset) { + if let Some(module) = sema.file_to_module_def(file_id) { + let famous_defs = FamousDefs(sema, module.krate()); + let maybe_famous_struct = match tok.kind() { + T![..] => famous_defs.core_ops_Range(), + T![..=] => famous_defs.core_ops_RangeInclusive(), + _ => None + }; + if let Some(fstruct) = maybe_famous_struct { + let target = def_to_nav(db, Definition::Adt(Adt::Struct(fstruct))); + return Some(RangeInfo::new(tok.text_range(), target)); + } + } + } + let edition = sema.attach_first_edition(file_id).map(|it| it.edition()).unwrap_or(Edition::CURRENT); let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind { @@ -420,7 +436,7 @@ fn expr_to_nav( mod tests { use ide_db::FileRange; use itertools::Itertools; - + use syntax::SmolStr; use crate::fixture; #[track_caller] @@ -450,6 +466,39 @@ mod tests { assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {navs:?}") } + + #[test] + fn goto_def_range_inclusive() { + let ra_fixture = r#" +//- minicore: range +fn f(a: usize, b: usize) { + for _ in a..$0=b { + + } +} +"#; + let (analysis, position, _) = fixture::annotations(ra_fixture); + let mut navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; + let Some(target) = navs.pop() else { panic!("no target found") }; + assert_eq!(target.name, SmolStr::new_inline("RangeInclusive")); + } + + #[test] + fn goto_def_range_half_open() { + let ra_fixture = r#" +//- minicore: range +fn f(a: usize, b: usize) { + for _ in a.$0.b { + + } +} +"#; + let (analysis, position, _) = fixture::annotations(ra_fixture); + let mut navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; + let Some(target) = navs.pop() else { panic!("no target found") }; + assert_eq!(target.name, SmolStr::new_inline("Range")); + } + #[test] fn goto_def_in_included_file() { check( From 774201e3b631c488c8dff4ddb20f3988c2c7d21a Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Mon, 21 Oct 2024 19:34:41 +0300 Subject: [PATCH 076/366] don't stage-off to previous compiler when CI rustc is available Signed-off-by: onur-ozkan --- src/bootstrap/src/core/build_steps/test.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index e25b571acbac..c3c2b526586e 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1734,13 +1734,15 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the } else { // We need to properly build cargo using the suitable stage compiler. - // HACK: currently tool stages are off-by-one compared to compiler stages, i.e. if - // you give `tool::Cargo` a stage 1 rustc, it will cause stage 2 rustc to be built - // and produce a cargo built with stage 2 rustc. To fix this, we need to chop off - // the compiler stage by 1 to align with expected `./x test run-make --stage N` - // behavior, i.e. we need to pass `N - 1` compiler stage to cargo. See also Miri - // which does a similar hack. - let compiler = builder.compiler(builder.top_stage - 1, compiler.host); + let compiler = builder.download_rustc().then_some(compiler).unwrap_or_else(|| + // HACK: currently tool stages are off-by-one compared to compiler stages, i.e. if + // you give `tool::Cargo` a stage 1 rustc, it will cause stage 2 rustc to be built + // and produce a cargo built with stage 2 rustc. To fix this, we need to chop off + // the compiler stage by 1 to align with expected `./x test run-make --stage N` + // behavior, i.e. we need to pass `N - 1` compiler stage to cargo. See also Miri + // which does a similar hack. + builder.compiler(builder.top_stage - 1, compiler.host)); + builder.ensure(tool::Cargo { compiler, target: compiler.host }) }; From d567fcc3018e8a9b09cbbd1a56c2f8bbf7e56438 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 21 Oct 2024 16:06:58 +0100 Subject: [PATCH 077/366] abi/compatibility: also test Option-like types --- tests/ui/abi/compatibility.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index 28c8063a9231..33d67360ff11 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -211,6 +211,15 @@ impl Clone for Zst { } } +enum Either { + Left(T), + Right(U), +} +enum Either2 { + Left(T), + Right(U, ()), +} + #[repr(C)] enum ReprCEnum { Variant1, @@ -328,7 +337,8 @@ mod unsized_ { test_transparent_unsized!(dyn_trait, dyn Any); } -// RFC 3391 . +// RFC 3391 , including the +// extension ratified at . macro_rules! test_nonnull { ($name:ident, $t:ty) => { mod $name { @@ -340,6 +350,12 @@ macro_rules! test_nonnull { test_abi_compatible!(result_ok_zst, Result, $t); test_abi_compatible!(result_err_arr, Result<$t, [i8; 0]>, $t); test_abi_compatible!(result_ok_arr, Result<[i8; 0], $t>, $t); + test_abi_compatible!(result_err_void, Result<$t, Void>, $t); + test_abi_compatible!(result_ok_void, Result, $t); + test_abi_compatible!(either_err_zst, Either<$t, Zst>, $t); + test_abi_compatible!(either_ok_zst, Either, $t); + test_abi_compatible!(either2_err_zst, Either2<$t, Zst>, $t); + test_abi_compatible!(either2_err_arr, Either2<$t, [i8; 0]>, $t); } } } From 1dcfa271443b4d3a608e656e203a987a5cb07e60 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Sat, 19 Oct 2024 17:47:16 +0200 Subject: [PATCH 078/366] Move COGNITIVE_COMPLEXITY to use macro again --- compiler/rustc_lint/src/shadowed_into_iter.rs | 2 +- compiler/rustc_lint_defs/src/lib.rs | 6 +- .../clippy_lints/src/cognitive_complexity.rs | 55 +++++++------------ src/tools/clippy/clippy_lints/src/ctfe.rs | 1 - .../clippy_lints/src/declare_clippy_lint.rs | 30 ++++++---- 5 files changed, 45 insertions(+), 49 deletions(-) diff --git a/compiler/rustc_lint/src/shadowed_into_iter.rs b/compiler/rustc_lint/src/shadowed_into_iter.rs index 33a4ae606632..a73904cd7769 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -64,7 +64,7 @@ declare_lint! { }; } -#[derive(Copy, Clone, Default)] +#[derive(Copy, Clone)] pub(crate) struct ShadowedIntoIter; impl_lint_pass!(ShadowedIntoIter => [ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER]); diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 418caa699e2b..601784f97323 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -904,15 +904,15 @@ macro_rules! declare_tool_lint { $(, @eval_always = $eval_always:literal)? $(, @feature_gate = $gate:ident;)? ) => ( - $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?} + $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?} ); ( $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, report_in_external_macro: $rep:expr - $(, @feature_gate = $gate:ident;)? $(, @eval_always = $eval_always: literal)? + $(, @feature_gate = $gate:ident;)? ) => ( - $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?} + $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?} ); ( $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index 91cb8b78ba8c..477435236a52 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -8,44 +8,31 @@ use core::ops::ControlFlow; use rustc_ast::ast::Attribute; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, Expr, ExprKind, FnDecl}; -use rustc_lint::Level::Allow; -use rustc_lint::{LateContext, LateLintPass, Lint, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::impl_lint_pass; use rustc_span::def_id::LocalDefId; use rustc_span::{Span, sym}; -use crate::LintInfo; - -pub static COGNITIVE_COMPLEXITY: &Lint = &Lint { - name: &"clippy::COGNITIVE_COMPLEXITY", - default_level: Allow, - desc: "functions that should be split up into multiple functions", - edition_lint_opts: None, - report_in_external_macro: true, - future_incompatible: None, - is_externally_loaded: true, - crate_level_only: false, - eval_always: true, - ..Lint::default_fields_for_macro() -}; -pub(crate) static COGNITIVE_COMPLEXITY_INFO: &'static LintInfo = &LintInfo { - lint: &COGNITIVE_COMPLEXITY, - category: crate::LintCategory::Nursery, - explanation: r"### What it does -Checks for methods with high cognitive complexity. - -### Why is this bad? -Methods of high cognitive complexity tend to be hard to both read and maintain. -Also LLVM will tend to optimize small methods better. - -### Known problems -Sometimes it's hard to find a way to reduce the complexity. - -### Example -You'll see it when you get the warning.", - version: Some("1.35.0"), - location: "clippy_lints/src/cognitive_complexity.rs#L47", -}; +declare_clippy_lint! { + /// ### What it does + /// Checks for methods with high cognitive complexity. + /// + /// ### Why is this bad? + /// Methods of high cognitive complexity tend to be hard to + /// both read and maintain. Also LLVM will tend to optimize small methods better. + /// + /// ### Known problems + /// Sometimes it's hard to find a way to reduce the + /// complexity. + /// + /// ### Example + /// You'll see it when you get the warning. + #[clippy::version = "1.35.0"] + pub COGNITIVE_COMPLEXITY, + nursery, + "functions that should be split up into multiple functions" + @eval_always = true +} pub struct CognitiveComplexity { limit: LimitStack, diff --git a/src/tools/clippy/clippy_lints/src/ctfe.rs b/src/tools/clippy/clippy_lints/src/ctfe.rs index 93d0ad789beb..2fe37a64db6a 100644 --- a/src/tools/clippy/clippy_lints/src/ctfe.rs +++ b/src/tools/clippy/clippy_lints/src/ctfe.rs @@ -8,7 +8,6 @@ use rustc_span::Span; /// Ensures that Constant-time Function Evaluation is being done (specifically, MIR lint passes). /// As Clippy deactivates codegen, this lint ensures that CTFE (used in hard errors) is still ran. -#[clippy::version = "1.82.0"] pub static CLIPPY_CTFE: &Lint = &Lint { name: &"clippy::CLIPPY_CTFE", default_level: Deny, diff --git a/src/tools/clippy/clippy_lints/src/declare_clippy_lint.rs b/src/tools/clippy/clippy_lints/src/declare_clippy_lint.rs index b1e39c70baa2..a785a9d377c5 100644 --- a/src/tools/clippy/clippy_lints/src/declare_clippy_lint.rs +++ b/src/tools/clippy/clippy_lints/src/declare_clippy_lint.rs @@ -9,6 +9,7 @@ macro_rules! declare_clippy_lint { $desc:literal, $version_expr:expr, $version_lit:literal + $(, $eval_always: literal)? ) => { rustc_session::declare_tool_lint! { $(#[doc = $lit])* @@ -17,6 +18,7 @@ macro_rules! declare_clippy_lint { $category, $desc, report_in_external_macro:true + $(, @eval_always = $eval_always)? } pub(crate) static ${concat($lint_name, _INFO)}: &'static crate::LintInfo = &crate::LintInfo { @@ -33,11 +35,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, restriction, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Allow, crate::LintCategory::Restriction, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; ( @@ -46,12 +49,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, style, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Warn, crate::LintCategory::Style, $desc, - Some($version), $version - + Some($version), $version $(, $eval_always)? } }; ( @@ -60,11 +63,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, correctness, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Deny, crate::LintCategory::Correctness, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; @@ -74,11 +78,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, perf, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Warn, crate::LintCategory::Perf, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; ( @@ -87,11 +92,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, complexity, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Warn, crate::LintCategory::Complexity, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; ( @@ -100,11 +106,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, suspicious, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Warn, crate::LintCategory::Suspicious, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; ( @@ -113,11 +120,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, nursery, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Allow, crate::LintCategory::Nursery, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; ( @@ -126,11 +134,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, pedantic, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Allow, crate::LintCategory::Pedantic, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; ( @@ -139,11 +148,12 @@ macro_rules! declare_clippy_lint { pub $lint_name:ident, cargo, $desc:literal + $(@eval_always = $eval_always: literal)? ) => { declare_clippy_lint! {@ $(#[doc = $lit])* pub $lint_name, Allow, crate::LintCategory::Cargo, $desc, - Some($version), $version + Some($version), $version $(, $eval_always)? } }; From ad27b8225f5ea209b6109a86f9972dad97611f7f Mon Sep 17 00:00:00 2001 From: roife Date: Tue, 22 Oct 2024 01:31:57 +0800 Subject: [PATCH 079/366] minor: refactor completions in item_list --- .../src/completions/item_list.rs | 51 +++++++++---------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs index 2c4a880eb334..3ab341e4eded 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list.rs @@ -29,7 +29,9 @@ pub(crate) fn complete_item_list( kind: &ItemListKind, ) { let _p = tracing::info_span!("complete_item_list").entered(); - if path_ctx.is_trivial_path() { + + // We handle completions for trait-impls in [`item_list::trait_impl`] + if path_ctx.is_trivial_path() && !matches!(kind, ItemListKind::TraitImpl(_)) { add_keywords(acc, ctx, Some(kind)); } @@ -81,7 +83,6 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option matches!(kind, Some(ItemListKind::ExternBlock { is_unsafe: true })); let in_trait = matches!(kind, Some(ItemListKind::Trait)); - let in_trait_impl = matches!(kind, Some(ItemListKind::TraitImpl(_))); let in_inherent_impl = matches!(kind, Some(ItemListKind::Impl)); let in_block = kind.is_none(); @@ -90,38 +91,34 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option let has_async_kw = ctx.qualifier_ctx.async_tok.is_some(); let has_safe_kw = ctx.qualifier_ctx.safe_tok.is_some(); - // We handle completions for trait-impls in [`item_list::trait_impl`] - if in_trait_impl { + // Some keywords are invalid after non-vis qualifiers, so we handle them first. + if (has_unsafe_kw || has_safe_kw) && in_extern_block { + add_keyword("fn", "fn $1($2);"); + add_keyword("static", "static $1: $2;"); return; } - // Some keywords are invalid after non-vis qualifiers, so we handle them first. - if has_unsafe_kw || has_async_kw || has_safe_kw { - if in_extern_block { - add_keyword("fn", "fn $1($2);"); - add_keyword("static", "static $1: $2;"); - } else { - if !has_unsafe_kw { - add_keyword("unsafe", "unsafe $0"); - } - if !has_async_kw { - add_keyword("async", "async $0"); - } + if has_unsafe_kw || has_async_kw { + if !has_unsafe_kw { + add_keyword("unsafe", "unsafe $0"); + } + if !has_async_kw { + add_keyword("async", "async $0"); + } - if in_item_list || in_assoc_non_trait_impl { - add_keyword("fn", "fn $1($2) {\n $0\n}"); - } + if in_item_list || in_assoc_non_trait_impl { + add_keyword("fn", "fn $1($2) {\n $0\n}"); + } - if has_unsafe_kw && in_item_list { - add_keyword("trait", "trait $1 {\n $0\n}"); - if no_vis_qualifiers { - add_keyword("impl", "impl $1 {\n $0\n}"); - } + if has_unsafe_kw && in_item_list { + add_keyword("trait", "trait $1 {\n $0\n}"); + if no_vis_qualifiers { + add_keyword("impl", "impl $1 {\n $0\n}"); } + } - if !has_async_kw && no_vis_qualifiers && in_item_list { - add_keyword("extern", "extern $0"); - } + if !has_async_kw && no_vis_qualifiers && in_item_list { + add_keyword("extern", "extern $0"); } return; From e91267f3f094a6f5d16aef0abb864fca4bc8c9f4 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 22 Oct 2024 00:03:09 +0000 Subject: [PATCH 080/366] Move tests --- src/tools/tidy/src/issues.txt | 20 +++++++++---------- .../assoc-type-const-bound-usage-0.rs | 0 .../assoc-type-const-bound-usage-0.stderr | 0 .../assoc-type-const-bound-usage-1.rs | 0 .../assoc-type-const-bound-usage-1.stderr | 0 .../const-traits}/assoc-type.rs | 0 .../const-traits}/assoc-type.stderr | 0 .../const-traits}/attr-misuse.rs | 0 .../const-traits}/attr-misuse.stderr | 0 .../const-traits}/auxiliary/cross-crate.rs | 0 .../const-traits}/auxiliary/staged-api.rs | 0 .../call-const-trait-method-fail.rs | 0 .../call-const-trait-method-fail.stderr | 0 .../call-const-trait-method-pass.rs | 0 .../call-const-trait-method-pass.stderr | 0 .../const-traits}/call-generic-in-impl.rs | 0 .../const-traits}/call-generic-in-impl.stderr | 0 .../call-generic-method-chain.rs | 0 .../call-generic-method-chain.stderr | 0 .../call-generic-method-dup-bound.rs | 0 .../call-generic-method-dup-bound.stderr | 0 .../const-traits}/call-generic-method-fail.rs | 0 .../call-generic-method-nonconst-bound.rs | 0 .../call-generic-method-nonconst.rs | 0 .../call-generic-method-nonconst.stderr | 0 .../const-traits}/call-generic-method-pass.rs | 0 .../call-generic-method-pass.stderr | 0 .../const-traits}/call.rs | 0 .../const-traits}/const-and-non-const-impl.rs | 0 .../const-and-non-const-impl.stderr | 0 .../const-bound-on-not-const-associated-fn.rs | 0 ...st-bound-on-not-const-associated-fn.stderr | 0 .../const-bounds-non-const-trait.rs | 0 .../const-bounds-non-const-trait.stderr | 0 .../const-check-fns-in-const-impl.rs | 0 .../const-check-fns-in-const-impl.stderr | 0 .../const-closure-parse-not-item.rs | 0 .../const-closure-parse-not-item.stderr | 0 .../const-closure-trait-method-fail.rs | 0 .../const-closure-trait-method-fail.stderr | 0 .../const-closure-trait-method.rs | 0 .../const-closure-trait-method.stderr | 0 .../const-traits}/const-closures.rs | 0 .../const-traits}/const-closures.stderr | 0 .../const-default-method-bodies.rs | 0 .../const-default-method-bodies.stderr | 0 .../const-traits}/const-drop-bound.rs | 0 .../const-traits}/const-drop-bound.stderr | 0 .../const-drop-fail-2.precise.stderr | 0 .../const-traits}/const-drop-fail-2.rs | 0 .../const-traits}/const-drop-fail-2.stderr | 0 .../const-drop-fail-2.stock.stderr | 0 .../const-drop-fail.precise.stderr | 0 .../const-traits}/const-drop-fail.rs | 0 .../const-drop-fail.stock.stderr | 0 .../const-traits}/const-drop.precise.stderr | 0 .../const-traits}/const-drop.rs | 0 .../const-traits}/const-drop.stock.stderr | 0 .../const-fns-are-early-bound.rs | 0 .../const-fns-are-early-bound.stderr | 0 .../const-traits}/const-impl-norecover.rs | 0 .../const-traits}/const-impl-norecover.stderr | 0 .../const-traits}/const-impl-recovery.rs | 0 .../const-traits}/const-impl-recovery.stderr | 0 .../const-impl-requires-const-trait.rs | 0 .../const-impl-requires-const-trait.stderr | 0 .../const-traits}/const-impl-trait.rs | 0 .../const-traits}/const-impl-trait.stderr | 0 .../const-trait-bounds-trait-objects.rs | 0 .../const-trait-bounds-trait-objects.stderr | 0 .../const-traits}/const-trait-bounds.rs | 0 .../const-traits}/const-trait-bounds.stderr | 0 .../const_derives/derive-const-gate.rs | 0 .../const_derives/derive-const-gate.stderr | 0 .../derive-const-non-const-type.rs | 0 .../derive-const-non-const-type.stderr | 0 .../const_derives/derive-const-use.rs | 0 .../const_derives/derive-const-use.stderr | 0 .../const_derives/derive-const-with-params.rs | 0 .../derive-const-with-params.stderr | 0 ...ross-crate-default-method-body-is-const.rs | 0 .../const-traits}/cross-crate.gatednc.stderr | 0 .../const-traits}/cross-crate.rs | 0 .../const-traits}/cross-crate.stock.stderr | 0 .../const-traits}/cross-crate.stocknc.stderr | 0 ...ault-method-body-is-const-body-checking.rs | 0 ...ault-method-body-is-const-same-trait-ck.rs | 0 ...-method-body-is-const-same-trait-ck.stderr | 0 ...lt-method-body-is-const-with-staged-api.rs | 0 .../do-not-const-check-override.rs | 0 .../const-traits}/do-not-const-check.rs | 0 .../effects/auxiliary/cross-crate.rs | 0 ...nst_closure-const_trait_impl-ice-113381.rs | 0 .../effects/effect-param-infer.rs | 0 .../const-traits}/effects/fallback.rs | 0 .../const-traits}/effects/group-traits.rs | 0 .../const-traits}/effects/helloworld.rs | 0 .../ice-112822-expected-type-for-param.rs | 0 .../ice-112822-expected-type-for-param.stderr | 0 ...ice-113375-index-out-of-bounds-generics.rs | 0 .../const-traits}/effects/infer-fallback.rs | 0 .../const-traits}/effects/minicore.rs | 0 .../const-traits}/effects/minicore.stderr | 0 .../effects/mismatched_generic_args.rs | 0 .../effects/mismatched_generic_args.stderr | 0 .../no-explicit-const-params-cross-crate.rs | 0 ...o-explicit-const-params-cross-crate.stderr | 0 .../effects/no-explicit-const-params.rs | 0 .../effects/no-explicit-const-params.stderr | 0 .../const-traits}/effects/project.rs | 0 .../effects/span-bug-issue-121418.rs | 0 .../effects/span-bug-issue-121418.stderr | 0 .../effects/spec-effectvar-ice.rs | 0 .../effects/spec-effectvar-ice.stderr | 0 .../const-traits}/effects/trait-fn-const.rs | 0 .../effects/trait-fn-const.stderr | 0 .../with-without-next-solver.coherence.stderr | 0 .../effects/with-without-next-solver.rs | 0 .../with-without-next-solver.stock.stderr | 0 .../const-traits}/feature-gate.gated.stderr | 0 .../const-traits}/feature-gate.rs | 0 .../const-traits}/feature-gate.stock.stderr | 0 ...function-pointer-does-not-require-const.rs | 0 .../const-traits}/gate.rs | 0 .../const-traits}/gate.stderr | 0 .../const-traits}/generic-bound.rs | 0 .../const-traits}/generic-bound.stderr | 0 .../const-traits}/hir-const-check.rs | 0 .../const-traits}/hir-const-check.stderr | 0 .../ice-119717-constant-lifetime.rs | 0 .../ice-119717-constant-lifetime.stderr | 0 .../ice-120503-async-const-method.rs | 0 .../ice-120503-async-const-method.stderr | 0 .../const-traits}/ice-121536-const-method.rs | 0 .../ice-121536-const-method.stderr | 0 .../ice-123664-unexpected-bound-var.rs | 0 .../ice-123664-unexpected-bound-var.stderr | 0 ...-124857-combine-effect-const-infer-vars.rs | 0 ...857-combine-effect-const-infer-vars.stderr | 0 .../ice-126148-failed-to-normalize.rs | 0 .../ice-126148-failed-to-normalize.stderr | 0 .../const-traits}/impl-tilde-const-trait.rs | 0 .../impl-tilde-const-trait.stderr | 0 .../impl-with-default-fn-fail.rs | 0 .../impl-with-default-fn-fail.stderr | 0 .../impl-with-default-fn-pass.rs | 0 .../inherent-impl-const-bounds.rs | 0 .../const-traits}/inherent-impl.rs | 0 .../const-traits}/inherent-impl.stderr | 0 .../inline-incorrect-early-bound-in-ctfe.rs | 0 ...nline-incorrect-early-bound-in-ctfe.stderr | 0 .../const-traits}/issue-100222.rs | 0 .../const-traits}/issue-102156.rs | 0 .../const-traits}/issue-102156.stderr | 0 .../const-traits}/issue-102985.rs | 0 .../const-traits}/issue-102985.stderr | 0 .../const-traits}/issue-103677.rs | 0 .../const-traits}/issue-79450.rs | 0 .../const-traits}/issue-79450.stderr | 0 .../const-traits}/issue-88155.rs | 0 .../const-traits}/issue-88155.stderr | 0 .../const-traits}/issue-92111.rs | 0 .../const-traits}/issue-92111.stderr | 0 .../issue-92230-wf-super-trait-env.rs | 0 .../match-non-const-eq.gated.stderr | 0 .../const-traits}/match-non-const-eq.rs | 0 .../match-non-const-eq.stock.stderr | 0 ...e-bare-trait-objects-const-trait-bounds.rs | 0 ...onst-trait-bound-theoretical-regression.rs | 0 ...-trait-bound-theoretical-regression.stderr | 0 .../const-traits}/mbe-dyn-const-2015.rs | 0 ...utually-exclusive-trait-bound-modifiers.rs | 0 ...lly-exclusive-trait-bound-modifiers.stderr | 0 .../const-traits}/nested-closure.rs | 0 ...-const-op-const-closure-non-const-outer.rs | 0 ...st-op-const-closure-non-const-outer.stderr | 0 .../non-const-op-in-closure-in-const.rs | 0 .../non-const-op-in-closure-in-const.stderr | 0 ...fault-bound-non-const-specialized-bound.rs | 0 ...t-bound-non-const-specialized-bound.stderr | 0 .../const-default-const-specialized.rs | 0 .../const-default-const-specialized.stderr | 0 ...default-impl-non-const-specialized-impl.rs | 0 ...ult-impl-non-const-specialized-impl.stderr | 0 .../specialization/default-keyword.rs | 0 .../specialization/default-keyword.stderr | 0 .../issue-95186-specialize-on-tilde-const.rs | 0 ...sue-95186-specialize-on-tilde-const.stderr | 0 ...87-same-trait-bound-different-constness.rs | 0 ...ame-trait-bound-different-constness.stderr | 0 .../non-const-default-const-specialized.rs | 0 ...non-const-default-const-specialized.stderr | 0 .../const-traits}/specializing-constness-2.rs | 0 .../specializing-constness-2.stderr | 0 .../const-traits}/specializing-constness.rs | 0 .../specializing-constness.stderr | 0 .../const-traits}/staged-api-user-crate.rs | 0 .../staged-api-user-crate.stderr | 0 .../const-traits}/staged-api.rs | 0 .../const-traits}/staged-api.stable.stderr | 0 .../const-traits}/staged-api.unstable.stderr | 0 .../const-traits}/static-const-trait-bound.rs | 0 .../const-traits}/std-impl-gate.gated.stderr | 0 .../const-traits}/std-impl-gate.rs | 0 .../const-traits}/std-impl-gate.stock.stderr | 0 .../super-traits-fail-2.nn.stderr | 0 .../super-traits-fail-2.ny.stderr | 0 .../const-traits}/super-traits-fail-2.rs | 0 .../super-traits-fail-2.yn.stderr | 0 .../super-traits-fail-2.yy.stderr | 0 .../super-traits-fail-3.nn.stderr | 0 .../super-traits-fail-3.ny.stderr | 0 .../const-traits}/super-traits-fail-3.rs | 0 .../super-traits-fail-3.yn.stderr | 0 .../const-traits}/super-traits-fail.rs | 0 .../const-traits}/super-traits-fail.stderr | 0 .../const-traits}/super-traits.rs | 0 .../const-traits}/syntax.rs | 0 .../tilde-const-and-const-params.rs | 0 .../tilde-const-and-const-params.stderr | 0 .../tilde-const-assoc-fn-in-trait-impl.rs | 0 .../tilde-const-inherent-assoc-const-fn.rs | 0 .../tilde-const-invalid-places.rs | 0 .../tilde-const-invalid-places.stderr | 0 .../const-traits}/tilde-const-syntax.rs | 0 .../tilde-const-trait-assoc-tys.rs | 0 .../const-traits}/tilde-twice.rs | 0 .../const-traits}/tilde-twice.stderr | 0 .../trait-default-body-stability.rs | 0 .../trait-default-body-stability.stderr | 0 .../trait-method-ptr-in-consts-ice.rs | 0 .../const-traits}/trait-where-clause-const.rs | 0 .../trait-where-clause-const.stderr | 0 .../const-traits}/trait-where-clause-run.rs | 0 .../trait-where-clause-self-referential.rs | 0 .../const-traits}/trait-where-clause.rs | 0 .../const-traits}/trait-where-clause.stderr | 0 .../unsatisfied-const-trait-bound.rs | 0 .../unsatisfied-const-trait-bound.stderr | 0 239 files changed, 10 insertions(+), 10 deletions(-) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/assoc-type-const-bound-usage-0.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/assoc-type-const-bound-usage-0.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/assoc-type-const-bound-usage-1.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/assoc-type-const-bound-usage-1.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/assoc-type.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/assoc-type.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/attr-misuse.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/attr-misuse.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/auxiliary/cross-crate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/auxiliary/staged-api.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-const-trait-method-fail.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-const-trait-method-fail.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-const-trait-method-pass.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-const-trait-method-pass.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-in-impl.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-in-impl.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-chain.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-chain.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-dup-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-dup-bound.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-fail.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-nonconst-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-nonconst.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-nonconst.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-pass.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call-generic-method-pass.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/call.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-and-non-const-impl.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-and-non-const-impl.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-bound-on-not-const-associated-fn.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-bound-on-not-const-associated-fn.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-bounds-non-const-trait.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-bounds-non-const-trait.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-check-fns-in-const-impl.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-check-fns-in-const-impl.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closure-parse-not-item.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closure-parse-not-item.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closure-trait-method-fail.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closure-trait-method-fail.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closure-trait-method.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closure-trait-method.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closures.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-closures.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-default-method-bodies.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-default-method-bodies.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-bound.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail-2.precise.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail-2.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail-2.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail-2.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail.precise.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop-fail.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop.precise.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-drop.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-fns-are-early-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-fns-are-early-bound.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-norecover.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-norecover.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-recovery.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-recovery.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-requires-const-trait.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-requires-const-trait.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-trait.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-impl-trait.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-trait-bounds-trait-objects.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-trait-bounds-trait-objects.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-trait-bounds.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const-trait-bounds.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-gate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-gate.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-non-const-type.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-non-const-type.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-use.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-use.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-with-params.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/const_derives/derive-const-with-params.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/cross-crate-default-method-body-is-const.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/cross-crate.gatednc.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/cross-crate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/cross-crate.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/cross-crate.stocknc.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/default-method-body-is-const-body-checking.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/default-method-body-is-const-same-trait-ck.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/default-method-body-is-const-same-trait-ck.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/default-method-body-is-const-with-staged-api.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/do-not-const-check-override.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/do-not-const-check.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/auxiliary/cross-crate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/const_closure-const_trait_impl-ice-113381.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/effect-param-infer.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/fallback.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/group-traits.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/helloworld.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/ice-112822-expected-type-for-param.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/ice-112822-expected-type-for-param.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/ice-113375-index-out-of-bounds-generics.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/infer-fallback.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/minicore.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/minicore.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/mismatched_generic_args.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/mismatched_generic_args.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/no-explicit-const-params-cross-crate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/no-explicit-const-params-cross-crate.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/no-explicit-const-params.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/no-explicit-const-params.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/project.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/span-bug-issue-121418.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/span-bug-issue-121418.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/spec-effectvar-ice.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/spec-effectvar-ice.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/trait-fn-const.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/trait-fn-const.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/with-without-next-solver.coherence.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/with-without-next-solver.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/effects/with-without-next-solver.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/feature-gate.gated.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/feature-gate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/feature-gate.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/function-pointer-does-not-require-const.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/gate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/gate.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/generic-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/generic-bound.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/hir-const-check.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/hir-const-check.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-119717-constant-lifetime.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-119717-constant-lifetime.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-120503-async-const-method.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-120503-async-const-method.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-121536-const-method.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-121536-const-method.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-123664-unexpected-bound-var.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-123664-unexpected-bound-var.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-124857-combine-effect-const-infer-vars.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-124857-combine-effect-const-infer-vars.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-126148-failed-to-normalize.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/ice-126148-failed-to-normalize.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/impl-tilde-const-trait.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/impl-tilde-const-trait.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/impl-with-default-fn-fail.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/impl-with-default-fn-fail.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/impl-with-default-fn-pass.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/inherent-impl-const-bounds.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/inherent-impl.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/inherent-impl.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/inline-incorrect-early-bound-in-ctfe.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/inline-incorrect-early-bound-in-ctfe.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-100222.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-102156.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-102156.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-102985.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-102985.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-103677.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-79450.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-79450.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-88155.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-88155.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-92111.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-92111.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/issue-92230-wf-super-trait-env.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/match-non-const-eq.gated.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/match-non-const-eq.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/match-non-const-eq.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/mbe-bare-trait-objects-const-trait-bounds.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/mbe-const-trait-bound-theoretical-regression.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/mbe-const-trait-bound-theoretical-regression.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/mbe-dyn-const-2015.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/mutually-exclusive-trait-bound-modifiers.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/mutually-exclusive-trait-bound-modifiers.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/nested-closure.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/non-const-op-const-closure-non-const-outer.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/non-const-op-const-closure-non-const-outer.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/non-const-op-in-closure-in-const.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/non-const-op-in-closure-in-const.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/const-default-bound-non-const-specialized-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/const-default-bound-non-const-specialized-bound.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/const-default-const-specialized.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/const-default-const-specialized.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/const-default-impl-non-const-specialized-impl.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/const-default-impl-non-const-specialized-impl.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/default-keyword.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/default-keyword.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/issue-95186-specialize-on-tilde-const.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/issue-95186-specialize-on-tilde-const.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/issue-95187-same-trait-bound-different-constness.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/issue-95187-same-trait-bound-different-constness.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/non-const-default-const-specialized.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specialization/non-const-default-const-specialized.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specializing-constness-2.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specializing-constness-2.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specializing-constness.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/specializing-constness.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/staged-api-user-crate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/staged-api-user-crate.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/staged-api.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/staged-api.stable.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/staged-api.unstable.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/static-const-trait-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/std-impl-gate.gated.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/std-impl-gate.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/std-impl-gate.stock.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-2.nn.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-2.ny.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-2.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-2.yn.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-2.yy.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-3.nn.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-3.ny.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-3.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail-3.yn.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits-fail.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/super-traits.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/syntax.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-and-const-params.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-and-const-params.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-assoc-fn-in-trait-impl.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-inherent-assoc-const-fn.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-invalid-places.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-invalid-places.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-syntax.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-const-trait-assoc-tys.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-twice.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/tilde-twice.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-default-body-stability.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-default-body-stability.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-method-ptr-in-consts-ice.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-where-clause-const.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-where-clause-const.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-where-clause-run.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-where-clause-self-referential.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-where-clause.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/trait-where-clause.stderr (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/unsatisfied-const-trait-bound.rs (100%) rename tests/ui/{rfcs/rfc-2632-const-trait-impl => traits/const-traits}/unsatisfied-const-trait-bound.stderr (100%) diff --git a/src/tools/tidy/src/issues.txt b/src/tools/tidy/src/issues.txt index 97c42752c12d..94f8d23c1586 100644 --- a/src/tools/tidy/src/issues.txt +++ b/src/tools/tidy/src/issues.txt @@ -3720,16 +3720,6 @@ ui/rfcs/rfc-2497-if-let-chains/issue-99938.rs ui/rfcs/rfc-2528-type-changing-struct-update/issue-92010-trait-bound-not-satisfied.rs ui/rfcs/rfc-2528-type-changing-struct-update/issue-96878.rs ui/rfcs/rfc-2565-param-attrs/issue-64682-dropping-first-attrs-in-impl-fns.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-100222.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-102156.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-102985.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-103677.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-79450.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-88155.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-92111.rs -ui/rfcs/rfc-2632-const-trait-impl/issue-92230-wf-super-trait-env.rs -ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95186-specialize-on-tilde-const.rs -ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95187-same-trait-bound-different-constness.rs ui/rust-2018/issue-51008-1.rs ui/rust-2018/issue-51008.rs ui/rust-2018/issue-52202-use-suggestions.rs @@ -3983,6 +3973,16 @@ ui/traits/alias/issue-75983.rs ui/traits/alias/issue-83613.rs ui/traits/associated_type_bound/issue-51446.rs ui/traits/auxiliary/issue_89119_intercrate_caching.rs +ui/traits/const-traits/issue-100222.rs +ui/traits/const-traits/issue-102156.rs +ui/traits/const-traits/issue-102985.rs +ui/traits/const-traits/issue-103677.rs +ui/traits/const-traits/issue-79450.rs +ui/traits/const-traits/issue-88155.rs +ui/traits/const-traits/issue-92111.rs +ui/traits/const-traits/issue-92230-wf-super-trait-env.rs +ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs +ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs ui/traits/issue-103563.rs ui/traits/issue-104322.rs ui/traits/issue-105231.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-0.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-0.rs rename to tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-0.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-0.stderr rename to tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-1.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-1.rs rename to tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-1.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type-const-bound-usage-1.stderr rename to tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type.rs b/tests/ui/traits/const-traits/assoc-type.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type.rs rename to tests/ui/traits/const-traits/assoc-type.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type.stderr b/tests/ui/traits/const-traits/assoc-type.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/assoc-type.stderr rename to tests/ui/traits/const-traits/assoc-type.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/attr-misuse.rs b/tests/ui/traits/const-traits/attr-misuse.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/attr-misuse.rs rename to tests/ui/traits/const-traits/attr-misuse.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/attr-misuse.stderr b/tests/ui/traits/const-traits/attr-misuse.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/attr-misuse.stderr rename to tests/ui/traits/const-traits/attr-misuse.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/auxiliary/cross-crate.rs b/tests/ui/traits/const-traits/auxiliary/cross-crate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/auxiliary/cross-crate.rs rename to tests/ui/traits/const-traits/auxiliary/cross-crate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/auxiliary/staged-api.rs b/tests/ui/traits/const-traits/auxiliary/staged-api.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/auxiliary/staged-api.rs rename to tests/ui/traits/const-traits/auxiliary/staged-api.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-fail.rs b/tests/ui/traits/const-traits/call-const-trait-method-fail.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-fail.rs rename to tests/ui/traits/const-traits/call-const-trait-method-fail.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-fail.stderr b/tests/ui/traits/const-traits/call-const-trait-method-fail.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-fail.stderr rename to tests/ui/traits/const-traits/call-const-trait-method-fail.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs b/tests/ui/traits/const-traits/call-const-trait-method-pass.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs rename to tests/ui/traits/const-traits/call-const-trait-method-pass.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-pass.stderr b/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-const-trait-method-pass.stderr rename to tests/ui/traits/const-traits/call-const-trait-method-pass.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-in-impl.rs b/tests/ui/traits/const-traits/call-generic-in-impl.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-in-impl.rs rename to tests/ui/traits/const-traits/call-generic-in-impl.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-in-impl.stderr b/tests/ui/traits/const-traits/call-generic-in-impl.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-in-impl.stderr rename to tests/ui/traits/const-traits/call-generic-in-impl.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-chain.rs b/tests/ui/traits/const-traits/call-generic-method-chain.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-chain.rs rename to tests/ui/traits/const-traits/call-generic-method-chain.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-chain.stderr b/tests/ui/traits/const-traits/call-generic-method-chain.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-chain.stderr rename to tests/ui/traits/const-traits/call-generic-method-chain.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-dup-bound.rs b/tests/ui/traits/const-traits/call-generic-method-dup-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-dup-bound.rs rename to tests/ui/traits/const-traits/call-generic-method-dup-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-dup-bound.stderr b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-dup-bound.stderr rename to tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-fail.rs b/tests/ui/traits/const-traits/call-generic-method-fail.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-fail.rs rename to tests/ui/traits/const-traits/call-generic-method-fail.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-nonconst-bound.rs b/tests/ui/traits/const-traits/call-generic-method-nonconst-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-nonconst-bound.rs rename to tests/ui/traits/const-traits/call-generic-method-nonconst-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-nonconst.rs b/tests/ui/traits/const-traits/call-generic-method-nonconst.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-nonconst.rs rename to tests/ui/traits/const-traits/call-generic-method-nonconst.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-nonconst.stderr b/tests/ui/traits/const-traits/call-generic-method-nonconst.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-nonconst.stderr rename to tests/ui/traits/const-traits/call-generic-method-nonconst.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-pass.rs b/tests/ui/traits/const-traits/call-generic-method-pass.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-pass.rs rename to tests/ui/traits/const-traits/call-generic-method-pass.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-pass.stderr b/tests/ui/traits/const-traits/call-generic-method-pass.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call-generic-method-pass.stderr rename to tests/ui/traits/const-traits/call-generic-method-pass.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/call.rs b/tests/ui/traits/const-traits/call.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/call.rs rename to tests/ui/traits/const-traits/call.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-and-non-const-impl.rs b/tests/ui/traits/const-traits/const-and-non-const-impl.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-and-non-const-impl.rs rename to tests/ui/traits/const-traits/const-and-non-const-impl.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr b/tests/ui/traits/const-traits/const-and-non-const-impl.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr rename to tests/ui/traits/const-traits/const-and-non-const-impl.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-bound-on-not-const-associated-fn.rs b/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-bound-on-not-const-associated-fn.rs rename to tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-bound-on-not-const-associated-fn.stderr b/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-bound-on-not-const-associated-fn.stderr rename to tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-bounds-non-const-trait.rs b/tests/ui/traits/const-traits/const-bounds-non-const-trait.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-bounds-non-const-trait.rs rename to tests/ui/traits/const-traits/const-bounds-non-const-trait.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-bounds-non-const-trait.stderr b/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-bounds-non-const-trait.stderr rename to tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.rs b/tests/ui/traits/const-traits/const-check-fns-in-const-impl.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.rs rename to tests/ui/traits/const-traits/const-check-fns-in-const-impl.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.stderr b/tests/ui/traits/const-traits/const-check-fns-in-const-impl.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.stderr rename to tests/ui/traits/const-traits/const-check-fns-in-const-impl.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-parse-not-item.rs b/tests/ui/traits/const-traits/const-closure-parse-not-item.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-parse-not-item.rs rename to tests/ui/traits/const-traits/const-closure-parse-not-item.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-parse-not-item.stderr b/tests/ui/traits/const-traits/const-closure-parse-not-item.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-parse-not-item.stderr rename to tests/ui/traits/const-traits/const-closure-parse-not-item.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method-fail.rs b/tests/ui/traits/const-traits/const-closure-trait-method-fail.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method-fail.rs rename to tests/ui/traits/const-traits/const-closure-trait-method-fail.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method-fail.stderr b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method-fail.stderr rename to tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method.rs b/tests/ui/traits/const-traits/const-closure-trait-method.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method.rs rename to tests/ui/traits/const-traits/const-closure-trait-method.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method.stderr b/tests/ui/traits/const-traits/const-closure-trait-method.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closure-trait-method.stderr rename to tests/ui/traits/const-traits/const-closure-trait-method.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closures.rs b/tests/ui/traits/const-traits/const-closures.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closures.rs rename to tests/ui/traits/const-traits/const-closures.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-closures.stderr b/tests/ui/traits/const-traits/const-closures.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-closures.stderr rename to tests/ui/traits/const-traits/const-closures.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-default-method-bodies.rs b/tests/ui/traits/const-traits/const-default-method-bodies.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-default-method-bodies.rs rename to tests/ui/traits/const-traits/const-default-method-bodies.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-default-method-bodies.stderr b/tests/ui/traits/const-traits/const-default-method-bodies.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-default-method-bodies.stderr rename to tests/ui/traits/const-traits/const-default-method-bodies.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-bound.rs b/tests/ui/traits/const-traits/const-drop-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-bound.rs rename to tests/ui/traits/const-traits/const-drop-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-bound.stderr b/tests/ui/traits/const-traits/const-drop-bound.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-bound.stderr rename to tests/ui/traits/const-traits/const-drop-bound.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.precise.stderr b/tests/ui/traits/const-traits/const-drop-fail-2.precise.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.precise.stderr rename to tests/ui/traits/const-traits/const-drop-fail-2.precise.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.rs b/tests/ui/traits/const-traits/const-drop-fail-2.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.rs rename to tests/ui/traits/const-traits/const-drop-fail-2.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.stderr b/tests/ui/traits/const-traits/const-drop-fail-2.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.stderr rename to tests/ui/traits/const-traits/const-drop-fail-2.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.stock.stderr b/tests/ui/traits/const-traits/const-drop-fail-2.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail-2.stock.stderr rename to tests/ui/traits/const-traits/const-drop-fail-2.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail.precise.stderr b/tests/ui/traits/const-traits/const-drop-fail.precise.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail.precise.stderr rename to tests/ui/traits/const-traits/const-drop-fail.precise.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail.rs b/tests/ui/traits/const-traits/const-drop-fail.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail.rs rename to tests/ui/traits/const-traits/const-drop-fail.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail.stock.stderr b/tests/ui/traits/const-traits/const-drop-fail.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop-fail.stock.stderr rename to tests/ui/traits/const-traits/const-drop-fail.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop.precise.stderr b/tests/ui/traits/const-traits/const-drop.precise.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop.precise.stderr rename to tests/ui/traits/const-traits/const-drop.precise.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop.rs b/tests/ui/traits/const-traits/const-drop.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop.rs rename to tests/ui/traits/const-traits/const-drop.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop.stock.stderr b/tests/ui/traits/const-traits/const-drop.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-drop.stock.stderr rename to tests/ui/traits/const-traits/const-drop.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-fns-are-early-bound.rs b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-fns-are-early-bound.rs rename to tests/ui/traits/const-traits/const-fns-are-early-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-fns-are-early-bound.stderr b/tests/ui/traits/const-traits/const-fns-are-early-bound.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-fns-are-early-bound.stderr rename to tests/ui/traits/const-traits/const-fns-are-early-bound.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-norecover.rs b/tests/ui/traits/const-traits/const-impl-norecover.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-norecover.rs rename to tests/ui/traits/const-traits/const-impl-norecover.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-norecover.stderr b/tests/ui/traits/const-traits/const-impl-norecover.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-norecover.stderr rename to tests/ui/traits/const-traits/const-impl-norecover.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-recovery.rs b/tests/ui/traits/const-traits/const-impl-recovery.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-recovery.rs rename to tests/ui/traits/const-traits/const-impl-recovery.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-recovery.stderr b/tests/ui/traits/const-traits/const-impl-recovery.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-recovery.stderr rename to tests/ui/traits/const-traits/const-impl-recovery.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-requires-const-trait.rs b/tests/ui/traits/const-traits/const-impl-requires-const-trait.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-requires-const-trait.rs rename to tests/ui/traits/const-traits/const-impl-requires-const-trait.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-requires-const-trait.stderr b/tests/ui/traits/const-traits/const-impl-requires-const-trait.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-requires-const-trait.stderr rename to tests/ui/traits/const-traits/const-impl-requires-const-trait.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-trait.rs b/tests/ui/traits/const-traits/const-impl-trait.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-trait.rs rename to tests/ui/traits/const-traits/const-impl-trait.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-trait.stderr b/tests/ui/traits/const-traits/const-impl-trait.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-impl-trait.stderr rename to tests/ui/traits/const-traits/const-impl-trait.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds-trait-objects.rs b/tests/ui/traits/const-traits/const-trait-bounds-trait-objects.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds-trait-objects.rs rename to tests/ui/traits/const-traits/const-trait-bounds-trait-objects.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds-trait-objects.stderr b/tests/ui/traits/const-traits/const-trait-bounds-trait-objects.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds-trait-objects.stderr rename to tests/ui/traits/const-traits/const-trait-bounds-trait-objects.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds.rs b/tests/ui/traits/const-traits/const-trait-bounds.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds.rs rename to tests/ui/traits/const-traits/const-trait-bounds.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds.stderr b/tests/ui/traits/const-traits/const-trait-bounds.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds.stderr rename to tests/ui/traits/const-traits/const-trait-bounds.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-gate.rs b/tests/ui/traits/const-traits/const_derives/derive-const-gate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-gate.rs rename to tests/ui/traits/const-traits/const_derives/derive-const-gate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-gate.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-gate.stderr rename to tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.rs b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.rs rename to tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.stderr rename to tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-use.rs b/tests/ui/traits/const-traits/const_derives/derive-const-use.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-use.rs rename to tests/ui/traits/const-traits/const_derives/derive-const-use.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-use.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-use.stderr rename to tests/ui/traits/const-traits/const_derives/derive-const-use.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.rs b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.rs rename to tests/ui/traits/const-traits/const_derives/derive-const-with-params.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.stderr rename to tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate-default-method-body-is-const.rs b/tests/ui/traits/const-traits/cross-crate-default-method-body-is-const.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate-default-method-body-is-const.rs rename to tests/ui/traits/const-traits/cross-crate-default-method-body-is-const.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.gatednc.stderr b/tests/ui/traits/const-traits/cross-crate.gatednc.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.gatednc.stderr rename to tests/ui/traits/const-traits/cross-crate.gatednc.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.rs b/tests/ui/traits/const-traits/cross-crate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.rs rename to tests/ui/traits/const-traits/cross-crate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.stock.stderr b/tests/ui/traits/const-traits/cross-crate.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.stock.stderr rename to tests/ui/traits/const-traits/cross-crate.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.stocknc.stderr b/tests/ui/traits/const-traits/cross-crate.stocknc.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/cross-crate.stocknc.stderr rename to tests/ui/traits/const-traits/cross-crate.stocknc.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-body-checking.rs b/tests/ui/traits/const-traits/default-method-body-is-const-body-checking.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-body-checking.rs rename to tests/ui/traits/const-traits/default-method-body-is-const-body-checking.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.rs b/tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.rs rename to tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.stderr b/tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.stderr rename to tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-with-staged-api.rs b/tests/ui/traits/const-traits/default-method-body-is-const-with-staged-api.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/default-method-body-is-const-with-staged-api.rs rename to tests/ui/traits/const-traits/default-method-body-is-const-with-staged-api.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/do-not-const-check-override.rs b/tests/ui/traits/const-traits/do-not-const-check-override.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/do-not-const-check-override.rs rename to tests/ui/traits/const-traits/do-not-const-check-override.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/do-not-const-check.rs b/tests/ui/traits/const-traits/do-not-const-check.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/do-not-const-check.rs rename to tests/ui/traits/const-traits/do-not-const-check.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/auxiliary/cross-crate.rs b/tests/ui/traits/const-traits/effects/auxiliary/cross-crate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/auxiliary/cross-crate.rs rename to tests/ui/traits/const-traits/effects/auxiliary/cross-crate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/const_closure-const_trait_impl-ice-113381.rs b/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/const_closure-const_trait_impl-ice-113381.rs rename to tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/effect-param-infer.rs b/tests/ui/traits/const-traits/effects/effect-param-infer.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/effect-param-infer.rs rename to tests/ui/traits/const-traits/effects/effect-param-infer.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/fallback.rs b/tests/ui/traits/const-traits/effects/fallback.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/fallback.rs rename to tests/ui/traits/const-traits/effects/fallback.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/group-traits.rs b/tests/ui/traits/const-traits/effects/group-traits.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/group-traits.rs rename to tests/ui/traits/const-traits/effects/group-traits.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/helloworld.rs b/tests/ui/traits/const-traits/effects/helloworld.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/helloworld.rs rename to tests/ui/traits/const-traits/effects/helloworld.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs rename to tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.stderr b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.stderr rename to tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-113375-index-out-of-bounds-generics.rs b/tests/ui/traits/const-traits/effects/ice-113375-index-out-of-bounds-generics.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-113375-index-out-of-bounds-generics.rs rename to tests/ui/traits/const-traits/effects/ice-113375-index-out-of-bounds-generics.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/infer-fallback.rs b/tests/ui/traits/const-traits/effects/infer-fallback.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/infer-fallback.rs rename to tests/ui/traits/const-traits/effects/infer-fallback.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/minicore.rs b/tests/ui/traits/const-traits/effects/minicore.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/minicore.rs rename to tests/ui/traits/const-traits/effects/minicore.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/minicore.stderr b/tests/ui/traits/const-traits/effects/minicore.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/minicore.stderr rename to tests/ui/traits/const-traits/effects/minicore.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/mismatched_generic_args.rs b/tests/ui/traits/const-traits/effects/mismatched_generic_args.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/mismatched_generic_args.rs rename to tests/ui/traits/const-traits/effects/mismatched_generic_args.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/mismatched_generic_args.stderr b/tests/ui/traits/const-traits/effects/mismatched_generic_args.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/mismatched_generic_args.stderr rename to tests/ui/traits/const-traits/effects/mismatched_generic_args.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params-cross-crate.rs b/tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params-cross-crate.rs rename to tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params-cross-crate.stderr b/tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params-cross-crate.stderr rename to tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params.rs b/tests/ui/traits/const-traits/effects/no-explicit-const-params.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params.rs rename to tests/ui/traits/const-traits/effects/no-explicit-const-params.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params.stderr b/tests/ui/traits/const-traits/effects/no-explicit-const-params.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/no-explicit-const-params.stderr rename to tests/ui/traits/const-traits/effects/no-explicit-const-params.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/project.rs b/tests/ui/traits/const-traits/effects/project.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/project.rs rename to tests/ui/traits/const-traits/effects/project.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/span-bug-issue-121418.rs b/tests/ui/traits/const-traits/effects/span-bug-issue-121418.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/span-bug-issue-121418.rs rename to tests/ui/traits/const-traits/effects/span-bug-issue-121418.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/span-bug-issue-121418.stderr b/tests/ui/traits/const-traits/effects/span-bug-issue-121418.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/span-bug-issue-121418.stderr rename to tests/ui/traits/const-traits/effects/span-bug-issue-121418.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/spec-effectvar-ice.rs b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/spec-effectvar-ice.rs rename to tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/spec-effectvar-ice.stderr b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/spec-effectvar-ice.stderr rename to tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/trait-fn-const.rs b/tests/ui/traits/const-traits/effects/trait-fn-const.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/trait-fn-const.rs rename to tests/ui/traits/const-traits/effects/trait-fn-const.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/trait-fn-const.stderr b/tests/ui/traits/const-traits/effects/trait-fn-const.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/trait-fn-const.stderr rename to tests/ui/traits/const-traits/effects/trait-fn-const.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/with-without-next-solver.coherence.stderr b/tests/ui/traits/const-traits/effects/with-without-next-solver.coherence.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/with-without-next-solver.coherence.stderr rename to tests/ui/traits/const-traits/effects/with-without-next-solver.coherence.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/with-without-next-solver.rs b/tests/ui/traits/const-traits/effects/with-without-next-solver.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/with-without-next-solver.rs rename to tests/ui/traits/const-traits/effects/with-without-next-solver.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/with-without-next-solver.stock.stderr b/tests/ui/traits/const-traits/effects/with-without-next-solver.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/effects/with-without-next-solver.stock.stderr rename to tests/ui/traits/const-traits/effects/with-without-next-solver.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/feature-gate.gated.stderr b/tests/ui/traits/const-traits/feature-gate.gated.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/feature-gate.gated.stderr rename to tests/ui/traits/const-traits/feature-gate.gated.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/feature-gate.rs b/tests/ui/traits/const-traits/feature-gate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/feature-gate.rs rename to tests/ui/traits/const-traits/feature-gate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/feature-gate.stock.stderr b/tests/ui/traits/const-traits/feature-gate.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/feature-gate.stock.stderr rename to tests/ui/traits/const-traits/feature-gate.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/function-pointer-does-not-require-const.rs b/tests/ui/traits/const-traits/function-pointer-does-not-require-const.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/function-pointer-does-not-require-const.rs rename to tests/ui/traits/const-traits/function-pointer-does-not-require-const.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/gate.rs b/tests/ui/traits/const-traits/gate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/gate.rs rename to tests/ui/traits/const-traits/gate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/gate.stderr b/tests/ui/traits/const-traits/gate.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/gate.stderr rename to tests/ui/traits/const-traits/gate.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/generic-bound.rs b/tests/ui/traits/const-traits/generic-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/generic-bound.rs rename to tests/ui/traits/const-traits/generic-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/generic-bound.stderr b/tests/ui/traits/const-traits/generic-bound.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/generic-bound.stderr rename to tests/ui/traits/const-traits/generic-bound.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/hir-const-check.rs b/tests/ui/traits/const-traits/hir-const-check.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/hir-const-check.rs rename to tests/ui/traits/const-traits/hir-const-check.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/hir-const-check.stderr b/tests/ui/traits/const-traits/hir-const-check.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/hir-const-check.stderr rename to tests/ui/traits/const-traits/hir-const-check.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-119717-constant-lifetime.rs b/tests/ui/traits/const-traits/ice-119717-constant-lifetime.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-119717-constant-lifetime.rs rename to tests/ui/traits/const-traits/ice-119717-constant-lifetime.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-119717-constant-lifetime.stderr b/tests/ui/traits/const-traits/ice-119717-constant-lifetime.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-119717-constant-lifetime.stderr rename to tests/ui/traits/const-traits/ice-119717-constant-lifetime.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-120503-async-const-method.rs b/tests/ui/traits/const-traits/ice-120503-async-const-method.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-120503-async-const-method.rs rename to tests/ui/traits/const-traits/ice-120503-async-const-method.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-120503-async-const-method.stderr b/tests/ui/traits/const-traits/ice-120503-async-const-method.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-120503-async-const-method.stderr rename to tests/ui/traits/const-traits/ice-120503-async-const-method.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-121536-const-method.rs b/tests/ui/traits/const-traits/ice-121536-const-method.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-121536-const-method.rs rename to tests/ui/traits/const-traits/ice-121536-const-method.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-121536-const-method.stderr b/tests/ui/traits/const-traits/ice-121536-const-method.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-121536-const-method.stderr rename to tests/ui/traits/const-traits/ice-121536-const-method.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-123664-unexpected-bound-var.rs b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-123664-unexpected-bound-var.rs rename to tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-123664-unexpected-bound-var.stderr b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-123664-unexpected-bound-var.stderr rename to tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-124857-combine-effect-const-infer-vars.rs b/tests/ui/traits/const-traits/ice-124857-combine-effect-const-infer-vars.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-124857-combine-effect-const-infer-vars.rs rename to tests/ui/traits/const-traits/ice-124857-combine-effect-const-infer-vars.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-124857-combine-effect-const-infer-vars.stderr b/tests/ui/traits/const-traits/ice-124857-combine-effect-const-infer-vars.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-124857-combine-effect-const-infer-vars.stderr rename to tests/ui/traits/const-traits/ice-124857-combine-effect-const-infer-vars.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-126148-failed-to-normalize.rs b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-126148-failed-to-normalize.rs rename to tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/ice-126148-failed-to-normalize.stderr b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/ice-126148-failed-to-normalize.stderr rename to tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/impl-tilde-const-trait.rs b/tests/ui/traits/const-traits/impl-tilde-const-trait.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/impl-tilde-const-trait.rs rename to tests/ui/traits/const-traits/impl-tilde-const-trait.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/impl-tilde-const-trait.stderr b/tests/ui/traits/const-traits/impl-tilde-const-trait.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/impl-tilde-const-trait.stderr rename to tests/ui/traits/const-traits/impl-tilde-const-trait.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/impl-with-default-fn-fail.rs b/tests/ui/traits/const-traits/impl-with-default-fn-fail.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/impl-with-default-fn-fail.rs rename to tests/ui/traits/const-traits/impl-with-default-fn-fail.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/impl-with-default-fn-fail.stderr b/tests/ui/traits/const-traits/impl-with-default-fn-fail.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/impl-with-default-fn-fail.stderr rename to tests/ui/traits/const-traits/impl-with-default-fn-fail.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/impl-with-default-fn-pass.rs b/tests/ui/traits/const-traits/impl-with-default-fn-pass.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/impl-with-default-fn-pass.rs rename to tests/ui/traits/const-traits/impl-with-default-fn-pass.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/inherent-impl-const-bounds.rs b/tests/ui/traits/const-traits/inherent-impl-const-bounds.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/inherent-impl-const-bounds.rs rename to tests/ui/traits/const-traits/inherent-impl-const-bounds.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/inherent-impl.rs b/tests/ui/traits/const-traits/inherent-impl.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/inherent-impl.rs rename to tests/ui/traits/const-traits/inherent-impl.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/inherent-impl.stderr b/tests/ui/traits/const-traits/inherent-impl.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/inherent-impl.stderr rename to tests/ui/traits/const-traits/inherent-impl.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/inline-incorrect-early-bound-in-ctfe.rs b/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/inline-incorrect-early-bound-in-ctfe.rs rename to tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/inline-incorrect-early-bound-in-ctfe.stderr b/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/inline-incorrect-early-bound-in-ctfe.stderr rename to tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-100222.rs b/tests/ui/traits/const-traits/issue-100222.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-100222.rs rename to tests/ui/traits/const-traits/issue-100222.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.rs b/tests/ui/traits/const-traits/issue-102156.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.rs rename to tests/ui/traits/const-traits/issue-102156.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.stderr b/tests/ui/traits/const-traits/issue-102156.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.stderr rename to tests/ui/traits/const-traits/issue-102156.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102985.rs b/tests/ui/traits/const-traits/issue-102985.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102985.rs rename to tests/ui/traits/const-traits/issue-102985.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102985.stderr b/tests/ui/traits/const-traits/issue-102985.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102985.stderr rename to tests/ui/traits/const-traits/issue-102985.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-103677.rs b/tests/ui/traits/const-traits/issue-103677.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-103677.rs rename to tests/ui/traits/const-traits/issue-103677.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-79450.rs b/tests/ui/traits/const-traits/issue-79450.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-79450.rs rename to tests/ui/traits/const-traits/issue-79450.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-79450.stderr b/tests/ui/traits/const-traits/issue-79450.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-79450.stderr rename to tests/ui/traits/const-traits/issue-79450.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-88155.rs b/tests/ui/traits/const-traits/issue-88155.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-88155.rs rename to tests/ui/traits/const-traits/issue-88155.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-88155.stderr b/tests/ui/traits/const-traits/issue-88155.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-88155.stderr rename to tests/ui/traits/const-traits/issue-88155.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-92111.rs b/tests/ui/traits/const-traits/issue-92111.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-92111.rs rename to tests/ui/traits/const-traits/issue-92111.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-92111.stderr b/tests/ui/traits/const-traits/issue-92111.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-92111.stderr rename to tests/ui/traits/const-traits/issue-92111.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-92230-wf-super-trait-env.rs b/tests/ui/traits/const-traits/issue-92230-wf-super-trait-env.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/issue-92230-wf-super-trait-env.rs rename to tests/ui/traits/const-traits/issue-92230-wf-super-trait-env.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/match-non-const-eq.gated.stderr b/tests/ui/traits/const-traits/match-non-const-eq.gated.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/match-non-const-eq.gated.stderr rename to tests/ui/traits/const-traits/match-non-const-eq.gated.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/match-non-const-eq.rs b/tests/ui/traits/const-traits/match-non-const-eq.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/match-non-const-eq.rs rename to tests/ui/traits/const-traits/match-non-const-eq.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/match-non-const-eq.stock.stderr b/tests/ui/traits/const-traits/match-non-const-eq.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/match-non-const-eq.stock.stderr rename to tests/ui/traits/const-traits/match-non-const-eq.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-bare-trait-objects-const-trait-bounds.rs b/tests/ui/traits/const-traits/mbe-bare-trait-objects-const-trait-bounds.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-bare-trait-objects-const-trait-bounds.rs rename to tests/ui/traits/const-traits/mbe-bare-trait-objects-const-trait-bounds.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-const-trait-bound-theoretical-regression.rs b/tests/ui/traits/const-traits/mbe-const-trait-bound-theoretical-regression.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-const-trait-bound-theoretical-regression.rs rename to tests/ui/traits/const-traits/mbe-const-trait-bound-theoretical-regression.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-const-trait-bound-theoretical-regression.stderr b/tests/ui/traits/const-traits/mbe-const-trait-bound-theoretical-regression.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-const-trait-bound-theoretical-regression.stderr rename to tests/ui/traits/const-traits/mbe-const-trait-bound-theoretical-regression.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-dyn-const-2015.rs b/tests/ui/traits/const-traits/mbe-dyn-const-2015.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/mbe-dyn-const-2015.rs rename to tests/ui/traits/const-traits/mbe-dyn-const-2015.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/mutually-exclusive-trait-bound-modifiers.rs b/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/mutually-exclusive-trait-bound-modifiers.rs rename to tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/mutually-exclusive-trait-bound-modifiers.stderr b/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/mutually-exclusive-trait-bound-modifiers.stderr rename to tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/nested-closure.rs b/tests/ui/traits/const-traits/nested-closure.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/nested-closure.rs rename to tests/ui/traits/const-traits/nested-closure.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-const-closure-non-const-outer.rs b/tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-const-closure-non-const-outer.rs rename to tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-const-closure-non-const-outer.stderr b/tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-const-closure-non-const-outer.stderr rename to tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.rs b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.rs rename to tests/ui/traits/const-traits/non-const-op-in-closure-in-const.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.stderr b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.stderr rename to tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-bound-non-const-specialized-bound.rs b/tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-bound-non-const-specialized-bound.rs rename to tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-bound-non-const-specialized-bound.stderr b/tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-bound-non-const-specialized-bound.stderr rename to tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-const-specialized.rs b/tests/ui/traits/const-traits/specialization/const-default-const-specialized.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-const-specialized.rs rename to tests/ui/traits/const-traits/specialization/const-default-const-specialized.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-const-specialized.stderr b/tests/ui/traits/const-traits/specialization/const-default-const-specialized.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-const-specialized.stderr rename to tests/ui/traits/const-traits/specialization/const-default-const-specialized.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-impl-non-const-specialized-impl.rs b/tests/ui/traits/const-traits/specialization/const-default-impl-non-const-specialized-impl.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-impl-non-const-specialized-impl.rs rename to tests/ui/traits/const-traits/specialization/const-default-impl-non-const-specialized-impl.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-impl-non-const-specialized-impl.stderr b/tests/ui/traits/const-traits/specialization/const-default-impl-non-const-specialized-impl.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/const-default-impl-non-const-specialized-impl.stderr rename to tests/ui/traits/const-traits/specialization/const-default-impl-non-const-specialized-impl.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/default-keyword.rs b/tests/ui/traits/const-traits/specialization/default-keyword.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/default-keyword.rs rename to tests/ui/traits/const-traits/specialization/default-keyword.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/default-keyword.stderr b/tests/ui/traits/const-traits/specialization/default-keyword.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/default-keyword.stderr rename to tests/ui/traits/const-traits/specialization/default-keyword.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95186-specialize-on-tilde-const.rs b/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95186-specialize-on-tilde-const.rs rename to tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95186-specialize-on-tilde-const.stderr b/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95186-specialize-on-tilde-const.stderr rename to tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95187-same-trait-bound-different-constness.rs b/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95187-same-trait-bound-different-constness.rs rename to tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95187-same-trait-bound-different-constness.stderr b/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/issue-95187-same-trait-bound-different-constness.stderr rename to tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/non-const-default-const-specialized.rs b/tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/non-const-default-const-specialized.rs rename to tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/non-const-default-const-specialized.stderr b/tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specialization/non-const-default-const-specialized.stderr rename to tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness-2.rs b/tests/ui/traits/const-traits/specializing-constness-2.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness-2.rs rename to tests/ui/traits/const-traits/specializing-constness-2.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness-2.stderr b/tests/ui/traits/const-traits/specializing-constness-2.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness-2.stderr rename to tests/ui/traits/const-traits/specializing-constness-2.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness.rs b/tests/ui/traits/const-traits/specializing-constness.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness.rs rename to tests/ui/traits/const-traits/specializing-constness.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness.stderr b/tests/ui/traits/const-traits/specializing-constness.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/specializing-constness.stderr rename to tests/ui/traits/const-traits/specializing-constness.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api-user-crate.rs b/tests/ui/traits/const-traits/staged-api-user-crate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api-user-crate.rs rename to tests/ui/traits/const-traits/staged-api-user-crate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api-user-crate.stderr b/tests/ui/traits/const-traits/staged-api-user-crate.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api-user-crate.stderr rename to tests/ui/traits/const-traits/staged-api-user-crate.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api.rs b/tests/ui/traits/const-traits/staged-api.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api.rs rename to tests/ui/traits/const-traits/staged-api.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api.stable.stderr b/tests/ui/traits/const-traits/staged-api.stable.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api.stable.stderr rename to tests/ui/traits/const-traits/staged-api.stable.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api.unstable.stderr b/tests/ui/traits/const-traits/staged-api.unstable.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/staged-api.unstable.stderr rename to tests/ui/traits/const-traits/staged-api.unstable.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/static-const-trait-bound.rs b/tests/ui/traits/const-traits/static-const-trait-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/static-const-trait-bound.rs rename to tests/ui/traits/const-traits/static-const-trait-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/std-impl-gate.gated.stderr b/tests/ui/traits/const-traits/std-impl-gate.gated.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/std-impl-gate.gated.stderr rename to tests/ui/traits/const-traits/std-impl-gate.gated.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/std-impl-gate.rs b/tests/ui/traits/const-traits/std-impl-gate.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/std-impl-gate.rs rename to tests/ui/traits/const-traits/std-impl-gate.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/std-impl-gate.stock.stderr b/tests/ui/traits/const-traits/std-impl-gate.stock.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/std-impl-gate.stock.stderr rename to tests/ui/traits/const-traits/std-impl-gate.stock.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.nn.stderr rename to tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.ny.stderr rename to tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.rs b/tests/ui/traits/const-traits/super-traits-fail-2.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.rs rename to tests/ui/traits/const-traits/super-traits-fail-2.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.yn.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.yn.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.yn.stderr rename to tests/ui/traits/const-traits/super-traits-fail-2.yn.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.yy.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.yy.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-2.yy.stderr rename to tests/ui/traits/const-traits/super-traits-fail-2.yy.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.nn.stderr rename to tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.ny.stderr rename to tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.rs b/tests/ui/traits/const-traits/super-traits-fail-3.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.rs rename to tests/ui/traits/const-traits/super-traits-fail-3.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.yn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail-3.yn.stderr rename to tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail.rs b/tests/ui/traits/const-traits/super-traits-fail.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail.rs rename to tests/ui/traits/const-traits/super-traits-fail.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail.stderr b/tests/ui/traits/const-traits/super-traits-fail.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits-fail.stderr rename to tests/ui/traits/const-traits/super-traits-fail.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits.rs b/tests/ui/traits/const-traits/super-traits.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/super-traits.rs rename to tests/ui/traits/const-traits/super-traits.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/syntax.rs b/tests/ui/traits/const-traits/syntax.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/syntax.rs rename to tests/ui/traits/const-traits/syntax.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-and-const-params.rs b/tests/ui/traits/const-traits/tilde-const-and-const-params.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-and-const-params.rs rename to tests/ui/traits/const-traits/tilde-const-and-const-params.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-and-const-params.stderr b/tests/ui/traits/const-traits/tilde-const-and-const-params.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-and-const-params.stderr rename to tests/ui/traits/const-traits/tilde-const-and-const-params.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-assoc-fn-in-trait-impl.rs b/tests/ui/traits/const-traits/tilde-const-assoc-fn-in-trait-impl.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-assoc-fn-in-trait-impl.rs rename to tests/ui/traits/const-traits/tilde-const-assoc-fn-in-trait-impl.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-inherent-assoc-const-fn.rs b/tests/ui/traits/const-traits/tilde-const-inherent-assoc-const-fn.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-inherent-assoc-const-fn.rs rename to tests/ui/traits/const-traits/tilde-const-inherent-assoc-const-fn.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-invalid-places.rs b/tests/ui/traits/const-traits/tilde-const-invalid-places.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-invalid-places.rs rename to tests/ui/traits/const-traits/tilde-const-invalid-places.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-invalid-places.stderr b/tests/ui/traits/const-traits/tilde-const-invalid-places.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-invalid-places.stderr rename to tests/ui/traits/const-traits/tilde-const-invalid-places.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-syntax.rs b/tests/ui/traits/const-traits/tilde-const-syntax.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-syntax.rs rename to tests/ui/traits/const-traits/tilde-const-syntax.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-trait-assoc-tys.rs b/tests/ui/traits/const-traits/tilde-const-trait-assoc-tys.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-trait-assoc-tys.rs rename to tests/ui/traits/const-traits/tilde-const-trait-assoc-tys.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-twice.rs b/tests/ui/traits/const-traits/tilde-twice.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-twice.rs rename to tests/ui/traits/const-traits/tilde-twice.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-twice.stderr b/tests/ui/traits/const-traits/tilde-twice.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-twice.stderr rename to tests/ui/traits/const-traits/tilde-twice.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-default-body-stability.rs b/tests/ui/traits/const-traits/trait-default-body-stability.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-default-body-stability.rs rename to tests/ui/traits/const-traits/trait-default-body-stability.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-default-body-stability.stderr b/tests/ui/traits/const-traits/trait-default-body-stability.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-default-body-stability.stderr rename to tests/ui/traits/const-traits/trait-default-body-stability.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs b/tests/ui/traits/const-traits/trait-method-ptr-in-consts-ice.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs rename to tests/ui/traits/const-traits/trait-method-ptr-in-consts-ice.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-const.rs b/tests/ui/traits/const-traits/trait-where-clause-const.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-const.rs rename to tests/ui/traits/const-traits/trait-where-clause-const.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-const.stderr b/tests/ui/traits/const-traits/trait-where-clause-const.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-const.stderr rename to tests/ui/traits/const-traits/trait-where-clause-const.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-run.rs b/tests/ui/traits/const-traits/trait-where-clause-run.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-run.rs rename to tests/ui/traits/const-traits/trait-where-clause-run.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-self-referential.rs b/tests/ui/traits/const-traits/trait-where-clause-self-referential.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause-self-referential.rs rename to tests/ui/traits/const-traits/trait-where-clause-self-referential.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause.rs b/tests/ui/traits/const-traits/trait-where-clause.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause.rs rename to tests/ui/traits/const-traits/trait-where-clause.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause.stderr b/tests/ui/traits/const-traits/trait-where-clause.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/trait-where-clause.stderr rename to tests/ui/traits/const-traits/trait-where-clause.stderr diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/unsatisfied-const-trait-bound.rs b/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.rs similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/unsatisfied-const-trait-bound.rs rename to tests/ui/traits/const-traits/unsatisfied-const-trait-bound.rs diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/unsatisfied-const-trait-bound.stderr b/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr similarity index 100% rename from tests/ui/rfcs/rfc-2632-const-trait-impl/unsatisfied-const-trait-bound.stderr rename to tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr From 8e69377c46bec8a77c9c56eb7d52ecd6f6b091f6 Mon Sep 17 00:00:00 2001 From: duncanproctor Date: Mon, 21 Oct 2024 20:07:07 -0400 Subject: [PATCH 081/366] Move explicit range handling out of goto_definition, use OperatorClass instead --- .../rust-analyzer/crates/hir/src/semantics.rs | 10 +++- .../crates/hir/src/source_analyzer.rs | 26 +++++++--- .../rust-analyzer/crates/ide-db/src/defs.rs | 23 ++++++--- .../crates/ide-db/src/famous_defs.rs | 17 +------ .../crates/ide/src/goto_definition.rs | 47 ++++++++++--------- 5 files changed, 70 insertions(+), 53 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index b27f1fbb5db1..fd3172a61a85 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -17,7 +17,7 @@ use hir_def::{ path::ModPath, resolver::{self, HasResolver, Resolver, TypeNs}, type_ref::Mutability, - AsMacroCall, DefWithBodyId, FunctionId, MacroId, TraitId, VariantId, + AsMacroCall, DefWithBodyId, FunctionId, MacroId, StructId, TraitId, VariantId, }; use hir_expand::{ attrs::collect_attrs, @@ -203,6 +203,10 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> { self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast)) } + pub fn resolve_range_expr(&self, range_expr: &ast::RangeExpr) -> Option { + self.imp.resolve_range_expr(range_expr).map(Struct::from) + } + pub fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option { self.imp.resolve_await_to_poll(await_expr).map(Function::from) } @@ -1357,6 +1361,10 @@ impl<'db> SemanticsImpl<'db> { self.analyze(call.syntax())?.resolve_method_call_fallback(self.db, call) } + fn resolve_range_expr(&self, range_expr: &ast::RangeExpr) -> Option { + self.analyze(range_expr.syntax())?.resolve_range_expr(self.db, range_expr) + } + fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option { self.analyze(await_expr.syntax())?.resolve_await_to_poll(self.db, await_expr) } diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 3da67ae23f83..5e05fad8c397 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -7,6 +7,11 @@ //! purely for "IDE needs". use std::iter::{self, once}; +use crate::{ + db::HirDatabase, semantics::PathResolution, Adt, AssocItem, BindingMode, BuiltinAttr, + BuiltinType, Callable, Const, DeriveHelper, Field, Function, Local, Macro, ModuleDef, Static, + Struct, ToolModule, Trait, TraitAlias, TupleField, Type, TypeAlias, Variant, +}; use either::Either; use hir_def::{ body::{ @@ -21,7 +26,7 @@ use hir_def::{ resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs}, type_ref::Mutability, AsMacroCall, AssocItemId, ConstId, DefWithBodyId, FieldId, FunctionId, ItemContainerId, - LocalFieldId, Lookup, ModuleDefId, TraitId, VariantId, + LocalFieldId, Lookup, ModuleDefId, StructId, TraitId, VariantId, }; use hir_expand::{ mod_path::path, @@ -40,18 +45,13 @@ use hir_ty::{ use intern::sym; use itertools::Itertools; use smallvec::SmallVec; +use syntax::ast::{RangeItem, RangeOp}; use syntax::{ ast::{self, AstNode}, SyntaxKind, SyntaxNode, TextRange, TextSize, }; use triomphe::Arc; -use crate::{ - db::HirDatabase, semantics::PathResolution, Adt, AssocItem, BindingMode, BuiltinAttr, - BuiltinType, Callable, Const, DeriveHelper, Field, Function, Local, Macro, ModuleDef, Static, - Struct, ToolModule, Trait, TraitAlias, TupleField, Type, TypeAlias, Variant, -}; - /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of /// original source files. It should not be used inside the HIR itself. #[derive(Debug)] @@ -348,6 +348,18 @@ impl SourceAnalyzer { } } + pub(crate) fn resolve_range_expr( + &self, + db: &dyn HirDatabase, + range_expr: &ast::RangeExpr, + ) -> Option { + let path = match range_expr.op_kind()? { + RangeOp::Exclusive => path![core::ops::Range], + RangeOp::Inclusive => path![core::ops::RangeInclusive], + }; + self.resolver.resolve_known_struct(db.upcast(), &path) + } + pub(crate) fn resolve_await_to_poll( &self, db: &dyn HirDatabase, diff --git a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs index 099f26eba78a..a253e086f81a 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs @@ -5,14 +5,17 @@ // FIXME: this badly needs rename/rewrite (matklad, 2020-02-06). +use crate::documentation::{Documentation, HasDocs}; +use crate::famous_defs::FamousDefs; +use crate::RootDatabase; use arrayvec::ArrayVec; use either::Either; use hir::{ Adt, AsAssocItem, AsExternAssocItem, AssocItem, AttributeTemplate, BuiltinAttr, BuiltinType, Const, Crate, DefWithBody, DeriveHelper, DocLinkDef, ExternAssocItem, ExternCrateDecl, Field, Function, GenericParam, HasVisibility, HirDisplay, Impl, InlineAsmOperand, Label, Local, Macro, - Module, ModuleDef, Name, PathResolution, Semantics, Static, StaticLifetime, ToolModule, Trait, - TraitAlias, TupleField, TypeAlias, Variant, VariantDef, Visibility, + Module, ModuleDef, Name, PathResolution, Semantics, Static, StaticLifetime, Struct, ToolModule, + Trait, TraitAlias, TupleField, TypeAlias, Variant, VariantDef, Visibility, }; use span::Edition; use stdx::{format_to, impl_from}; @@ -21,10 +24,6 @@ use syntax::{ match_ast, SyntaxKind, SyntaxNode, SyntaxToken, }; -use crate::documentation::{Documentation, HasDocs}; -use crate::famous_defs::FamousDefs; -use crate::RootDatabase; - // FIXME: a more precise name would probably be `Symbol`? #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)] pub enum Definition { @@ -319,6 +318,7 @@ impl IdentClass { .map(IdentClass::NameClass) .or_else(|| NameRefClass::classify_lifetime(sema, &lifetime).map(IdentClass::NameRefClass)) }, + ast::RangeExpr(range_expr) => OperatorClass::classify_range(sema, &range_expr).map(IdentClass::Operator), ast::AwaitExpr(await_expr) => OperatorClass::classify_await(sema, &await_expr).map(IdentClass::Operator), ast::BinExpr(bin_expr) => OperatorClass::classify_bin(sema, &bin_expr).map(IdentClass::Operator), ast::IndexExpr(index_expr) => OperatorClass::classify_index(sema, &index_expr).map(IdentClass::Operator), @@ -372,6 +372,9 @@ impl IdentClass { | OperatorClass::Index(func) | OperatorClass::Try(func), ) => res.push(Definition::Function(func)), + IdentClass::Operator(OperatorClass::Range(struct0)) => { + res.push(Definition::Adt(Adt::Struct(struct0))) + } } res } @@ -546,6 +549,7 @@ impl NameClass { #[derive(Debug)] pub enum OperatorClass { + Range(Struct), Await(Function), Prefix(Function), Index(Function), @@ -554,6 +558,13 @@ pub enum OperatorClass { } impl OperatorClass { + pub fn classify_range( + sema: &Semantics<'_, RootDatabase>, + range_expr: &ast::RangeExpr, + ) -> Option { + sema.resolve_range_expr(range_expr).map(OperatorClass::Range) + } + pub fn classify_await( sema: &Semantics<'_, RootDatabase>, await_expr: &ast::AwaitExpr, diff --git a/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs index 9b4273ab103e..ba6e50abf658 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/famous_defs.rs @@ -1,7 +1,7 @@ //! See [`FamousDefs`]. use base_db::{CrateOrigin, LangCrateOrigin, SourceDatabase}; -use hir::{Crate, Enum, Function, Macro, Module, ScopeDef, Semantics, Struct, Trait}; +use hir::{Crate, Enum, Function, Macro, Module, ScopeDef, Semantics, Trait}; use crate::RootDatabase; @@ -102,14 +102,6 @@ impl FamousDefs<'_, '_> { self.find_trait("core:ops:Drop") } - pub fn core_ops_Range(&self) -> Option { - self.find_struct("core:ops:Range") - } - - pub fn core_ops_RangeInclusive(&self) -> Option { - self.find_struct("core:ops:RangeInclusive") - } - pub fn core_marker_Copy(&self) -> Option { self.find_trait("core:marker:Copy") } @@ -145,13 +137,6 @@ impl FamousDefs<'_, '_> { .flatten() } - fn find_struct(&self, path: &str) -> Option { - match self.find_def(path)? { - hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Struct(it))) => Some(it), - _ => None, - } - } - fn find_trait(&self, path: &str) -> Option { match self.find_def(path)? { hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it), diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 3ac7cc823ef2..4c965fd2d86a 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -5,7 +5,7 @@ use crate::{ navigation_target::{self, ToNav}, FilePosition, NavigationTarget, RangeInfo, TryToNav, UpmappingResult, }; -use hir::{Adt, AsAssocItem, AssocItem, FileRange, InFile, MacroFileIdExt, ModuleDef, Semantics}; +use hir::{AsAssocItem, AssocItem, FileRange, InFile, MacroFileIdExt, ModuleDef, Semantics}; use ide_db::{ base_db::{AnchoredPath, FileLoader, SourceDatabase}, defs::{Definition, IdentClass}, @@ -13,7 +13,6 @@ use ide_db::{ RootDatabase, SymbolKind, }; use itertools::Itertools; -use ide_db::famous_defs::FamousDefs; use span::{Edition, FileId}; use syntax::{ ast::{self, HasLoopBody}, @@ -41,22 +40,6 @@ pub(crate) fn goto_definition( ) -> Option>> { let sema = &Semantics::new(db); let file = sema.parse_guess_edition(file_id).syntax().clone(); - - if let syntax::TokenAtOffset::Single(tok) = file.token_at_offset(offset) { - if let Some(module) = sema.file_to_module_def(file_id) { - let famous_defs = FamousDefs(sema, module.krate()); - let maybe_famous_struct = match tok.kind() { - T![..] => famous_defs.core_ops_Range(), - T![..=] => famous_defs.core_ops_RangeInclusive(), - _ => None - }; - if let Some(fstruct) = maybe_famous_struct { - let target = def_to_nav(db, Definition::Adt(Adt::Struct(fstruct))); - return Some(RangeInfo::new(tok.text_range(), target)); - } - } - } - let edition = sema.attach_first_edition(file_id).map(|it| it.edition()).unwrap_or(Edition::CURRENT); let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind { @@ -434,10 +417,10 @@ fn expr_to_nav( #[cfg(test)] mod tests { + use crate::fixture; use ide_db::FileRange; use itertools::Itertools; use syntax::SmolStr; - use crate::fixture; #[track_caller] fn check(ra_fixture: &str) { @@ -466,9 +449,25 @@ mod tests { assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {navs:?}") } + #[test] + fn goto_def_range_inclusive_0() { + let ra_fixture = r#" +//- minicore: range +fn f(a: usize, b: usize) { + for _ in a.$0.=b { + + } +} +"#; + let (analysis, position, _) = fixture::annotations(ra_fixture); + let mut navs = + analysis.goto_definition(position).unwrap().expect("no definition found").info; + let Some(target) = navs.pop() else { panic!("no target found") }; + assert_eq!(target.name, SmolStr::new_inline("RangeInclusive")); + } #[test] - fn goto_def_range_inclusive() { + fn goto_def_range_inclusive_1() { let ra_fixture = r#" //- minicore: range fn f(a: usize, b: usize) { @@ -478,13 +477,14 @@ fn f(a: usize, b: usize) { } "#; let (analysis, position, _) = fixture::annotations(ra_fixture); - let mut navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; + let mut navs = + analysis.goto_definition(position).unwrap().expect("no definition found").info; let Some(target) = navs.pop() else { panic!("no target found") }; assert_eq!(target.name, SmolStr::new_inline("RangeInclusive")); } #[test] - fn goto_def_range_half_open() { + fn goto_def_range() { let ra_fixture = r#" //- minicore: range fn f(a: usize, b: usize) { @@ -494,7 +494,8 @@ fn f(a: usize, b: usize) { } "#; let (analysis, position, _) = fixture::annotations(ra_fixture); - let mut navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; + let mut navs = + analysis.goto_definition(position).unwrap().expect("no definition found").info; let Some(target) = navs.pop() else { panic!("no target found") }; assert_eq!(target.name, SmolStr::new_inline("Range")); } From c18bab3fe64c8786c26ac483dac13f615e544276 Mon Sep 17 00:00:00 2001 From: David Ross Date: Mon, 21 Oct 2024 20:05:55 -0700 Subject: [PATCH 082/366] Document PartialEq impl for OnceLock --- library/std/src/sync/once_lock.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index be615a5a8ef3..0ae3cf4df361 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -634,6 +634,26 @@ impl From for OnceLock { #[stable(feature = "once_cell", since = "1.70.0")] impl PartialEq for OnceLock { + /// Equality for two `OnceLock`s. + /// + /// Two `OnceLock`s are equal if they either both contain values and their + /// values are equal, or if neither contains a value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::OnceLock; + /// + /// let five = OnceLock::new(); + /// five.set(5).unwrap(); + /// + /// let also_five = OnceLock::new(); + /// also_five.set(5).unwrap(); + /// + /// assert!(five == also_five); + /// + /// assert!(OnceLock::::new() == OnceLock::::new()); + /// ``` #[inline] fn eq(&self, other: &OnceLock) -> bool { self.get() == other.get() From 3952d493a7308e430678f7b32ccd848b0363ff76 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Tue, 22 Oct 2024 05:36:39 +0200 Subject: [PATCH 083/366] nuttx.md: typo --- src/doc/rustc/src/platform-support/nuttx.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc/src/platform-support/nuttx.md b/src/doc/rustc/src/platform-support/nuttx.md index cbbede45f52f..433a092aab22 100644 --- a/src/doc/rustc/src/platform-support/nuttx.md +++ b/src/doc/rustc/src/platform-support/nuttx.md @@ -35,7 +35,7 @@ The following target names are defined: ## Building the target -The target can be built by enabled in the `rustc` build: +The target can be built by enabling it in the `rustc` build: ```toml [build] From 25365aeacf32715f2a4cd0d63326139d16e3c7ed Mon Sep 17 00:00:00 2001 From: lcnr Date: Tue, 22 Oct 2024 08:20:23 +0200 Subject: [PATCH 084/366] fix typo --- .../rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index 71ce0cce7722..e2fd0dd2a25f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs @@ -170,7 +170,7 @@ where // // We don't do so for `NormalizesTo` goals as we erased the expected term and // bailing with overflow here would prevent us from detecting a type-mismatch, - // causing a coherence error in diesel, see #131969. We still bail with verflow + // causing a coherence error in diesel, see #131969. We still bail with overflow // when later returning from the parent AliasRelate goal. if !self.is_normalizes_to_goal { let num_non_region_vars = From d6ce2bd1de944c9c7fbb2a7095a12304e4484935 Mon Sep 17 00:00:00 2001 From: lcnr Date: Tue, 22 Oct 2024 08:27:11 +0200 Subject: [PATCH 085/366] remove unused field --- .../src/solve/eval_ctxt/mod.rs | 2 +- .../src/solve/inspect/build.rs | 16 ++++++---------- .../src/solve/inspect/analyse.rs | 2 +- compiler/rustc_type_ir/src/solve/inspect.rs | 17 +++++------------ 4 files changed, 13 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index cbefc826fb7d..250174e033e3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -291,7 +291,7 @@ where search_graph, nested_goals: NestedGoals::new(), tainted: Ok(()), - inspect: canonical_goal_evaluation.new_goal_evaluation_step(var_values, input), + inspect: canonical_goal_evaluation.new_goal_evaluation_step(var_values), }; for &(key, ty) in &input.predefined_opaques_in_body.opaque_types { diff --git a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs index 85474bf37b44..1607fbb1b6a7 100644 --- a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs +++ b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs @@ -13,7 +13,7 @@ use rustc_type_ir::{self as ty, Interner}; use crate::delegate::SolverDelegate; use crate::solve::eval_ctxt::canonical; use crate::solve::{ - CanonicalInput, Certainty, GenerateProofTree, Goal, GoalEvaluationKind, GoalSource, QueryInput, + CanonicalInput, Certainty, GenerateProofTree, Goal, GoalEvaluationKind, GoalSource, QueryResult, inspect, }; @@ -119,6 +119,9 @@ impl WipCanonicalGoalEvaluation { } } +/// This only exists during proof tree building and does not have +/// a corresponding struct in `inspect`. We need this to track a +/// bunch of metadata about the current evaluation. #[derive_where(PartialEq, Eq, Debug; I: Interner)] struct WipCanonicalGoalEvaluationStep { /// Unlike `EvalCtxt::var_values`, we append a new @@ -128,7 +131,6 @@ struct WipCanonicalGoalEvaluationStep { /// This is necessary as we otherwise don't unify these /// vars when instantiating multiple `CanonicalState`. var_values: Vec, - instantiated_goal: QueryInput, probe_depth: usize, evaluation: WipProbe, } @@ -145,16 +147,12 @@ impl WipCanonicalGoalEvaluationStep { current } - fn finalize(self) -> inspect::CanonicalGoalEvaluationStep { + fn finalize(self) -> inspect::Probe { let evaluation = self.evaluation.finalize(); match evaluation.kind { - inspect::ProbeKind::Root { .. } => (), + inspect::ProbeKind::Root { .. } => evaluation, _ => unreachable!("unexpected root evaluation: {evaluation:?}"), } - inspect::CanonicalGoalEvaluationStep { - instantiated_goal: self.instantiated_goal, - evaluation, - } } } @@ -328,11 +326,9 @@ impl, I: Interner> ProofTreeBuilder { pub(crate) fn new_goal_evaluation_step( &mut self, var_values: ty::CanonicalVarValues, - instantiated_goal: QueryInput, ) -> ProofTreeBuilder { self.nested(|| WipCanonicalGoalEvaluationStep { var_values: var_values.var_values.to_vec(), - instantiated_goal, evaluation: WipProbe { initial_num_var_values: var_values.len(), steps: vec![], diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 4975a9ce0c75..e735020a63e6 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -344,7 +344,7 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { }; let mut nested_goals = vec![]; - self.candidates_recur(&mut candidates, &mut nested_goals, &last_eval_step.evaluation); + self.candidates_recur(&mut candidates, &mut nested_goals, &last_eval_step); candidates } diff --git a/compiler/rustc_type_ir/src/solve/inspect.rs b/compiler/rustc_type_ir/src/solve/inspect.rs index 138ba8bac887..d0e618dc6f96 100644 --- a/compiler/rustc_type_ir/src/solve/inspect.rs +++ b/compiler/rustc_type_ir/src/solve/inspect.rs @@ -23,9 +23,7 @@ use std::hash::Hash; use derive_where::derive_where; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; -use crate::solve::{ - CandidateSource, CanonicalInput, Certainty, Goal, GoalSource, QueryInput, QueryResult, -}; +use crate::solve::{CandidateSource, CanonicalInput, Certainty, Goal, GoalSource, QueryResult}; use crate::{Canonical, CanonicalVarValues, Interner}; /// Some `data` together with information about how they relate to the input @@ -69,15 +67,10 @@ pub struct CanonicalGoalEvaluation { #[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] pub enum CanonicalGoalEvaluationKind { Overflow, - Evaluation { final_revision: CanonicalGoalEvaluationStep }, -} - -#[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] -pub struct CanonicalGoalEvaluationStep { - pub instantiated_goal: QueryInput, - - /// The actual evaluation of the goal, always `ProbeKind::Root`. - pub evaluation: Probe, + Evaluation { + /// This is always `ProbeKind::Root`. + final_revision: Probe, + }, } /// A self-contained computation during trait solving. This either From 46ce5cbf339e1ea84d2b28ac04369084b9f2d948 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 8 Oct 2024 14:06:56 +0200 Subject: [PATCH 086/366] terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it) --- compiler/rustc_ast_passes/src/feature_gate.rs | 88 ++++++++++--------- .../src/check_consts/check.rs | 12 +-- .../src/error_codes/E0636.md | 4 +- .../src/error_codes/E0705.md | 2 +- compiler/rustc_expand/src/config.rs | 20 ++--- compiler/rustc_expand/src/mbe/quoted.rs | 2 +- compiler/rustc_feature/src/unstable.rs | 56 +++++------- compiler/rustc_lint/src/builtin.rs | 4 +- compiler/rustc_lint/src/levels.rs | 2 +- compiler/rustc_middle/src/middle/stability.rs | 8 +- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_passes/messages.ftl | 2 +- compiler/rustc_passes/src/check_const.rs | 4 +- compiler/rustc_passes/src/stability.rs | 12 +-- .../src/ich/impls_syntax.rs | 6 +- compiler/rustc_resolve/src/macros.rs | 6 +- compiler/rustc_target/src/spec/abi/mod.rs | 2 +- .../clippy_lints/src/manual_div_ceil.rs | 6 +- tests/rustdoc-ui/rustc-check-passes.stderr | 2 +- tests/ui/feature-gates/duplicate-features.rs | 4 +- .../feature-gates/duplicate-features.stderr | 4 +- 21 files changed, 117 insertions(+), 131 deletions(-) diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index f2773dcdc601..376ef85307b0 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -600,59 +600,61 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { } fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) { - // checks if `#![feature]` has been used to enable any lang feature - // does not check the same for lib features unless there's at least one - // declared lang feature - if !sess.opts.unstable_features.is_nightly_build() { - if features.declared_features.is_empty() { - return; - } - for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) { - let mut err = errors::FeatureOnNonNightly { - span: attr.span, - channel: option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"), - stable_features: vec![], - sugg: None, - }; - - let mut all_stable = true; - for ident in - attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) - { - let name = ident.name; - let stable_since = features - .declared_lang_features - .iter() - .flat_map(|&(feature, _, since)| if feature == name { since } else { None }) - .next(); - if let Some(since) = stable_since { - err.stable_features.push(errors::StableFeature { name, since }); - } else { - all_stable = false; - } - } - if all_stable { - err.sugg = Some(attr.span); - } - sess.dcx().emit_err(err); - } + // checks if `#![feature]` has been used to enable any feature. + if sess.opts.unstable_features.is_nightly_build() { + return; } + if features.enabled_features.is_empty() { + return; + } + let mut errored = false; + for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) { + // `feature(...)` used on non-nightly. This is definitely an error. + let mut err = errors::FeatureOnNonNightly { + span: attr.span, + channel: option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"), + stable_features: vec![], + sugg: None, + }; + + let mut all_stable = true; + for ident in attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) { + let name = ident.name; + let stable_since = features + .enabled_lang_features + .iter() + .flat_map(|&(feature, _, since)| if feature == name { since } else { None }) + .next(); + if let Some(since) = stable_since { + err.stable_features.push(errors::StableFeature { name, since }); + } else { + all_stable = false; + } + } + if all_stable { + err.sugg = Some(attr.span); + } + sess.dcx().emit_err(err); + errored = true; + } + // Just make sure we actually error if anything is listed in `enabled_features`. + assert!(errored); } fn check_incompatible_features(sess: &Session, features: &Features) { - let declared_features = features - .declared_lang_features + let enabled_features = features + .enabled_lang_features .iter() .copied() .map(|(name, span, _)| (name, span)) - .chain(features.declared_lib_features.iter().copied()); + .chain(features.enabled_lib_features.iter().copied()); for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES .iter() - .filter(|&&(f1, f2)| features.active(f1) && features.active(f2)) + .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2)) { - if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) { - if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2) + if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1) { + if let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2) { let spans = vec![f1_span, f2_span]; sess.dcx().emit_err(errors::IncompatibleFeatures { @@ -672,7 +674,7 @@ fn check_new_solver_banned_features(sess: &Session, features: &Features) { // Ban GCE with the new solver, because it does not implement GCE correctly. if let Some(&(_, gce_span, _)) = features - .declared_lang_features + .enabled_lang_features .iter() .find(|&&(feat, _, _)| feat == sym::generic_const_exprs) { diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 463a66d4e2e4..73344508a9d8 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -276,7 +276,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { let gate = match op.status_in_item(self.ccx) { Status::Allowed => return, - Status::Unstable(gate) if self.tcx.features().active(gate) => { + Status::Unstable(gate) if self.tcx.features().enabled(gate) => { let unstable_in_stable = self.ccx.is_const_stable_const_fn() && !super::rustc_allow_const_fn_unstable(self.tcx, self.def_id(), gate); if unstable_in_stable { @@ -700,10 +700,10 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // Calling an unstable function *always* requires that the corresponding gate // (or implied gate) be enabled, even if the function has // `#[rustc_allow_const_fn_unstable(the_gate)]`. - let gate_declared = |gate| tcx.features().declared(gate); - let feature_gate_declared = gate_declared(gate); - let implied_gate_declared = implied_by.is_some_and(gate_declared); - if !feature_gate_declared && !implied_gate_declared { + let gate_enabled = |gate| tcx.features().enabled(gate); + let feature_gate_enabled = gate_enabled(gate); + let implied_gate_enabled = implied_by.is_some_and(gate_enabled); + if !feature_gate_enabled && !implied_gate_enabled { self.check_op(ops::FnCallUnstable(callee, Some(gate))); return; } @@ -717,7 +717,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // Otherwise, we are something const-stable calling a const-unstable fn. if super::rustc_allow_const_fn_unstable(tcx, caller, gate) { - trace!("rustc_allow_const_fn_unstable gate active"); + trace!("rustc_allow_const_fn_unstable gate enabled"); return; } diff --git a/compiler/rustc_error_codes/src/error_codes/E0636.md b/compiler/rustc_error_codes/src/error_codes/E0636.md index 57cf72db5568..41fd701a8ede 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0636.md +++ b/compiler/rustc_error_codes/src/error_codes/E0636.md @@ -1,9 +1,9 @@ -A `#![feature]` attribute was declared multiple times. +The same feature is enabled multiple times with `#![feature]` attributes Erroneous code example: ```compile_fail,E0636 #![allow(stable_features)] #![feature(rust1)] -#![feature(rust1)] // error: the feature `rust1` has already been declared +#![feature(rust1)] // error: the feature `rust1` has already been enabled ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0705.md b/compiler/rustc_error_codes/src/error_codes/E0705.md index 317f3a47effa..e7d7d74cc4c8 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0705.md +++ b/compiler/rustc_error_codes/src/error_codes/E0705.md @@ -1,6 +1,6 @@ #### Note: this error code is no longer emitted by the compiler. -A `#![feature]` attribute was declared for a feature that is stable in the +A `#![feature]` attribute was used for a feature that is stable in the current edition, but not in all editions. Erroneous code example: diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index ea06415801f1..d08ebc5a9427 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -52,7 +52,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - let mut features = Features::default(); - // Process all features declared in the code. + // Process all features enabled in the code. for attr in krate_attrs { for mi in feature_list(attr) { let name = match mi.ident() { @@ -76,7 +76,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - } }; - // If the declared feature has been removed, issue an error. + // If the enabled feature has been removed, issue an error. if let Some(f) = REMOVED_FEATURES.iter().find(|f| name == f.feature.name) { sess.dcx().emit_err(FeatureRemoved { span: mi.span(), @@ -85,14 +85,14 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - continue; } - // If the declared feature is stable, record it. + // If the enabled feature is stable, record it. if let Some(f) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) { let since = Some(Symbol::intern(f.since)); - features.set_declared_lang_feature(name, mi.span(), since); + features.set_enabled_lang_feature(name, mi.span(), since); continue; } - // If `-Z allow-features` is used and the declared feature is + // If `-Z allow-features` is used and the enabled feature is // unstable and not also listed as one of the allowed features, // issue an error. if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() { @@ -102,7 +102,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - } } - // If the declared feature is unstable, record it. + // If the enabled feature is unstable, record it. if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name) { (f.set_enabled)(&mut features); // When the ICE comes from core, alloc or std (approximation of the standard @@ -115,13 +115,13 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - { sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed); } - features.set_declared_lang_feature(name, mi.span(), None); + features.set_enabled_lang_feature(name, mi.span(), None); continue; } - // Otherwise, the feature is unknown. Record it as a lib feature. - // It will be checked later. - features.set_declared_lib_feature(name, mi.span()); + // Otherwise, the feature is unknown. Enable it as a lib feature. + // It will be checked later whether the feature really exists. + features.set_enabled_lib_feature(name, mi.span()); // Similar to above, detect internal lib features to suppress // the ICE message that asks for a report. diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index 2edd289625e1..e518b27e419f 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -119,7 +119,7 @@ pub(super) fn parse( result } -/// Asks for the `macro_metavar_expr` feature if it is not already declared +/// Asks for the `macro_metavar_expr` feature if it is not enabled fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &Session, span: Span) { if !features.macro_metavar_expr { let msg = "meta-variable expressions are unstable"; diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index fc3696c40226..166f2af22105 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -54,14 +54,13 @@ macro_rules! declare_features { #[derive(Clone, Default, Debug)] pub struct Features { /// `#![feature]` attrs for language features, for error reporting. - /// "declared" here means that the feature is actually enabled in the current crate. - pub declared_lang_features: Vec<(Symbol, Span, Option)>, + pub enabled_lang_features: Vec<(Symbol, Span, Option)>, /// `#![feature]` attrs for non-language (library) features. - /// "declared" here means that the feature is actually enabled in the current crate. - pub declared_lib_features: Vec<(Symbol, Span)>, - /// `declared_lang_features` + `declared_lib_features`. - pub declared_features: FxHashSet, - /// Active state of individual features (unstable only). + pub enabled_lib_features: Vec<(Symbol, Span)>, + /// `enabled_lang_features` + `enabled_lib_features`. + pub enabled_features: FxHashSet, + /// State of individual features (unstable lang features only). + /// This is `true` if and only if the corresponding feature is listed in `enabled_lang_features`. $( $(#[doc = $doc])* pub $feature: bool @@ -69,46 +68,34 @@ macro_rules! declare_features { } impl Features { - pub fn set_declared_lang_feature( + pub fn set_enabled_lang_feature( &mut self, symbol: Symbol, span: Span, since: Option ) { - self.declared_lang_features.push((symbol, span, since)); - self.declared_features.insert(symbol); + self.enabled_lang_features.push((symbol, span, since)); + self.enabled_features.insert(symbol); } - pub fn set_declared_lib_feature(&mut self, symbol: Symbol, span: Span) { - self.declared_lib_features.push((symbol, span)); - self.declared_features.insert(symbol); + pub fn set_enabled_lib_feature(&mut self, symbol: Symbol, span: Span) { + self.enabled_lib_features.push((symbol, span)); + self.enabled_features.insert(symbol); } - /// This is intended for hashing the set of active features. + /// This is intended for hashing the set of enabled language features. /// /// The expectation is that this produces much smaller code than other alternatives. /// /// Note that the total feature count is pretty small, so this is not a huge array. #[inline] - pub fn all_features(&self) -> [u8; NUM_FEATURES] { + pub fn all_lang_features(&self) -> [u8; NUM_FEATURES] { [$(self.$feature as u8),+] } - /// Is the given feature explicitly declared, i.e. named in a - /// `#![feature(...)]` within the code? - pub fn declared(&self, feature: Symbol) -> bool { - self.declared_features.contains(&feature) - } - - /// Is the given feature active (enabled by the user)? - /// - /// Panics if the symbol doesn't correspond to a declared feature. - pub fn active(&self, feature: Symbol) -> bool { - match feature { - $( sym::$feature => self.$feature, )* - - _ => panic!("`{}` was not listed in `declare_features`", feature), - } + /// Is the given feature enabled (via `#[feature(...)]`)? + pub fn enabled(&self, feature: Symbol) -> bool { + self.enabled_features.contains(&feature) } /// Some features are known to be incomplete and using them is likely to have @@ -119,8 +106,11 @@ macro_rules! declare_features { $( sym::$feature => status_to_enum!($status) == FeatureStatus::Incomplete, )* - // Accepted/removed features aren't in this file but are never incomplete. - _ if self.declared_features.contains(&feature) => false, + _ if self.enabled_features.contains(&feature) => { + // Accepted/removed features and library features aren't in this file but + // are never incomplete. + false + } _ => panic!("`{}` was not listed in `declare_features`", feature), } } @@ -132,7 +122,7 @@ macro_rules! declare_features { $( sym::$feature => status_to_enum!($status) == FeatureStatus::Internal, )* - _ if self.declared_features.contains(&feature) => { + _ if self.enabled_features.contains(&feature) => { // This could be accepted/removed, or a libs feature. // Accepted/removed features aren't in this file but are never internal // (a removed feature might have been internal, but that's now irrelevant). diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index ef8100da9e2e..8fac1a82e8a3 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2288,10 +2288,10 @@ impl EarlyLintPass for IncompleteInternalFeatures { fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { let features = cx.builder.features(); features - .declared_lang_features + .enabled_lang_features .iter() .map(|(name, span, _)| (name, span)) - .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span))) + .chain(features.enabled_lib_features.iter().map(|(name, span)| (name, span))) .filter(|(&name, _)| features.incomplete(name) || features.internal(name)) .for_each(|(&name, &span)| { if features.incomplete(name) { diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 95a8e7625ff4..ff2ae69e1db8 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -858,7 +858,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { #[track_caller] fn check_gated_lint(&self, lint_id: LintId, span: Span, lint_from_cli: bool) -> bool { let feature = if let Some(feature) = lint_id.lint.feature_gate - && !self.features.active(feature) + && !self.features.enabled(feature) { // Lint is behind a feature that is not enabled; eventually return false. feature diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index ee34ccd889f7..c0688aff1832 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -422,15 +422,15 @@ impl<'tcx> TyCtxt<'tcx> { debug!("stability: skipping span={:?} since it is internal", span); return EvalResult::Allow; } - if self.features().declared(feature) { + if self.features().enabled(feature) { return EvalResult::Allow; } // If this item was previously part of a now-stabilized feature which is still - // active (i.e. the user hasn't removed the attribute for the stabilized feature + // enabled (i.e. the user hasn't removed the attribute for the stabilized feature // yet) then allow use of this item. if let Some(implied_by) = implied_by - && self.features().declared(implied_by) + && self.features().enabled(implied_by) { return EvalResult::Allow; } @@ -509,7 +509,7 @@ impl<'tcx> TyCtxt<'tcx> { debug!("body stability: skipping span={:?} since it is internal", span); return EvalResult::Allow; } - if self.features().declared(feature) { + if self.features().enabled(feature) { return EvalResult::Allow; } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index c2a550604906..210b115ae370 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -3093,7 +3093,7 @@ impl<'tcx> TyCtxt<'tcx> { Some(stability) if stability.is_const_unstable() => { // has a `rustc_const_unstable` attribute, check whether the user enabled the // corresponding feature gate. - self.features().declared(stability.feature) + self.features().enabled(stability.feature) } // functions without const stability are either stable user written // const fn or the user is using feature gates and we thus don't diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 3613b7b862d7..899a7b841008 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -256,7 +256,7 @@ passes_duplicate_diagnostic_item_in_crate = .note = the diagnostic item is first defined in crate `{$orig_crate_name}` passes_duplicate_feature_err = - the feature `{$feature}` has already been declared + the feature `{$feature}` has already been enabled passes_duplicate_lang_item = found duplicate lang item `{$lang_item_name}` diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index 0dad94a9939f..ca13ca11673f 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -87,7 +87,7 @@ impl<'tcx> CheckConstVisitor<'tcx> { let is_feature_allowed = |feature_gate| { // All features require that the corresponding gate be enabled, // even if the function has `#[rustc_allow_const_fn_unstable(the_gate)]`. - if !tcx.features().active(feature_gate) { + if !tcx.features().enabled(feature_gate) { return false; } @@ -135,7 +135,7 @@ impl<'tcx> CheckConstVisitor<'tcx> { let required_gates = required_gates.unwrap_or(&[]); let missing_gates: Vec<_> = - required_gates.iter().copied().filter(|&g| !features.active(g)).collect(); + required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect(); match missing_gates.as_slice() { [] => { diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 751c87a9fe51..2f94edc83a58 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -935,9 +935,9 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { tcx.hir().visit_all_item_likes_in_crate(&mut missing); } - let declared_lang_features = &tcx.features().declared_lang_features; + let enabled_lang_features = &tcx.features().enabled_lang_features; let mut lang_features = UnordSet::default(); - for &(feature, span, since) in declared_lang_features { + for &(feature, span, since) in enabled_lang_features { if let Some(since) = since { // Warn if the user has enabled an already-stable lang feature. unnecessary_stable_feature_lint(tcx, span, feature, since); @@ -948,9 +948,9 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { } } - let declared_lib_features = &tcx.features().declared_lib_features; + let enabled_lib_features = &tcx.features().enabled_lib_features; let mut remaining_lib_features = FxIndexMap::default(); - for (feature, span) in declared_lib_features { + for (feature, span) in enabled_lib_features { if remaining_lib_features.contains_key(&feature) { // Warn if the user enables a lib feature multiple times. tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *span, feature: *feature }); @@ -961,7 +961,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { // recognise the feature when building std. // Likewise, libtest is handled specially, so `test` isn't // available as we'd like it to be. - // FIXME: only remove `libc` when `stdbuild` is active. + // FIXME: only remove `libc` when `stdbuild` is enabled. // FIXME: remove special casing for `test`. // FIXME(#120456) - is `swap_remove` correct? remaining_lib_features.swap_remove(&sym::libc); @@ -1021,7 +1021,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { // All local crate implications need to have the feature that implies it confirmed to exist. let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone(); - // We always collect the lib features declared in the current crate, even if there are + // We always collect the lib features enabled in the current crate, even if there are // no unknown features, because the collection also does feature attribute validation. let local_defined_features = tcx.lib_features(LOCAL_CRATE); if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() { diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 5e450979273a..797db3a17bd3 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -112,10 +112,10 @@ impl<'tcx> HashStable> for rustc_feature::Features { fn hash_stable(&self, hcx: &mut StableHashingContext<'tcx>, hasher: &mut StableHasher) { // Unfortunately we cannot exhaustively list fields here, since the // struct is macro generated. - self.declared_lang_features.hash_stable(hcx, hasher); - self.declared_lib_features.hash_stable(hcx, hasher); + self.enabled_lang_features.hash_stable(hcx, hasher); + self.enabled_lib_features.hash_stable(hcx, hasher); - self.all_features()[..].hash_stable(hcx, hasher); + self.all_lang_features()[..].hash_stable(hcx, hasher); for feature in rustc_feature::UNSTABLE_FEATURES.iter() { feature.feature.name.hash_stable(hcx, hasher); } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index e43c87186658..5e38fb5b6c51 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -1007,10 +1007,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { { let feature = stability.feature; - let is_allowed = |feature| { - self.tcx.features().declared_features.contains(&feature) - || span.allows_unstable(feature) - }; + let is_allowed = + |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature); let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature)); if !is_allowed(feature) && !allowed_by_implication { let lint_buffer = &mut self.lint_buffer; diff --git a/compiler/rustc_target/src/spec/abi/mod.rs b/compiler/rustc_target/src/spec/abi/mod.rs index cac0cf9959d2..c2095155afaf 100644 --- a/compiler/rustc_target/src/spec/abi/mod.rs +++ b/compiler/rustc_target/src/spec/abi/mod.rs @@ -184,7 +184,7 @@ pub fn is_enabled( ) -> Result<(), AbiDisabled> { let s = is_stable(name); if let Err(AbiDisabled::Unstable { feature, .. }) = s { - if features.active(feature) || span.allows_unstable(feature) { + if features.enabled(feature) || span.allows_unstable(feature) { return Ok(()); } } diff --git a/src/tools/clippy/clippy_lints/src/manual_div_ceil.rs b/src/tools/clippy/clippy_lints/src/manual_div_ceil.rs index 00e02e2a3365..4c171e6d890f 100644 --- a/src/tools/clippy/clippy_lints/src/manual_div_ceil.rs +++ b/src/tools/clippy/clippy_lints/src/manual_div_ceil.rs @@ -111,11 +111,7 @@ fn check_int_ty_and_feature(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { let expr_ty = cx.typeck_results().expr_ty(expr); match expr_ty.peel_refs().kind() { ty::Uint(_) => true, - ty::Int(_) => cx - .tcx - .features() - .declared_features - .contains(&Symbol::intern("int_roundings")), + ty::Int(_) => cx.tcx.features().enabled(Symbol::intern("int_roundings")), _ => false, } diff --git a/tests/rustdoc-ui/rustc-check-passes.stderr b/tests/rustdoc-ui/rustc-check-passes.stderr index 58d61c0213ec..5b20d1128c59 100644 --- a/tests/rustdoc-ui/rustc-check-passes.stderr +++ b/tests/rustdoc-ui/rustc-check-passes.stderr @@ -1,4 +1,4 @@ -error[E0636]: the feature `rustdoc_internals` has already been declared +error[E0636]: the feature `rustdoc_internals` has already been enabled --> $DIR/rustc-check-passes.rs:2:12 | LL | #![feature(rustdoc_internals)] diff --git a/tests/ui/feature-gates/duplicate-features.rs b/tests/ui/feature-gates/duplicate-features.rs index d8f7818054a1..1fae71c3eb2b 100644 --- a/tests/ui/feature-gates/duplicate-features.rs +++ b/tests/ui/feature-gates/duplicate-features.rs @@ -1,9 +1,9 @@ #![allow(stable_features)] #![feature(rust1)] -#![feature(rust1)] //~ ERROR the feature `rust1` has already been declared +#![feature(rust1)] //~ ERROR the feature `rust1` has already been enabled #![feature(if_let)] -#![feature(if_let)] //~ ERROR the feature `if_let` has already been declared +#![feature(if_let)] //~ ERROR the feature `if_let` has already been enabled fn main() {} diff --git a/tests/ui/feature-gates/duplicate-features.stderr b/tests/ui/feature-gates/duplicate-features.stderr index dbde806f6cc4..f667a5b9623f 100644 --- a/tests/ui/feature-gates/duplicate-features.stderr +++ b/tests/ui/feature-gates/duplicate-features.stderr @@ -1,10 +1,10 @@ -error[E0636]: the feature `if_let` has already been declared +error[E0636]: the feature `if_let` has already been enabled --> $DIR/duplicate-features.rs:7:12 | LL | #![feature(if_let)] | ^^^^^^ -error[E0636]: the feature `rust1` has already been declared +error[E0636]: the feature `rust1` has already been enabled --> $DIR/duplicate-features.rs:4:12 | LL | #![feature(rust1)] From 1381773e01210cc7f377a9ab1aa886e621ceafe4 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 9 Oct 2024 08:30:43 +0200 Subject: [PATCH 087/366] make some rustc_feature internals private, and ensure invariants with debug assertions --- compiler/rustc_ast_passes/src/feature_gate.rs | 10 +-- compiler/rustc_expand/src/config.rs | 5 +- compiler/rustc_feature/src/unstable.rs | 61 +++++++++++++++---- compiler/rustc_lint/src/builtin.rs | 4 +- compiler/rustc_passes/src/stability.rs | 4 +- .../src/ich/impls_syntax.rs | 4 +- 6 files changed, 62 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 376ef85307b0..94fcfabc32ca 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -604,7 +604,7 @@ fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) if sess.opts.unstable_features.is_nightly_build() { return; } - if features.enabled_features.is_empty() { + if features.enabled_features().is_empty() { return; } let mut errored = false; @@ -621,7 +621,7 @@ fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) for ident in attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) { let name = ident.name; let stable_since = features - .enabled_lang_features + .enabled_lang_features() .iter() .flat_map(|&(feature, _, since)| if feature == name { since } else { None }) .next(); @@ -643,11 +643,11 @@ fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) fn check_incompatible_features(sess: &Session, features: &Features) { let enabled_features = features - .enabled_lang_features + .enabled_lang_features() .iter() .copied() .map(|(name, span, _)| (name, span)) - .chain(features.enabled_lib_features.iter().copied()); + .chain(features.enabled_lib_features().iter().copied()); for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES .iter() @@ -674,7 +674,7 @@ fn check_new_solver_banned_features(sess: &Session, features: &Features) { // Ban GCE with the new solver, because it does not implement GCE correctly. if let Some(&(_, gce_span, _)) = features - .enabled_lang_features + .enabled_lang_features() .iter() .find(|&&(feat, _, _)| feat == sym::generic_const_exprs) { diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index d08ebc5a9427..a6b7291ee8f4 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -88,7 +88,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - // If the enabled feature is stable, record it. if let Some(f) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) { let since = Some(Symbol::intern(f.since)); - features.set_enabled_lang_feature(name, mi.span(), since); + features.set_enabled_lang_feature(name, mi.span(), since, None); continue; } @@ -104,7 +104,6 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - // If the enabled feature is unstable, record it. if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name) { - (f.set_enabled)(&mut features); // When the ICE comes from core, alloc or std (approximation of the standard // library), there's a chance that the person hitting the ICE may be using // -Zbuild-std or similar with an untested target. The bug is probably in the @@ -115,7 +114,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - { sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed); } - features.set_enabled_lang_feature(name, mi.span(), None); + features.set_enabled_lang_feature(name, mi.span(), None, Some(f)); continue; } diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 166f2af22105..0f9cf34fc185 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -8,7 +8,7 @@ use super::{Feature, to_nonzero}; pub struct UnstableFeature { pub feature: Feature, - pub set_enabled: fn(&mut Features), + set_enabled: fn(&mut Features), } #[derive(PartialEq)] @@ -54,11 +54,11 @@ macro_rules! declare_features { #[derive(Clone, Default, Debug)] pub struct Features { /// `#![feature]` attrs for language features, for error reporting. - pub enabled_lang_features: Vec<(Symbol, Span, Option)>, + enabled_lang_features: Vec<(Symbol, Span, Option)>, /// `#![feature]` attrs for non-language (library) features. - pub enabled_lib_features: Vec<(Symbol, Span)>, + enabled_lib_features: Vec<(Symbol, Span)>, /// `enabled_lang_features` + `enabled_lib_features`. - pub enabled_features: FxHashSet, + enabled_features: FxHashSet, /// State of individual features (unstable lang features only). /// This is `true` if and only if the corresponding feature is listed in `enabled_lang_features`. $( @@ -70,17 +70,27 @@ macro_rules! declare_features { impl Features { pub fn set_enabled_lang_feature( &mut self, - symbol: Symbol, + name: Symbol, span: Span, - since: Option + since: Option, + feature: Option<&UnstableFeature>, ) { - self.enabled_lang_features.push((symbol, span, since)); - self.enabled_features.insert(symbol); + self.enabled_lang_features.push((name, span, since)); + self.enabled_features.insert(name); + if let Some(feature) = feature { + assert_eq!(feature.feature.name, name); + (feature.set_enabled)(self); + } else { + // Ensure we don't skip a `set_enabled` call. + debug_assert!(UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name).is_none()); + } } - pub fn set_enabled_lib_feature(&mut self, symbol: Symbol, span: Span) { - self.enabled_lib_features.push((symbol, span)); - self.enabled_features.insert(symbol); + pub fn set_enabled_lib_feature(&mut self, name: Symbol, span: Span) { + self.enabled_lib_features.push((name, span)); + self.enabled_features.insert(name); + // Ensure we don't skip a `set_enabled` call. + debug_assert!(UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name).is_none()); } /// This is intended for hashing the set of enabled language features. @@ -93,9 +103,36 @@ macro_rules! declare_features { [$(self.$feature as u8),+] } + pub fn enabled_lang_features(&self) -> &Vec<(Symbol, Span, Option)> { + &self.enabled_lang_features + } + + pub fn enabled_lib_features(&self) -> &Vec<(Symbol, Span)> { + &self.enabled_lib_features + } + + pub fn enabled_features(&self) -> &FxHashSet { + &self.enabled_features + } + /// Is the given feature enabled (via `#[feature(...)]`)? pub fn enabled(&self, feature: Symbol) -> bool { - self.enabled_features.contains(&feature) + let e = self.enabled_features.contains(&feature); + if cfg!(debug_assertions) { + // Ensure this matches `self.$feature`, if that exists. + let e2 = match feature { + $( sym::$feature => Some(self.$feature), )* + _ => None, + }; + if let Some(e2) = e2 { + assert_eq!( + e, e2, + "mismatch in feature state for `{feature}`: \ + `enabled_features` says {e} but `self.{feature}` says {e2}" + ); + } + } + e } /// Some features are known to be incomplete and using them is likely to have diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 8fac1a82e8a3..125fe9b3f16f 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2288,10 +2288,10 @@ impl EarlyLintPass for IncompleteInternalFeatures { fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { let features = cx.builder.features(); features - .enabled_lang_features + .enabled_lang_features() .iter() .map(|(name, span, _)| (name, span)) - .chain(features.enabled_lib_features.iter().map(|(name, span)| (name, span))) + .chain(features.enabled_lib_features().iter().map(|(name, span)| (name, span))) .filter(|(&name, _)| features.incomplete(name) || features.internal(name)) .for_each(|(&name, &span)| { if features.incomplete(name) { diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 2f94edc83a58..80ac2741c386 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -935,7 +935,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { tcx.hir().visit_all_item_likes_in_crate(&mut missing); } - let enabled_lang_features = &tcx.features().enabled_lang_features; + let enabled_lang_features = tcx.features().enabled_lang_features(); let mut lang_features = UnordSet::default(); for &(feature, span, since) in enabled_lang_features { if let Some(since) = since { @@ -948,7 +948,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { } } - let enabled_lib_features = &tcx.features().enabled_lib_features; + let enabled_lib_features = tcx.features().enabled_lib_features(); let mut remaining_lib_features = FxIndexMap::default(); for (feature, span) in enabled_lib_features { if remaining_lib_features.contains_key(&feature) { diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 797db3a17bd3..78c37688d34c 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -112,8 +112,8 @@ impl<'tcx> HashStable> for rustc_feature::Features { fn hash_stable(&self, hcx: &mut StableHashingContext<'tcx>, hasher: &mut StableHasher) { // Unfortunately we cannot exhaustively list fields here, since the // struct is macro generated. - self.enabled_lang_features.hash_stable(hcx, hasher); - self.enabled_lib_features.hash_stable(hcx, hasher); + self.enabled_lang_features().hash_stable(hcx, hasher); + self.enabled_lib_features().hash_stable(hcx, hasher); self.all_lang_features()[..].hash_stable(hcx, hasher); for feature in rustc_feature::UNSTABLE_FEATURES.iter() { From 88b9b9d5dab1ecd3038149d80c8e75fe3302084a Mon Sep 17 00:00:00 2001 From: Duncan Proctor Date: Tue, 22 Oct 2024 03:11:23 -0400 Subject: [PATCH 088/366] goto definition on RangeFrom, RangeFull, RangeTo, and RangeToInclusive links to respective struct --- .../crates/hir/src/source_analyzer.rs | 14 ++- .../crates/ide/src/goto_definition.rs | 103 +++++++++++------- 2 files changed, 73 insertions(+), 44 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 5e05fad8c397..e95041b923ff 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -353,9 +353,17 @@ impl SourceAnalyzer { db: &dyn HirDatabase, range_expr: &ast::RangeExpr, ) -> Option { - let path = match range_expr.op_kind()? { - RangeOp::Exclusive => path![core::ops::Range], - RangeOp::Inclusive => path![core::ops::RangeInclusive], + let path: ModPath = match (range_expr.op_kind()?, range_expr.start(), range_expr.end()) { + (RangeOp::Exclusive, None, None) => path![core::ops::RangeFull], + (RangeOp::Exclusive, None, Some(_)) => path![core::ops::RangeTo], + (RangeOp::Exclusive, Some(_), None) => path![core::ops::RangeFrom], + (RangeOp::Exclusive, Some(_), Some(_)) => path![core::ops::Range], + (RangeOp::Inclusive, None, Some(_)) => path![core::ops::RangeToInclusive], + (RangeOp::Inclusive, Some(_), Some(_)) => path![core::ops::RangeInclusive], + + // [E0586] inclusive ranges must be bounded at the end + (RangeOp::Inclusive, None, None) => return None, + (RangeOp::Inclusive, Some(_), None) => return None }; self.resolver.resolve_known_struct(db.upcast(), &path) } diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 4c965fd2d86a..c532e2593555 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -449,55 +449,76 @@ mod tests { assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {navs:?}") } - #[test] - fn goto_def_range_inclusive_0() { - let ra_fixture = r#" -//- minicore: range -fn f(a: usize, b: usize) { - for _ in a.$0.=b { - - } -} -"#; + fn check_name(expected_name: &str, ra_fixture: &str) { let (analysis, position, _) = fixture::annotations(ra_fixture); - let mut navs = - analysis.goto_definition(position).unwrap().expect("no definition found").info; - let Some(target) = navs.pop() else { panic!("no target found") }; - assert_eq!(target.name, SmolStr::new_inline("RangeInclusive")); - } - - #[test] - fn goto_def_range_inclusive_1() { - let ra_fixture = r#" -//- minicore: range -fn f(a: usize, b: usize) { - for _ in a..$0=b { - - } -} -"#; - let (analysis, position, _) = fixture::annotations(ra_fixture); - let mut navs = - analysis.goto_definition(position).unwrap().expect("no definition found").info; - let Some(target) = navs.pop() else { panic!("no target found") }; - assert_eq!(target.name, SmolStr::new_inline("RangeInclusive")); + let navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; + assert!(navs.len() < 2, "expected single navigation target but encountered {}", navs.len()); + let Some(target) = navs.into_iter().next() else { + panic!("expected single navigation target but encountered none"); + }; + assert_eq!(target.name, SmolStr::new_inline(expected_name)); } #[test] fn goto_def_range() { - let ra_fixture = r#" + check_name("Range", r#" //- minicore: range -fn f(a: usize, b: usize) { - for _ in a.$0.b { - +let x = 0.$0.1; +"# + ); } + + #[test] + fn goto_def_range_from() { + check_name("RangeFrom", r#" +//- minicore: range +fn f(arr: &[i32]) -> &[i32] { + &arr[0.$0.] } -"#; - let (analysis, position, _) = fixture::annotations(ra_fixture); - let mut navs = - analysis.goto_definition(position).unwrap().expect("no definition found").info; - let Some(target) = navs.pop() else { panic!("no target found") }; - assert_eq!(target.name, SmolStr::new_inline("Range")); +"# + ); + } + + #[test] + fn goto_def_range_inclusive() { + check_name("RangeInclusive", r#" +//- minicore: range +let x = 0.$0.=1; +"# + ); + } + + #[test] + fn goto_def_range_full() { + check_name("RangeFull", r#" +//- minicore: range +fn f(arr: &[i32]) -> &[i32] { + &arr[.$0.] +} +"# + ); + } + + #[test] + fn goto_def_range_to() { + check_name("RangeTo", r#" +//- minicore: range +fn f(arr: &[i32]) -> &[i32] { + &arr[.$0.10] +} +"# + ); + } + + #[test] + fn goto_def_range_to_inclusive() { + check_name("RangeToInclusive", r#" +//- minicore: range +fn f(arr: &[i32]) -> &[i32] { + &arr[.$0.=10] +} +"# + ); } #[test] From 5038ee728227325ac0aca5e44c42171e473a93e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Tue, 22 Oct 2024 10:12:20 +0300 Subject: [PATCH 089/366] Preparing for merge from rust-lang/rust --- src/tools/rust-analyzer/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/rust-version b/src/tools/rust-analyzer/rust-version index d0f9fa7ac429..bc324402a96e 100644 --- a/src/tools/rust-analyzer/rust-version +++ b/src/tools/rust-analyzer/rust-version @@ -1 +1 @@ -dd5127615ad626741a1116d022cf784637ac05df +1de57a5ce952c722f7053aeacfc6c90bc139b678 From 420b665c60fe659ad05296fb6bd471ce6c724778 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Tue, 22 Oct 2024 10:12:46 +0300 Subject: [PATCH 090/366] Bump rustc crates --- src/tools/rust-analyzer/Cargo.toml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.toml b/src/tools/rust-analyzer/Cargo.toml index 397c68319de4..9db62de9abfc 100644 --- a/src/tools/rust-analyzer/Cargo.toml +++ b/src/tools/rust-analyzer/Cargo.toml @@ -85,11 +85,11 @@ tt = { path = "./crates/tt", version = "0.0.0" } vfs-notify = { path = "./crates/vfs-notify", version = "0.0.0" } vfs = { path = "./crates/vfs", version = "0.0.0" } -ra-ap-rustc_lexer = { version = "0.71.0", default-features = false } -ra-ap-rustc_parse_format = { version = "0.71.0", default-features = false } -ra-ap-rustc_index = { version = "0.71.0", default-features = false } -ra-ap-rustc_abi = { version = "0.71.0", default-features = false } -ra-ap-rustc_pattern_analysis = { version = "0.71.0", default-features = false } +ra-ap-rustc_lexer = { version = "0.73", default-features = false } +ra-ap-rustc_parse_format = { version = "0.73", default-features = false } +ra-ap-rustc_index = { version = "0.73", default-features = false } +ra-ap-rustc_abi = { version = "0.73", default-features = false } +ra-ap-rustc_pattern_analysis = { version = "0.73", default-features = false } # local crates that aren't published to crates.io. These should not have versions. test-fixture = { path = "./crates/test-fixture" } From efc2ba2d902e979770a17e2da6e3d289d6909812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Tue, 22 Oct 2024 10:19:25 +0300 Subject: [PATCH 091/366] Replace some LayoutError variants with the rustc_abi errors --- src/tools/rust-analyzer/Cargo.lock | 26 +++++++++---------- .../rust-analyzer/crates/hir-ty/src/layout.rs | 20 +++++++------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index 951c7f8bbacc..fd569571b38b 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -1497,9 +1497,9 @@ dependencies = [ [[package]] name = "ra-ap-rustc_abi" -version = "0.71.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6999d098000b98415939f13158dac78cb3eeeb7b0c073847f3e4b623866e27c" +checksum = "879ece0781e3c1cb670b9f29775c81a43a16db789d1296fad6bc5c74065b2fac" dependencies = [ "bitflags 2.6.0", "ra-ap-rustc_index", @@ -1508,9 +1508,9 @@ dependencies = [ [[package]] name = "ra-ap-rustc_index" -version = "0.71.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae9fb312d942817dab10790881f555928c1f6a11a85186e8e573ad4a86c7d3be" +checksum = "6910087ff89bb9f3db114bfcd86b5139042731fe7278d3ff4ceaa69a140154a7" dependencies = [ "arrayvec", "ra-ap-rustc_index_macros", @@ -1519,9 +1519,9 @@ dependencies = [ [[package]] name = "ra-ap-rustc_index_macros" -version = "0.71.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "766e3990eb1066a06deefc561b5a01b32ca5c9211feea31cbf4ed50611519872" +checksum = "3b6f7bd12b678fbb37444ba77f3b0cfc13b7394a6dc7b0c799491fc9df0a9997" dependencies = [ "proc-macro2", "quote", @@ -1530,9 +1530,9 @@ dependencies = [ [[package]] name = "ra-ap-rustc_lexer" -version = "0.71.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4afa98eb7889c137d5a3f1cd189089e16da04d1e4837d358a67aa3dab10ffbe" +checksum = "119bc05b5b6bc3e7f5b67ce8b8080e185da94bd83c447f91b6b3f3ecf60cbab1" dependencies = [ "unicode-properties", "unicode-xid", @@ -1540,9 +1540,9 @@ dependencies = [ [[package]] name = "ra-ap-rustc_parse_format" -version = "0.71.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9234c96ffb0565286790407fb7eb7f55ebf69267de4db382fdec0a17f14b0e2" +checksum = "70ed6150ae71d905c064dc88d7824ebb0fa81083f45d7477cba7b57176f2f635" dependencies = [ "ra-ap-rustc_index", "ra-ap-rustc_lexer", @@ -1550,12 +1550,12 @@ dependencies = [ [[package]] name = "ra-ap-rustc_pattern_analysis" -version = "0.71.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "273d5f72926a58c7eea27aebc898d1d5b32d23d2342f692a94a2cf8746aa4a2f" +checksum = "6e830862a0ec85fce211d34735315686bb8d6a12d418d6d735fb534aa1cd3293" dependencies = [ "ra-ap-rustc_index", - "rustc-hash 1.1.0", + "rustc-hash 2.0.0", "rustc_apfloat", "smallvec", "tracing", diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs b/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs index 2c68d50013ea..80831440720c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs @@ -72,18 +72,15 @@ pub type Variants = hir_def::layout::Variants), - EmptyUnion, HasErrorConst, HasErrorType, HasPlaceholder, InvalidSimdType, NotImplemented, RecursiveTypeWithoutIndirection, - SizeOverflow, TargetLayoutNotAvailable, - UnexpectedUnsized, Unknown, UserReprTooSmall, } @@ -93,7 +90,6 @@ impl fmt::Display for LayoutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { LayoutError::BadCalc(err) => err.fallback_fmt(f), - LayoutError::EmptyUnion => write!(f, "type is an union with no fields"), LayoutError::HasErrorConst => write!(f, "type contains an unevaluatable const"), LayoutError::HasErrorType => write!(f, "type contains an error"), LayoutError::HasPlaceholder => write!(f, "type contains placeholders"), @@ -102,11 +98,7 @@ impl fmt::Display for LayoutError { LayoutError::RecursiveTypeWithoutIndirection => { write!(f, "recursive type without indirection") } - LayoutError::SizeOverflow => write!(f, "size overflow"), LayoutError::TargetLayoutNotAvailable => write!(f, "target layout not available"), - LayoutError::UnexpectedUnsized => { - write!(f, "an unsized type was found where a sized type was expected") - } LayoutError::Unknown => write!(f, "unknown"), LayoutError::UserReprTooSmall => { write!(f, "the `#[repr]` hint is too small to hold the discriminants of the enum") @@ -181,7 +173,10 @@ fn layout_of_simd_ty( }; // Compute the size and alignment of the vector: - let size = e_ly.size.checked_mul(e_len, dl).ok_or(LayoutError::SizeOverflow)?; + let size = e_ly + .size + .checked_mul(e_len, dl) + .ok_or(LayoutError::BadCalc(LayoutCalculatorError::SizeOverflow))?; let align = dl.vector_align(size); let size = size.align_to(align.abi); @@ -294,7 +289,10 @@ pub fn layout_of_ty_query( TyKind::Array(element, count) => { let count = try_const_usize(db, count).ok_or(LayoutError::HasErrorConst)? as u64; let element = db.layout_of_ty(element.clone(), trait_env)?; - let size = element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow)?; + let size = element + .size + .checked_mul(count, dl) + .ok_or(LayoutError::BadCalc(LayoutCalculatorError::SizeOverflow))?; let abi = if count != 0 && matches!(element.abi, Abi::Uninhabited) { Abi::Uninhabited From b76391332969741c601619238204d9557f7d29ac Mon Sep 17 00:00:00 2001 From: Duncan Proctor Date: Tue, 22 Oct 2024 03:19:47 -0400 Subject: [PATCH 092/366] tidy --- .../crates/hir/src/source_analyzer.rs | 2 +- .../crates/ide/src/goto_definition.rs | 40 ++++++++++++------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index e95041b923ff..be0e57b0b1dd 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -363,7 +363,7 @@ impl SourceAnalyzer { // [E0586] inclusive ranges must be bounded at the end (RangeOp::Inclusive, None, None) => return None, - (RangeOp::Inclusive, Some(_), None) => return None + (RangeOp::Inclusive, Some(_), None) => return None, }; self.resolver.resolve_known_struct(db.upcast(), &path) } diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index c532e2593555..5c9ca0bc89af 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -453,71 +453,83 @@ mod tests { let (analysis, position, _) = fixture::annotations(ra_fixture); let navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; assert!(navs.len() < 2, "expected single navigation target but encountered {}", navs.len()); - let Some(target) = navs.into_iter().next() else { - panic!("expected single navigation target but encountered none"); + let Some(target) = navs.into_iter().next() else { + panic!("expected single navigation target but encountered none"); }; assert_eq!(target.name, SmolStr::new_inline(expected_name)); } #[test] fn goto_def_range() { - check_name("Range", r#" + check_name( + "Range", + r#" //- minicore: range let x = 0.$0.1; -"# +"#, ); } #[test] fn goto_def_range_from() { - check_name("RangeFrom", r#" + check_name( + "RangeFrom", + r#" //- minicore: range fn f(arr: &[i32]) -> &[i32] { &arr[0.$0.] } -"# +"#, ); } #[test] fn goto_def_range_inclusive() { - check_name("RangeInclusive", r#" + check_name( + "RangeInclusive", + r#" //- minicore: range let x = 0.$0.=1; -"# +"#, ); } #[test] fn goto_def_range_full() { - check_name("RangeFull", r#" + check_name( + "RangeFull", + r#" //- minicore: range fn f(arr: &[i32]) -> &[i32] { &arr[.$0.] } -"# +"#, ); } #[test] fn goto_def_range_to() { - check_name("RangeTo", r#" + check_name( + "RangeTo", + r#" //- minicore: range fn f(arr: &[i32]) -> &[i32] { &arr[.$0.10] } -"# +"#, ); } #[test] fn goto_def_range_to_inclusive() { - check_name("RangeToInclusive", r#" + check_name( + "RangeToInclusive", + r#" //- minicore: range fn f(arr: &[i32]) -> &[i32] { &arr[.$0.=10] } -"# +"#, ); } From 5b12d906bb66d308fb3e94d6d79e076fa87c7f7c Mon Sep 17 00:00:00 2001 From: Slanterns Date: Tue, 22 Oct 2024 01:08:15 -0700 Subject: [PATCH 093/366] optimize `Rc::default` --- library/alloc/src/rc.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index e98ae7c31ad0..582d850e14b6 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -2312,7 +2312,16 @@ impl Default for Rc { /// ``` #[inline] fn default() -> Rc { - Rc::new(Default::default()) + unsafe { + Self::from_inner( + Box::leak(Box::write(Box::new_uninit(), RcInner { + strong: Cell::new(1), + weak: Cell::new(1), + value: T::default(), + })) + .into(), + ) + } } } From 3e02349076ddb68cc694b3555c73113c1983edb8 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 10:50:23 +0200 Subject: [PATCH 094/366] Fix status bar messagen not being marked markdown --- src/tools/rust-analyzer/editors/code/src/ctx.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/editors/code/src/ctx.ts b/src/tools/rust-analyzer/editors/code/src/ctx.ts index 0f2a758db427..234fe6ab0247 100644 --- a/src/tools/rust-analyzer/editors/code/src/ctx.ts +++ b/src/tools/rust-analyzer/editors/code/src/ctx.ts @@ -446,7 +446,7 @@ export class Ctx implements RustAnalyzerExtensionApi { return; } if (status.message) { - statusBar.tooltip.appendText(status.message); + statusBar.tooltip.appendMarkdown(status.message); } if (statusBar.tooltip.value) { statusBar.tooltip.appendMarkdown("\n\n---\n\n"); From 5e3561ea065c73dc38ca92b5095fc9e6f43e4eaa Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 10:50:23 +0200 Subject: [PATCH 095/366] Cleanup file structure proto handling --- .../crates/rust-analyzer/src/handlers/request.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs index a9f8ac3a80a6..998b3b49012c 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs @@ -489,12 +489,12 @@ pub(crate) fn handle_document_symbol( tags.push(SymbolTag::DEPRECATED) }; - #[allow(deprecated)] let doc_symbol = lsp_types::DocumentSymbol { name: symbol.label, detail: symbol.detail, kind: to_proto::structure_node_kind(symbol.kind), tags: Some(tags), + #[allow(deprecated)] deprecated: Some(symbol.deprecated), range: to_proto::range(&line_index, symbol.node_range), selection_range: to_proto::range(&line_index, symbol.navigation_range), @@ -539,18 +539,11 @@ pub(crate) fn handle_document_symbol( url: &Url, res: &mut Vec, ) { - let mut tags = Vec::new(); - - #[allow(deprecated)] - if let Some(true) = symbol.deprecated { - tags.push(SymbolTag::DEPRECATED) - } - - #[allow(deprecated)] res.push(SymbolInformation { name: symbol.name.clone(), kind: symbol.kind, - tags: Some(tags), + tags: symbol.tags.clone(), + #[allow(deprecated)] deprecated: symbol.deprecated, location: Location::new(url.clone(), symbol.range), container_name, From 7782401c520ab1e744dbcf58d0f0254672da9026 Mon Sep 17 00:00:00 2001 From: Slanterns Date: Tue, 22 Oct 2024 01:33:22 -0700 Subject: [PATCH 096/366] add codegen test --- tests/codegen/placement-new.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/codegen/placement-new.rs b/tests/codegen/placement-new.rs index edb25df5eb4d..0ec2b6a6f20e 100644 --- a/tests/codegen/placement-new.rs +++ b/tests/codegen/placement-new.rs @@ -1,9 +1,11 @@ //@ compile-flags: -O +//@ compile-flags: -Zmerge-functions=disabled #![crate_type = "lib"] // Test to check that types with "complex" destructors, but trivial `Default` impls // are constructed directly into the allocation in `Box::default` and `Arc::default`. +use std::rc::Rc; use std::sync::Arc; // CHECK-LABEL: @box_default_inplace @@ -16,6 +18,16 @@ pub fn box_default_inplace() -> Box<(String, String)> { Box::default() } +// CHECK-LABEL: @rc_default_inplace +#[no_mangle] +pub fn rc_default_inplace() -> Rc<(String, String)> { + // CHECK-NOT: alloca + // CHECK: [[RC:%.*]] = {{.*}}call {{.*}}__rust_alloc( + // CHECK-NOT: call void @llvm.memcpy + // CHECK: ret ptr [[RC]] + Rc::default() +} + // CHECK-LABEL: @arc_default_inplace #[no_mangle] pub fn arc_default_inplace() -> Arc<(String, String)> { From 0a963ab2da139b177ef1e7f09efed7e4e1e8e930 Mon Sep 17 00:00:00 2001 From: Slanterns Date: Tue, 22 Oct 2024 01:37:13 -0700 Subject: [PATCH 097/366] refactor `Arc::default` --- library/alloc/src/sync.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index acbc325a5141..13677245e98c 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -3447,13 +3447,16 @@ impl Default for Arc { /// assert_eq!(*x, 0); /// ``` fn default() -> Arc { - let x = Box::into_raw(Box::write(Box::new_uninit(), ArcInner { - strong: atomic::AtomicUsize::new(1), - weak: atomic::AtomicUsize::new(1), - data: T::default(), - })); - // SAFETY: `Box::into_raw` consumes the `Box` and never returns null - unsafe { Self::from_inner(NonNull::new_unchecked(x)) } + unsafe { + Self::from_inner( + Box::leak(Box::write(Box::new_uninit(), ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: T::default(), + })) + .into(), + ) + } } } From ec4b9e090123d3bd4642a9aaab4837390836a936 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Wed, 16 Oct 2024 16:42:09 +0200 Subject: [PATCH 098/366] tests: Add `lsif_contains_generated_constant` test --- src/tools/rust-analyzer/.gitignore | 3 +- .../crates/rust-analyzer/src/bin/main.rs | 4 +- .../crates/rust-analyzer/src/cli/lsif.rs | 35 +++-- .../rust-analyzer/tests/slow-tests/cli.rs | 131 ++++++++++++++++++ .../rust-analyzer/tests/slow-tests/main.rs | 1 + .../rust-analyzer/tests/slow-tests/support.rs | 42 ++++++ 6 files changed, 199 insertions(+), 17 deletions(-) create mode 100644 src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/cli.rs diff --git a/src/tools/rust-analyzer/.gitignore b/src/tools/rust-analyzer/.gitignore index 68c87a6b1ed4..c4470a45078a 100644 --- a/src/tools/rust-analyzer/.gitignore +++ b/src/tools/rust-analyzer/.gitignore @@ -1,6 +1,5 @@ -/target/ +target/ /dist/ -crates/*/target **/*.rs.bk **/*.rs.pending-snap .idea/* diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs index ecc8333503e2..e872585c5717 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs @@ -85,7 +85,9 @@ fn actual_main() -> anyhow::Result { flags::RustAnalyzerCmd::UnresolvedReferences(cmd) => cmd.run()?, flags::RustAnalyzerCmd::Ssr(cmd) => cmd.run()?, flags::RustAnalyzerCmd::Search(cmd) => cmd.run()?, - flags::RustAnalyzerCmd::Lsif(cmd) => cmd.run()?, + flags::RustAnalyzerCmd::Lsif(cmd) => { + cmd.run(&mut std::io::stdout(), Some(project_model::RustLibSource::Discover))? + } flags::RustAnalyzerCmd::Scip(cmd) => cmd.run()?, flags::RustAnalyzerCmd::RunTests(cmd) => cmd.run()?, flags::RustAnalyzerCmd::RustcTests(cmd) => cmd.run()?, diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/lsif.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/lsif.rs index ca8acf57bff6..33c4f31fbee4 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/lsif.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/lsif.rs @@ -12,6 +12,7 @@ use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice}; use lsp_types::lsif; use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace, RustLibSource}; use rustc_hash::FxHashMap; +use stdx::format_to; use vfs::{AbsPathBuf, Vfs}; use crate::{ @@ -21,7 +22,7 @@ use crate::{ version::version, }; -struct LsifManager<'a> { +struct LsifManager<'a, 'w> { count: i32, token_map: FxHashMap, range_map: FxHashMap, @@ -30,6 +31,7 @@ struct LsifManager<'a> { analysis: &'a Analysis, db: &'a RootDatabase, vfs: &'a Vfs, + out: &'w mut dyn std::io::Write, } #[derive(Clone, Copy)] @@ -41,8 +43,13 @@ impl From for lsp_types::NumberOrString { } } -impl LsifManager<'_> { - fn new<'a>(analysis: &'a Analysis, db: &'a RootDatabase, vfs: &'a Vfs) -> LsifManager<'a> { +impl LsifManager<'_, '_> { + fn new<'a, 'w>( + analysis: &'a Analysis, + db: &'a RootDatabase, + vfs: &'a Vfs, + out: &'w mut dyn std::io::Write, + ) -> LsifManager<'a, 'w> { LsifManager { count: 0, token_map: FxHashMap::default(), @@ -52,6 +59,7 @@ impl LsifManager<'_> { analysis, db, vfs, + out, } } @@ -70,9 +78,8 @@ impl LsifManager<'_> { self.add(lsif::Element::Edge(edge)) } - // FIXME: support file in addition to stdout here - fn emit(&self, data: &str) { - println!("{data}"); + fn emit(&mut self, data: &str) { + format_to!(self.out, "{data}\n"); } fn get_token_id(&mut self, id: TokenId) -> Id { @@ -272,14 +279,14 @@ impl LsifManager<'_> { } impl flags::Lsif { - pub fn run(self) -> anyhow::Result<()> { + pub fn run( + self, + out: &mut dyn std::io::Write, + sysroot: Option, + ) -> anyhow::Result<()> { let now = Instant::now(); - let cargo_config = &CargoConfig { - sysroot: Some(RustLibSource::Discover), - all_targets: true, - set_test: true, - ..Default::default() - }; + let cargo_config = + &CargoConfig { sysroot, all_targets: true, set_test: true, ..Default::default() }; let no_progress = &|_| (); let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: true, @@ -308,7 +315,7 @@ impl flags::Lsif { let si = StaticIndex::compute(&analysis, vendored_libs_config); - let mut lsif = LsifManager::new(&analysis, db, &vfs); + let mut lsif = LsifManager::new(&analysis, db, &vfs, out); lsif.add_vertex(lsif::Vertex::MetaData(lsif::MetaData { version: String::from("0.5.0"), project_root: lsp_types::Url::from_file_path(path).unwrap(), diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/cli.rs b/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/cli.rs new file mode 100644 index 000000000000..fba546669128 --- /dev/null +++ b/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/cli.rs @@ -0,0 +1,131 @@ +use expect_test::expect; +use test_utils::skip_slow_tests; + +use crate::support::Project; + +// If you choose to change the test fixture here, please inform the ferrocene/needy maintainers by +// opening an issue at https://github.com/ferrocene/needy as the tool relies on specific token +// mapping behavior. +#[test] +fn lsif_contains_generated_constant() { + if skip_slow_tests() { + return; + } + + let stdout = Project::with_fixture( + r#" +//- /Cargo.toml +[package] +name = "foo" +version = "0.0.0" + +//- /src/lib.rs +#![allow(unused)] + +macro_rules! generate_const_from_identifier( + ($id:ident) => ( + const _: () = { const $id: &str = "encoded_data"; }; + ) +); + +generate_const_from_identifier!(REQ_001); +mod tests { + use super::*; + generate_const_from_identifier!(REQ_002); +} +"#, + ) + .root("foo") + .run_lsif(); + let n = stdout.find(r#"{"id":2,"#).unwrap(); + // the first 2 entries contain paths that are not stable + let stdout = &stdout[n..]; + expect![[r#" + {"id":2,"type":"vertex","label":"foldingRangeResult","result":[{"startLine":2,"startCharacter":43,"endLine":6,"endCharacter":1},{"startLine":3,"startCharacter":19,"endLine":5,"endCharacter":5},{"startLine":9,"startCharacter":10,"endLine":12,"endCharacter":1}]} + {"id":3,"type":"edge","label":"textDocument/foldingRange","inV":2,"outV":1} + {"id":4,"type":"vertex","label":"range","start":{"line":0,"character":3},"end":{"line":0,"character":8}} + {"id":5,"type":"vertex","label":"resultSet"} + {"id":6,"type":"edge","label":"next","inV":5,"outV":4} + {"id":7,"type":"vertex","label":"range","start":{"line":2,"character":13},"end":{"line":2,"character":43}} + {"id":8,"type":"vertex","label":"resultSet"} + {"id":9,"type":"edge","label":"next","inV":8,"outV":7} + {"id":10,"type":"vertex","label":"range","start":{"line":8,"character":0},"end":{"line":8,"character":30}} + {"id":11,"type":"edge","label":"next","inV":8,"outV":10} + {"id":12,"type":"vertex","label":"range","start":{"line":8,"character":32},"end":{"line":8,"character":39}} + {"id":13,"type":"vertex","label":"resultSet"} + {"id":14,"type":"edge","label":"next","inV":13,"outV":12} + {"id":15,"type":"vertex","label":"range","start":{"line":9,"character":4},"end":{"line":9,"character":9}} + {"id":16,"type":"vertex","label":"resultSet"} + {"id":17,"type":"edge","label":"next","inV":16,"outV":15} + {"id":18,"type":"vertex","label":"range","start":{"line":10,"character":8},"end":{"line":10,"character":13}} + {"id":19,"type":"vertex","label":"resultSet"} + {"id":20,"type":"edge","label":"next","inV":19,"outV":18} + {"id":21,"type":"vertex","label":"range","start":{"line":11,"character":4},"end":{"line":11,"character":34}} + {"id":22,"type":"edge","label":"next","inV":8,"outV":21} + {"id":23,"type":"vertex","label":"range","start":{"line":11,"character":36},"end":{"line":11,"character":43}} + {"id":24,"type":"vertex","label":"resultSet"} + {"id":25,"type":"edge","label":"next","inV":24,"outV":23} + {"id":26,"type":"edge","label":"contains","inVs":[4,7,10,12,15,18,21,23],"outV":1} + {"id":27,"type":"vertex","label":"hoverResult","result":{"contents":{"kind":"markdown","value":"\n```rust\n#[allow]\n```\n\n---\n\nValid forms are:\n\n* \\#\\[allow(lint1, lint2, ..., /\\*opt\\*/ reason = \"...\")\\]"}}} + {"id":28,"type":"edge","label":"textDocument/hover","inV":27,"outV":5} + {"id":29,"type":"vertex","label":"referenceResult"} + {"id":30,"type":"edge","label":"textDocument/references","inV":29,"outV":5} + {"id":31,"type":"edge","label":"item","document":1,"property":"references","inVs":[4],"outV":29} + {"id":32,"type":"vertex","label":"hoverResult","result":{"contents":{"kind":"markdown","value":"\n```rust\nfoo\n```\n\n```rust\nmacro_rules! generate_const_from_identifier\n```"}}} + {"id":33,"type":"edge","label":"textDocument/hover","inV":32,"outV":8} + {"id":34,"type":"vertex","label":"packageInformation","name":"foo","manager":"cargo","version":"0.0.0"} + {"id":35,"type":"vertex","label":"moniker","scheme":"rust-analyzer","identifier":"foo::generate_const_from_identifier","unique":"scheme","kind":"export"} + {"id":36,"type":"edge","label":"packageInformation","inV":34,"outV":35} + {"id":37,"type":"edge","label":"moniker","inV":35,"outV":8} + {"id":38,"type":"vertex","label":"definitionResult"} + {"id":39,"type":"edge","label":"item","document":1,"inVs":[7],"outV":38} + {"id":40,"type":"edge","label":"textDocument/definition","inV":38,"outV":8} + {"id":41,"type":"vertex","label":"referenceResult"} + {"id":42,"type":"edge","label":"textDocument/references","inV":41,"outV":8} + {"id":43,"type":"edge","label":"item","document":1,"property":"definitions","inVs":[7],"outV":41} + {"id":44,"type":"edge","label":"item","document":1,"property":"references","inVs":[10,21],"outV":41} + {"id":45,"type":"vertex","label":"hoverResult","result":{"contents":{"kind":"markdown","value":"\n```rust\nfoo\n```\n\n```rust\nconst REQ_001: &str = \"encoded_data\"\n```"}}} + {"id":46,"type":"edge","label":"textDocument/hover","inV":45,"outV":13} + {"id":47,"type":"vertex","label":"moniker","scheme":"rust-analyzer","identifier":"foo::REQ_001","unique":"scheme","kind":"export"} + {"id":48,"type":"edge","label":"packageInformation","inV":34,"outV":47} + {"id":49,"type":"edge","label":"moniker","inV":47,"outV":13} + {"id":50,"type":"vertex","label":"definitionResult"} + {"id":51,"type":"edge","label":"item","document":1,"inVs":[12],"outV":50} + {"id":52,"type":"edge","label":"textDocument/definition","inV":50,"outV":13} + {"id":53,"type":"vertex","label":"referenceResult"} + {"id":54,"type":"edge","label":"textDocument/references","inV":53,"outV":13} + {"id":55,"type":"edge","label":"item","document":1,"property":"definitions","inVs":[12],"outV":53} + {"id":56,"type":"vertex","label":"hoverResult","result":{"contents":{"kind":"markdown","value":"\n```rust\nfoo\n```\n\n```rust\nmod tests\n```"}}} + {"id":57,"type":"edge","label":"textDocument/hover","inV":56,"outV":16} + {"id":58,"type":"vertex","label":"moniker","scheme":"rust-analyzer","identifier":"foo::tests","unique":"scheme","kind":"export"} + {"id":59,"type":"edge","label":"packageInformation","inV":34,"outV":58} + {"id":60,"type":"edge","label":"moniker","inV":58,"outV":16} + {"id":61,"type":"vertex","label":"definitionResult"} + {"id":62,"type":"edge","label":"item","document":1,"inVs":[15],"outV":61} + {"id":63,"type":"edge","label":"textDocument/definition","inV":61,"outV":16} + {"id":64,"type":"vertex","label":"referenceResult"} + {"id":65,"type":"edge","label":"textDocument/references","inV":64,"outV":16} + {"id":66,"type":"edge","label":"item","document":1,"property":"definitions","inVs":[15],"outV":64} + {"id":67,"type":"vertex","label":"hoverResult","result":{"contents":{"kind":"markdown","value":"\n```rust\nextern crate foo\n```"}}} + {"id":68,"type":"edge","label":"textDocument/hover","inV":67,"outV":19} + {"id":69,"type":"vertex","label":"definitionResult"} + {"id":70,"type":"vertex","label":"range","start":{"line":0,"character":0},"end":{"line":13,"character":0}} + {"id":71,"type":"edge","label":"contains","inVs":[70],"outV":1} + {"id":72,"type":"edge","label":"item","document":1,"inVs":[70],"outV":69} + {"id":73,"type":"edge","label":"textDocument/definition","inV":69,"outV":19} + {"id":74,"type":"vertex","label":"referenceResult"} + {"id":75,"type":"edge","label":"textDocument/references","inV":74,"outV":19} + {"id":76,"type":"edge","label":"item","document":1,"property":"references","inVs":[18],"outV":74} + {"id":77,"type":"vertex","label":"hoverResult","result":{"contents":{"kind":"markdown","value":"\n```rust\nfoo::tests\n```\n\n```rust\nconst REQ_002: &str = \"encoded_data\"\n```"}}} + {"id":78,"type":"edge","label":"textDocument/hover","inV":77,"outV":24} + {"id":79,"type":"vertex","label":"moniker","scheme":"rust-analyzer","identifier":"foo::tests::REQ_002","unique":"scheme","kind":"export"} + {"id":80,"type":"edge","label":"packageInformation","inV":34,"outV":79} + {"id":81,"type":"edge","label":"moniker","inV":79,"outV":24} + {"id":82,"type":"vertex","label":"definitionResult"} + {"id":83,"type":"edge","label":"item","document":1,"inVs":[23],"outV":82} + {"id":84,"type":"edge","label":"textDocument/definition","inV":82,"outV":24} + {"id":85,"type":"vertex","label":"referenceResult"} + {"id":86,"type":"edge","label":"textDocument/references","inV":85,"outV":24} + {"id":87,"type":"edge","label":"item","document":1,"property":"definitions","inVs":[23],"outV":85} + "#]].assert_eq(stdout); +} diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/main.rs b/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/main.rs index 54cd27f4b3bc..97c76bf8d173 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/main.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/main.rs @@ -10,6 +10,7 @@ #![allow(clippy::disallowed_types)] +mod cli; mod ratoml; mod support; mod testdir; diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/support.rs b/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/support.rs index 18aface632d1..78572e37a9b1 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/support.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/support.rs @@ -6,11 +6,13 @@ use std::{ }; use crossbeam_channel::{after, select, Receiver}; +use itertools::Itertools; use lsp_server::{Connection, Message, Notification, Request}; use lsp_types::{notification::Exit, request::Shutdown, TextDocumentIdentifier, Url}; use parking_lot::{Mutex, MutexGuard}; use paths::{Utf8Path, Utf8PathBuf}; use rust_analyzer::{ + cli::flags, config::{Config, ConfigChange, ConfigErrors}, lsp, main_loop, }; @@ -84,6 +86,46 @@ impl Project<'_> { self } + pub(crate) fn run_lsif(self) -> String { + let tmp_dir = self.tmp_dir.unwrap_or_else(|| { + if self.root_dir_contains_symlink { + TestDir::new_symlink() + } else { + TestDir::new() + } + }); + + let FixtureWithProjectMeta { + fixture, + mini_core, + proc_macro_names, + toolchain, + target_data_layout: _, + } = FixtureWithProjectMeta::parse(self.fixture); + assert!(proc_macro_names.is_empty()); + assert!(mini_core.is_none()); + assert!(toolchain.is_none()); + + for entry in fixture { + let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path.as_path(), entry.text.as_bytes()).unwrap(); + } + + let tmp_dir_path = AbsPathBuf::assert(tmp_dir.path().to_path_buf()); + let mut buf = Vec::new(); + flags::Lsif::run( + flags::Lsif { + path: tmp_dir_path.join(self.roots.iter().exactly_one().unwrap()).into(), + exclude_vendored_libraries: false, + }, + &mut buf, + None, + ) + .unwrap(); + String::from_utf8(buf).unwrap() + } + pub(crate) fn server(self) -> Server { static CONFIG_DIR_LOCK: Mutex<()> = Mutex::new(()); let tmp_dir = self.tmp_dir.unwrap_or_else(|| { From 7f4dd9bb815182a1b60242d82890f9b0b3273c4b Mon Sep 17 00:00:00 2001 From: Zalathar Date: Tue, 22 Oct 2024 13:31:54 +1100 Subject: [PATCH 099/366] Move `cmp_in_dominator_order` out of graph dominator computation Dominator-order information is only needed for coverage graphs, and is easy enough to collect by just traversing the graph again. This avoids wasted work when computing graph dominators for any other purpose. --- .../src/graph/dominators/mod.rs | 23 +---------------- .../rustc_mir_transform/src/coverage/graph.rs | 25 +++++++++++++++++-- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index 7cb013fdbd83..85b030c1a485 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -9,8 +9,6 @@ //! Thomas Lengauer and Robert Endre Tarjan. //! -use std::cmp::Ordering; - use rustc_index::{Idx, IndexSlice, IndexVec}; use super::ControlFlowGraph; @@ -64,9 +62,6 @@ fn is_small_path_graph(g: &G) -> bool { } fn dominators_impl(graph: &G) -> Inner { - // compute the post order index (rank) for each node - let mut post_order_rank = IndexVec::from_elem_n(0, graph.num_nodes()); - // We allocate capacity for the full set of nodes, because most of the time // most of the nodes *are* reachable. let mut parent: IndexVec = @@ -83,12 +78,10 @@ fn dominators_impl(graph: &G) -> Inner { pre_order_to_real.push(graph.start_node()); parent.push(PreorderIndex::ZERO); // the parent of the root node is the root for now. real_to_pre_order[graph.start_node()] = Some(PreorderIndex::ZERO); - let mut post_order_idx = 0; // Traverse the graph, collecting a number of things: // // * Preorder mapping (to it, and back to the actual ordering) - // * Postorder mapping (used exclusively for `cmp_in_dominator_order` on the final product) // * Parents for each vertex in the preorder tree // // These are all done here rather than through one of the 'standard' @@ -104,8 +97,6 @@ fn dominators_impl(graph: &G) -> Inner { continue 'recurse; } } - post_order_rank[pre_order_to_real[frame.pre_order_idx]] = post_order_idx; - post_order_idx += 1; stack.pop(); } @@ -282,7 +273,7 @@ fn dominators_impl(graph: &G) -> Inner { let time = compute_access_time(start_node, &immediate_dominators); - Inner { post_order_rank, immediate_dominators, time } + Inner { immediate_dominators, time } } /// Evaluate the link-eval virtual forest, providing the currently minimum semi @@ -348,7 +339,6 @@ fn compress( /// Tracks the list of dominators for each node. #[derive(Clone, Debug)] struct Inner { - post_order_rank: IndexVec, // Even though we track only the immediate dominator of each node, it's // possible to get its full list of dominators by looking up the dominator // of each dominator. @@ -379,17 +369,6 @@ impl Dominators { } } - /// Provide deterministic ordering of nodes such that, if any two nodes have a dominator - /// relationship, the dominator will always precede the dominated. (The relative ordering - /// of two unrelated nodes will also be consistent, but otherwise the order has no - /// meaning.) This method cannot be used to determine if either Node dominates the other. - pub fn cmp_in_dominator_order(&self, lhs: Node, rhs: Node) -> Ordering { - match &self.kind { - Kind::Path => lhs.index().cmp(&rhs.index()), - Kind::General(g) => g.post_order_rank[rhs].cmp(&g.post_order_rank[lhs]), - } - } - /// Returns true if `a` dominates `b`. /// /// # Panics diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index d839f46cfbd5..930fa129ef2a 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -21,6 +21,10 @@ pub(crate) struct CoverageGraph { pub(crate) successors: IndexVec>, pub(crate) predecessors: IndexVec>, dominators: Option>, + /// Allows nodes to be compared in some total order such that _if_ + /// `a` dominates `b`, then `a < b`. If neither node dominates the other, + /// their relative order is consistent but arbitrary. + dominator_order_rank: IndexVec, } impl CoverageGraph { @@ -54,10 +58,27 @@ impl CoverageGraph { } } - let mut this = Self { bcbs, bb_to_bcb, successors, predecessors, dominators: None }; + let num_nodes = bcbs.len(); + let mut this = Self { + bcbs, + bb_to_bcb, + successors, + predecessors, + dominators: None, + dominator_order_rank: IndexVec::from_elem_n(0, num_nodes), + }; + assert_eq!(num_nodes, this.num_nodes()); this.dominators = Some(dominators::dominators(&this)); + // The dominator rank of each node is just its index in a reverse-postorder traversal. + let reverse_post_order = graph::iterate::reverse_post_order(&this, this.start_node()); + // The coverage graph is created by traversal, so all nodes are reachable. + assert_eq!(reverse_post_order.len(), this.num_nodes()); + for (rank, bcb) in (0u32..).zip(reverse_post_order) { + this.dominator_order_rank[bcb] = rank; + } + // The coverage graph's entry-point node (bcb0) always starts with bb0, // which never has predecessors. Any other blocks merged into bcb0 can't // have multiple (coverage-relevant) predecessors, so bcb0 always has @@ -162,7 +183,7 @@ impl CoverageGraph { a: BasicCoverageBlock, b: BasicCoverageBlock, ) -> Ordering { - self.dominators.as_ref().unwrap().cmp_in_dominator_order(a, b) + self.dominator_order_rank[a].cmp(&self.dominator_order_rank[b]) } /// Returns the source of this node's sole in-edge, if it has exactly one. From 76368b805da46434ca4a10ae50a5936801fe0c04 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 11:02:41 +0200 Subject: [PATCH 100/366] Fix new nightly lints --- .../rust-analyzer/crates/hir-def/src/lower.rs | 2 +- .../crates/hir-expand/src/hygiene.rs | 2 +- .../crates/hir-ty/src/autoderef.rs | 2 +- .../crates/hir-ty/src/chalk_db.rs | 2 +- .../diagnostics/match_check/pat_analysis.rs | 2 +- .../crates/hir-ty/src/dyn_compatibility.rs | 2 +- .../rust-analyzer/crates/hir-ty/src/infer.rs | 2 +- .../rust-analyzer/crates/hir-ty/src/mir.rs | 37 ++++++++++++------- .../crates/hir-ty/src/mir/borrowck.rs | 12 ++++++ .../crates/hir-ty/src/mir/eval.rs | 24 ++++++------ .../crates/hir-ty/src/mir/monomorphization.rs | 4 ++ .../crates/hir-ty/src/mir/pretty.rs | 4 ++ .../rust-analyzer/crates/hir-ty/src/utils.rs | 2 +- .../rust-analyzer/crates/hir/src/semantics.rs | 2 +- .../crates/parser/src/grammar/patterns.rs | 5 +-- .../crates/proc-macro-api/src/msg/flat.rs | 4 +- .../crates/ra-salsa/src/derived/slot.rs | 2 +- .../crates/ra-salsa/src/derived_lru/slot.rs | 2 +- .../crates/ra-salsa/src/interned.rs | 2 +- .../rust-analyzer/crates/ra-salsa/src/lib.rs | 6 +-- .../rust-analyzer/src/handlers/request.rs | 4 +- .../crates/rust-analyzer/src/tracing/hprof.rs | 2 +- .../rust-analyzer/crates/tt/src/buffer.rs | 2 +- src/tools/rust-analyzer/xtask/src/codegen.rs | 4 +- 24 files changed, 81 insertions(+), 51 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/lower.rs index e4786a1dd40e..8e521460c358 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lower.rs @@ -34,7 +34,7 @@ impl<'a> OuterImplTraitGuard<'a> { } } -impl<'a> Drop for OuterImplTraitGuard<'a> { +impl Drop for OuterImplTraitGuard<'_> { fn drop(&mut self) { self.ctx.outer_impl_trait.replace(self.old); } diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/hygiene.rs b/src/tools/rust-analyzer/crates/hir-expand/src/hygiene.rs index a81911891577..f48de807c28c 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/hygiene.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/hygiene.rs @@ -227,7 +227,7 @@ pub(crate) fn dump_syntax_contexts(db: &dyn ExpandDatabase) -> String { &'a SyntaxContextData, ); - impl<'a> std::fmt::Debug for SyntaxContextDebug<'a> { + impl std::fmt::Debug for SyntaxContextDebug<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fancy_debug(self.2, self.1, self.0, f) } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs b/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs index 7a3846df40ee..2b5342314a65 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs @@ -114,7 +114,7 @@ impl<'table, 'db> Autoderef<'table, 'db, usize> { } #[allow(private_bounds)] -impl<'table, 'db, T: TrackAutoderefSteps> Autoderef<'table, 'db, T> { +impl Autoderef<'_, '_, T> { pub(crate) fn step_count(&self) -> usize { self.steps.len() } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs b/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs index f7bacbd49b33..8a616956de23 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs @@ -521,7 +521,7 @@ impl chalk_solve::RustIrDatabase for ChalkContext<'_> { } } -impl<'a> ChalkContext<'a> { +impl ChalkContext<'_> { fn edition(&self) -> Edition { self.db.crate_graph()[self.krate].edition } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs index 1066a28c3ff8..58de19ba81ee 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs @@ -519,7 +519,7 @@ impl<'db> PatCx for MatchCheckCtx<'db> { } } -impl<'db> fmt::Debug for MatchCheckCtx<'db> { +impl fmt::Debug for MatchCheckCtx<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("MatchCheckCtx").finish() } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs b/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs index e0d1758210ec..3d21785a70a3 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs @@ -266,7 +266,7 @@ fn contains_illegal_self_type_reference>( trait_self_param_idx: usize, allow_self_projection: AllowSelfProjection, } - impl<'a> TypeVisitor for IllegalSelfTypeVisitor<'a> { + impl TypeVisitor for IllegalSelfTypeVisitor<'_> { type BreakTy = (); fn as_dyn(&mut self) -> &mut dyn TypeVisitor { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index 88334b492d5a..4f41af0b4e25 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -1022,7 +1022,7 @@ impl<'a> InferenceContext<'a> { non_assocs: FxHashMap, } - impl<'a, 'b> TypeVisitor for TypeAliasImplTraitCollector<'a, 'b> { + impl TypeVisitor for TypeAliasImplTraitCollector<'_, '_> { type BreakTy = (); fn as_dyn(&mut self) -> &mut dyn TypeVisitor { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir.rs index 8e815aabf207..59c583afb2a8 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir.rs @@ -879,7 +879,8 @@ pub enum Rvalue { /// /// **Needs clarification**: Are there weird additional semantics here related to the runtime /// nature of this operation? - //ThreadLocalRef(DefId), + // ThreadLocalRef(DefId), + ThreadLocalRef(std::convert::Infallible), /// Creates a pointer with the indicated mutability to the place. /// @@ -888,7 +889,8 @@ pub enum Rvalue { /// /// Like with references, the semantics of this operation are heavily dependent on the aliasing /// model. - //AddressOf(Mutability, Place), + // AddressOf(Mutability, Place), + AddressOf(std::convert::Infallible), /// Yields the length of the place, as a `usize`. /// @@ -906,19 +908,21 @@ pub enum Rvalue { Cast(CastKind, Operand, Ty), // FIXME link to `pointer::offset` when it hits stable. - // /// * `Offset` has the same semantics as `pointer::offset`, except that the second - // /// parameter may be a `usize` as well. - // /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats, - // /// raw pointers, or function pointers and return a `bool`. The types of the operands must be - // /// matching, up to the usual caveat of the lifetimes in function pointers. - // /// * Left and right shift operations accept signed or unsigned integers not necessarily of the - // /// same type and return a value of the same type as their LHS. Like in Rust, the RHS is - // /// truncated as needed. - // /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching - // /// types and return a value of that type. - // /// * The remaining operations accept signed integers, unsigned integers, or floats with - // /// matching types and return a value of that type. + /// * `Offset` has the same semantics as `pointer::offset`, except that the second + /// parameter may be a `usize` as well. + /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats, + /// raw pointers, or function pointers and return a `bool`. The types of the operands must be + /// matching, up to the usual caveat of the lifetimes in function pointers. + /// * Left and right shift operations accept signed or unsigned integers not necessarily of the + /// same type and return a value of the same type as their LHS. Like in Rust, the RHS is + /// truncated as needed. + /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching + /// types and return a value of that type. + /// * The remaining operations accept signed integers, unsigned integers, or floats with + /// matching types and return a value of that type. //BinaryOp(BinOp, Box<(Operand, Operand)>), + BinaryOp(std::convert::Infallible), + /// Same as `BinaryOp`, but yields `(T, bool)` with a `bool` indicating an error condition. /// /// When overflow checking is disabled and we are generating run-time code, the error condition @@ -937,6 +941,7 @@ pub enum Rvalue { /// Computes a value as described by the operation. //NullaryOp(NullOp, Ty), + NullaryOp(std::convert::Infallible), /// Exactly like `BinaryOp`, but less operands. /// @@ -1095,6 +1100,10 @@ impl MirBody { for_operand(op, &mut f, &mut self.projection_store); } } + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, } } StatementKind::FakeRead(p) | StatementKind::Deinit(p) => { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs index 9830fa1ca7b7..9c86d3b59f6d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs @@ -167,6 +167,10 @@ fn moved_out_of_ref(db: &dyn HirDatabase, body: &MirBody) -> Vec for_operand(op, statement.span); } } + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, }, StatementKind::FakeRead(_) | StatementKind::Deinit(_) @@ -253,6 +257,10 @@ fn partially_moved(db: &dyn HirDatabase, body: &MirBody) -> Vec for_operand(op, statement.span); } } + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, }, StatementKind::FakeRead(_) | StatementKind::Deinit(_) @@ -548,6 +556,10 @@ fn mutability_of_locals( } } Rvalue::ShallowInitBox(_, _) | Rvalue::ShallowInitBoxWithAlloc(_) => (), + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, } if let Rvalue::Ref( BorrowKind::Mut { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs index 0d42617d185c..7580f042adc7 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs @@ -1628,6 +1628,10 @@ impl Evaluator<'_> { } CastKind::FnPtrToPtr => not_supported!("fn ptr to ptr cast"), }, + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, }) } @@ -2703,17 +2707,15 @@ impl Evaluator<'_> { TyKind::Function(_) => { self.exec_fn_pointer(func_data, destination, &args[1..], locals, target_bb, span) } - TyKind::Closure(closure, subst) => { - return self.exec_closure( - *closure, - func_data, - &Substitution::from_iter(Interner, ClosureSubst(subst).parent_subst()), - destination, - &args[1..], - locals, - span, - ); - } + TyKind::Closure(closure, subst) => self.exec_closure( + *closure, + func_data, + &Substitution::from_iter(Interner, ClosureSubst(subst).parent_subst()), + destination, + &args[1..], + locals, + span, + ), _ => { // try to execute the manual impl of `FnTrait` for structs (nightly feature used in std) let arg0 = func; diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/monomorphization.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/monomorphization.rs index 4c6bc376e2b7..92132fa04736 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/monomorphization.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/monomorphization.rs @@ -258,6 +258,10 @@ impl Filler<'_> { | Rvalue::UnaryOp(_, _) | Rvalue::Discriminant(_) | Rvalue::CopyForDeref(_) => (), + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, }, StatementKind::Deinit(_) | StatementKind::FakeRead(_) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/pretty.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/pretty.rs index df56071aa9af..06765a104cbb 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/pretty.rs @@ -459,6 +459,10 @@ impl<'a> MirPrettyCtx<'a> { self.place(p); w!(self, ")"); } + Rvalue::ThreadLocalRef(n) + | Rvalue::AddressOf(n) + | Rvalue::BinaryOp(n) + | Rvalue::NullaryOp(n) => match *n {}, } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs index 620bba2d75c1..98e8feceb063 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs @@ -123,7 +123,7 @@ pub(super) struct ClauseElaborator<'a> { seen: FxHashSet, } -impl<'a> ClauseElaborator<'a> { +impl ClauseElaborator<'_> { fn extend_deduped(&mut self, clauses: impl IntoIterator) { self.stack.extend(clauses.into_iter().filter(|c| self.seen.insert(c.clone()))) } diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index 80908dac5d72..2716a10343b0 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -154,7 +154,7 @@ impl<'db, DB> ops::Deref for Semantics<'db, DB> { } } -impl<'db, DB: HirDatabase> Semantics<'db, DB> { +impl Semantics<'_, DB> { pub fn new(db: &DB) -> Semantics<'_, DB> { let impl_ = SemanticsImpl::new(db); Semantics { db, imp: impl_ } diff --git a/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs b/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs index 882c243b0cd9..3db1a10ca5ce 100644 --- a/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs +++ b/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs @@ -40,9 +40,6 @@ pub(super) fn pattern_top_r(p: &mut Parser<'_>, recovery_set: TokenSet) { pattern_r(p, recovery_set); } -/// Parses a pattern list separated by pipes `|`, with no leading `|`,using the -/// given `recovery_set`. - // test or_pattern // fn main() { // match () { @@ -52,6 +49,8 @@ pub(super) fn pattern_top_r(p: &mut Parser<'_>, recovery_set: TokenSet) { // [_ | _,] => (), // } // } +/// Parses a pattern list separated by pipes `|`, with no leading `|`,using the +/// given `recovery_set`. fn pattern_r(p: &mut Parser<'_>, recovery_set: TokenSet) { let m = p.start(); pattern_single_r(p, recovery_set); diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/msg/flat.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/msg/flat.rs index 88256e98b588..5443a9bd67bb 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-api/src/msg/flat.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/msg/flat.rs @@ -401,7 +401,7 @@ struct Writer<'a, 'span, S: InternableSpan> { text: Vec, } -impl<'a, 'span, S: InternableSpan> Writer<'a, 'span, S> { +impl<'a, S: InternableSpan> Writer<'a, '_, S> { fn write(&mut self, root: &'a tt::Subtree) { self.enqueue(root); while let Some((idx, subtree)) = self.work.pop_front() { @@ -524,7 +524,7 @@ struct Reader<'span, S: InternableSpan> { span_data_table: &'span S::Table, } -impl<'span, S: InternableSpan> Reader<'span, S> { +impl Reader<'_, S> { pub(crate) fn read(self) -> tt::Subtree { let mut res: Vec>> = vec![None; self.subtree.len()]; let read_span = |id| S::span_for_token_id(self.span_data_table, id); diff --git a/src/tools/rust-analyzer/crates/ra-salsa/src/derived/slot.rs b/src/tools/rust-analyzer/crates/ra-salsa/src/derived/slot.rs index de7a39760746..6c5ccba173b9 100644 --- a/src/tools/rust-analyzer/crates/ra-salsa/src/derived/slot.rs +++ b/src/tools/rust-analyzer/crates/ra-salsa/src/derived/slot.rs @@ -616,7 +616,7 @@ Please report this bug to https://github.com/salsa-rs/salsa/issues." } } -impl<'me, Q> Drop for PanicGuard<'me, Q> +impl Drop for PanicGuard<'_, Q> where Q: QueryFunction, Q::Value: Eq, diff --git a/src/tools/rust-analyzer/crates/ra-salsa/src/derived_lru/slot.rs b/src/tools/rust-analyzer/crates/ra-salsa/src/derived_lru/slot.rs index d0e4b5422b5f..ff9cc4eade2c 100644 --- a/src/tools/rust-analyzer/crates/ra-salsa/src/derived_lru/slot.rs +++ b/src/tools/rust-analyzer/crates/ra-salsa/src/derived_lru/slot.rs @@ -666,7 +666,7 @@ Please report this bug to https://github.com/salsa-rs/salsa/issues." } } -impl<'me, Q, MP> Drop for PanicGuard<'me, Q, MP> +impl Drop for PanicGuard<'_, Q, MP> where Q: QueryFunction, MP: MemoizationPolicy, diff --git a/src/tools/rust-analyzer/crates/ra-salsa/src/interned.rs b/src/tools/rust-analyzer/crates/ra-salsa/src/interned.rs index 359662ec6b2f..42c398d697de 100644 --- a/src/tools/rust-analyzer/crates/ra-salsa/src/interned.rs +++ b/src/tools/rust-analyzer/crates/ra-salsa/src/interned.rs @@ -493,7 +493,7 @@ where is_static::>(); } -impl<'me, Q> QueryTable<'me, Q> +impl QueryTable<'_, Q> where Q: Query>, Q::Key: InternValue, diff --git a/src/tools/rust-analyzer/crates/ra-salsa/src/lib.rs b/src/tools/rust-analyzer/crates/ra-salsa/src/lib.rs index 1b327773ec6c..bd1ab6971cb1 100644 --- a/src/tools/rust-analyzer/crates/ra-salsa/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ra-salsa/src/lib.rs @@ -149,7 +149,7 @@ where db: &'me D, } -impl<'me, D: ?Sized> fmt::Debug for EventDebug<'me, D> +impl fmt::Debug for EventDebug<'_, D> where D: plumbing::DatabaseOps, { @@ -242,7 +242,7 @@ where db: &'me D, } -impl<'me, D: ?Sized> fmt::Debug for EventKindDebug<'me, D> +impl fmt::Debug for EventKindDebug<'_, D> where D: plumbing::DatabaseOps, { @@ -729,7 +729,7 @@ impl Cycle { db: &'me dyn Database, } - impl<'me> std::fmt::Debug for UnexpectedCycleDebug<'me> { + impl std::fmt::Debug for UnexpectedCycleDebug<'_> { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fmt.debug_struct("UnexpectedCycle") .field("all_participants", &self.c.all_participants(self.db)) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs index 998b3b49012c..b4e6e4c29373 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs @@ -489,12 +489,12 @@ pub(crate) fn handle_document_symbol( tags.push(SymbolTag::DEPRECATED) }; + #[allow(deprecated)] let doc_symbol = lsp_types::DocumentSymbol { name: symbol.label, detail: symbol.detail, kind: to_proto::structure_node_kind(symbol.kind), tags: Some(tags), - #[allow(deprecated)] deprecated: Some(symbol.deprecated), range: to_proto::range(&line_index, symbol.node_range), selection_range: to_proto::range(&line_index, symbol.navigation_range), @@ -539,11 +539,11 @@ pub(crate) fn handle_document_symbol( url: &Url, res: &mut Vec, ) { + #[allow(deprecated)] res.push(SymbolInformation { name: symbol.name.clone(), kind: symbol.kind, tags: symbol.tags.clone(), - #[allow(deprecated)] deprecated: symbol.deprecated, location: Location::new(url.clone(), symbol.range), container_name, diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/hprof.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/hprof.rs index cad92962f348..d466acef0115 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/hprof.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/hprof.rs @@ -120,7 +120,7 @@ pub struct DataVisitor<'a> { string: &'a mut String, } -impl<'a> Visit for DataVisitor<'a> { +impl Visit for DataVisitor<'_> { fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { write!(self.string, "{} = {:?} ", field.name(), value).unwrap(); } diff --git a/src/tools/rust-analyzer/crates/tt/src/buffer.rs b/src/tools/rust-analyzer/crates/tt/src/buffer.rs index 1319739371ff..acb7e2d6c51a 100644 --- a/src/tools/rust-analyzer/crates/tt/src/buffer.rs +++ b/src/tools/rust-analyzer/crates/tt/src/buffer.rs @@ -134,7 +134,7 @@ pub enum TokenTreeRef<'a, Span> { Leaf(&'a Leaf, &'a TokenTree), } -impl<'a, Span: Copy> TokenTreeRef<'a, Span> { +impl TokenTreeRef<'_, Span> { pub fn span(&self) -> Span { match self { TokenTreeRef::Subtree(subtree, _) => subtree.delimiter.open, diff --git a/src/tools/rust-analyzer/xtask/src/codegen.rs b/src/tools/rust-analyzer/xtask/src/codegen.rs index 4c7b07c5e02c..bc04b9474f26 100644 --- a/src/tools/rust-analyzer/xtask/src/codegen.rs +++ b/src/tools/rust-analyzer/xtask/src/codegen.rs @@ -79,7 +79,7 @@ impl CommentBlock { let mut block = dummy_block.clone(); for (line_num, line) in lines.enumerate() { match line.strip_prefix("//") { - Some(mut contents) => { + Some(mut contents) if !contents.starts_with('/') => { if let Some('/' | '!') = contents.chars().next() { contents = &contents[1..]; block.is_doc = true; @@ -89,7 +89,7 @@ impl CommentBlock { } block.contents.push(contents.to_owned()); } - None => { + _ => { if !block.contents.is_empty() { let block = mem::replace(&mut block, dummy_block.clone()); res.push(block); From 21636ac046415c56f47fde71863ebc1b11cb14e4 Mon Sep 17 00:00:00 2001 From: Duncan Proctor Date: Tue, 22 Oct 2024 06:20:16 -0400 Subject: [PATCH 101/366] resolve range patterns to the their struct types --- .../rust-analyzer/crates/hir/src/semantics.rs | 8 ++ .../crates/hir/src/source_analyzer.rs | 20 ++++ .../rust-analyzer/crates/ide-db/src/defs.rs | 12 +- .../crates/ide/src/goto_definition.rs | 109 +++++++++++++++++- 4 files changed, 141 insertions(+), 8 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index fd3172a61a85..28f1895fbf09 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -203,6 +203,10 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> { self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast)) } + pub fn resolve_range_pat(&self, range_pat: &ast::RangePat) -> Option { + self.imp.resolve_range_pat(range_pat).map(Struct::from) + } + pub fn resolve_range_expr(&self, range_expr: &ast::RangeExpr) -> Option { self.imp.resolve_range_expr(range_expr).map(Struct::from) } @@ -1361,6 +1365,10 @@ impl<'db> SemanticsImpl<'db> { self.analyze(call.syntax())?.resolve_method_call_fallback(self.db, call) } + fn resolve_range_pat(&self, range_pat: &ast::RangePat) -> Option { + self.analyze(range_pat.syntax())?.resolve_range_pat(self.db, range_pat) + } + fn resolve_range_expr(&self, range_expr: &ast::RangeExpr) -> Option { self.analyze(range_expr.syntax())?.resolve_range_expr(self.db, range_expr) } diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index be0e57b0b1dd..1e28990f43ab 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -348,6 +348,26 @@ impl SourceAnalyzer { } } + pub(crate) fn resolve_range_pat( + &self, + db: &dyn HirDatabase, + range_pat: &ast::RangePat, + ) -> Option { + let path: ModPath = match (range_pat.op_kind()?, range_pat.start(), range_pat.end()) { + (RangeOp::Exclusive, None, Some(_)) => path![core::ops::RangeTo], + (RangeOp::Exclusive, Some(_), None) => path![core::ops::RangeFrom], + (RangeOp::Exclusive, Some(_), Some(_)) => path![core::ops::Range], + (RangeOp::Inclusive, None, Some(_)) => path![core::ops::RangeToInclusive], + (RangeOp::Inclusive, Some(_), Some(_)) => path![core::ops::RangeInclusive], + + (RangeOp::Exclusive, None, None) => return None, + (RangeOp::Inclusive, None, None) => return None, + (RangeOp::Inclusive, Some(_), None) => return None, + }; + let s = self.resolver.resolve_known_struct(db.upcast(), &path); + return s; + } + pub(crate) fn resolve_range_expr( &self, db: &dyn HirDatabase, diff --git a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs index a253e086f81a..48daabbf3729 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs @@ -318,7 +318,8 @@ impl IdentClass { .map(IdentClass::NameClass) .or_else(|| NameRefClass::classify_lifetime(sema, &lifetime).map(IdentClass::NameRefClass)) }, - ast::RangeExpr(range_expr) => OperatorClass::classify_range(sema, &range_expr).map(IdentClass::Operator), + ast::RangePat(range_pat) => OperatorClass::classify_range_pat(sema, &range_pat).map(IdentClass::Operator), + ast::RangeExpr(range_expr) => OperatorClass::classify_range_expr(sema, &range_expr).map(IdentClass::Operator), ast::AwaitExpr(await_expr) => OperatorClass::classify_await(sema, &await_expr).map(IdentClass::Operator), ast::BinExpr(bin_expr) => OperatorClass::classify_bin(sema, &bin_expr).map(IdentClass::Operator), ast::IndexExpr(index_expr) => OperatorClass::classify_index(sema, &index_expr).map(IdentClass::Operator), @@ -558,7 +559,14 @@ pub enum OperatorClass { } impl OperatorClass { - pub fn classify_range( + pub fn classify_range_pat( + sema: &Semantics<'_, RootDatabase>, + range_pat: &ast::RangePat, + ) -> Option { + sema.resolve_range_pat(range_pat).map(OperatorClass::Range) + } + + pub fn classify_range_expr( sema: &Semantics<'_, RootDatabase>, range_expr: &ast::RangeExpr, ) -> Option { diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 5c9ca0bc89af..aa5c8d004199 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -98,6 +98,7 @@ pub(crate) fn goto_definition( return Some(vec![x]); } } + Some( IdentClass::classify_node(sema, &parent)? .definitions() @@ -460,7 +461,103 @@ mod tests { } #[test] - fn goto_def_range() { + fn goto_def_pat_range_to_inclusive() { + check_name( + "RangeToInclusive", + r#" +//- minicore: range +fn f(ch: char) -> bool { + match ch { + ..$0='z' => true, + _ => false + } +} +"# + ); + } + + #[test] + fn goto_def_pat_range_to() { + check_name( + "RangeTo", + r#" +//- minicore: range +fn f(ch: char) -> bool { + match ch { + .$0.'z' => true, + _ => false + } +} +"# + ); + } + + #[test] + fn goto_def_pat_range() { + check_name( + "Range", + r#" +//- minicore: range +fn f(ch: char) -> bool { + match ch { + 'a'.$0.'z' => true, + _ => false + } +} +"# + ); + } + + #[test] + fn goto_def_pat_range_inclusive() { + check_name( + "RangeInclusive", + r#" +//- minicore: range +fn f(ch: char) -> bool { + match ch { + 'a'..$0='z' => true, + _ => false + } +} +"# + ); + } + + #[test] + fn goto_def_pat_range_from() { + check_name( + "RangeFrom", + r#" +//- minicore: range +fn f(ch: char) -> bool { + match ch { + 'a'..$0 => true, + _ => false + } +} +"# + ); + } + + #[test] + fn goto_def_range_pat_inclusive() { + check_name( + "RangeInclusive", + r#" +//- minicore: range +fn f(ch: char) -> bool { + match ch { + 'a'..$0='z' => true, + _ => false + } +} +"# + ); + } + + #[test] + fn goto_def_expr_range() { check_name( "Range", r#" @@ -471,7 +568,7 @@ let x = 0.$0.1; } #[test] - fn goto_def_range_from() { + fn goto_def_expr_range_from() { check_name( "RangeFrom", r#" @@ -484,7 +581,7 @@ fn f(arr: &[i32]) -> &[i32] { } #[test] - fn goto_def_range_inclusive() { + fn goto_def_expr_range_inclusive() { check_name( "RangeInclusive", r#" @@ -495,7 +592,7 @@ let x = 0.$0.=1; } #[test] - fn goto_def_range_full() { + fn goto_def_expr_range_full() { check_name( "RangeFull", r#" @@ -508,7 +605,7 @@ fn f(arr: &[i32]) -> &[i32] { } #[test] - fn goto_def_range_to() { + fn goto_def_expr_range_to() { check_name( "RangeTo", r#" @@ -521,7 +618,7 @@ fn f(arr: &[i32]) -> &[i32] { } #[test] - fn goto_def_range_to_inclusive() { + fn goto_def_expr_range_to_inclusive() { check_name( "RangeToInclusive", r#" From b181cac478806928cb720d9e13a02759592b3d70 Mon Sep 17 00:00:00 2001 From: Duncan Proctor Date: Tue, 22 Oct 2024 06:25:13 -0400 Subject: [PATCH 102/366] remove duplicate test --- .../crates/ide/src/goto_definition.rs | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index aa5c8d004199..1dbab2f3d286 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -540,22 +540,6 @@ fn f(ch: char) -> bool { ); } - #[test] - fn goto_def_range_pat_inclusive() { - check_name( - "RangeInclusive", - r#" -//- minicore: range -fn f(ch: char) -> bool { - match ch { - 'a'..$0='z' => true, - _ => false - } -} -"# - ); - } - #[test] fn goto_def_expr_range() { check_name( From 1467deea64d5b4b638679679aab8fcd2997a81ad Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 13 Oct 2024 12:05:59 +1100 Subject: [PATCH 103/366] Stop using `line_directive` in `runtest::debugger` This also removes unused support for `[rev]` in debugger commands, and makes breakpoint detection slightly more sensible. --- src/tools/compiletest/src/runtest/debugger.rs | 15 +++++------ .../compiletest/src/runtest/debuginfo.rs | 27 +++++-------------- 2 files changed, 12 insertions(+), 30 deletions(-) diff --git a/src/tools/compiletest/src/runtest/debugger.rs b/src/tools/compiletest/src/runtest/debugger.rs index 985fe6381e8d..c15422fb6f68 100644 --- a/src/tools/compiletest/src/runtest/debugger.rs +++ b/src/tools/compiletest/src/runtest/debugger.rs @@ -4,7 +4,6 @@ use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use crate::common::Config; -use crate::header::line_directive; use crate::runtest::ProcRes; /// Representation of information to invoke a debugger and check its output @@ -24,7 +23,6 @@ impl DebuggerCommands { file: &Path, config: &Config, debugger_prefixes: &[&str], - rev: Option<&str>, ) -> Result { let directives = debugger_prefixes .iter() @@ -39,17 +37,16 @@ impl DebuggerCommands { for (line_no, line) in reader.lines().enumerate() { counter += 1; let line = line.map_err(|e| format!("Error while parsing debugger commands: {}", e))?; - let (lnrev, line) = line_directive("//", &line).unwrap_or((None, &line)); - // Skip any revision specific directive that doesn't match the current - // revision being tested - if lnrev.is_some() && lnrev != rev { + // Breakpoints appear on lines with actual code, typically at the end of the line. + if line.contains("#break") { + breakpoint_lines.push(counter); continue; } - if line.contains("#break") { - breakpoint_lines.push(counter); - } + let Some(line) = line.trim_start().strip_prefix("//").map(str::trim_start) else { + continue; + }; for &(ref command_directive, ref check_directive) in &directives { config diff --git a/src/tools/compiletest/src/runtest/debuginfo.rs b/src/tools/compiletest/src/runtest/debuginfo.rs index bd0845b45241..c621c22ac993 100644 --- a/src/tools/compiletest/src/runtest/debuginfo.rs +++ b/src/tools/compiletest/src/runtest/debuginfo.rs @@ -66,13 +66,8 @@ impl TestCx<'_> { }; // Parse debugger commands etc from test files - let dbg_cmds = DebuggerCommands::parse_from( - &self.testpaths.file, - self.config, - prefixes, - self.revision, - ) - .unwrap_or_else(|e| self.fatal(&e)); + let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, prefixes) + .unwrap_or_else(|e| self.fatal(&e)); // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands let mut script_str = String::with_capacity(2048); @@ -142,13 +137,8 @@ impl TestCx<'_> { } fn run_debuginfo_gdb_test_no_opt(&self) { - let dbg_cmds = DebuggerCommands::parse_from( - &self.testpaths.file, - self.config, - &["gdb"], - self.revision, - ) - .unwrap_or_else(|e| self.fatal(&e)); + let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, &["gdb"]) + .unwrap_or_else(|e| self.fatal(&e)); let mut cmds = dbg_cmds.commands.join("\n"); // compile test file (it should have 'compile-flags:-g' in the header) @@ -413,13 +403,8 @@ impl TestCx<'_> { } // Parse debugger commands etc from test files - let dbg_cmds = DebuggerCommands::parse_from( - &self.testpaths.file, - self.config, - &["lldb"], - self.revision, - ) - .unwrap_or_else(|e| self.fatal(&e)); + let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, &["lldb"]) + .unwrap_or_else(|e| self.fatal(&e)); // Write debugger script: // We don't want to hang when calling `quit` while the process is still running From 734710ff44ca4652ffd07ad2b6e6058b168f7b33 Mon Sep 17 00:00:00 2001 From: Duncan Proctor Date: Tue, 22 Oct 2024 06:37:12 -0400 Subject: [PATCH 104/366] tidy --- .../rust-analyzer/crates/ide/src/goto_definition.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 1dbab2f3d286..71e6739d45b1 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -472,7 +472,7 @@ fn f(ch: char) -> bool { _ => false } } -"# +"#, ); } @@ -488,7 +488,7 @@ fn f(ch: char) -> bool { _ => false } } -"# +"#, ); } @@ -504,7 +504,7 @@ fn f(ch: char) -> bool { _ => false } } -"# +"#, ); } @@ -520,7 +520,7 @@ fn f(ch: char) -> bool { _ => false } } -"# +"#, ); } @@ -536,7 +536,7 @@ fn f(ch: char) -> bool { _ => false } } -"# +"#, ); } From c4016ea455c28574b6a5a4413d9c8950fefcb64c Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 13 Oct 2024 13:11:59 +1100 Subject: [PATCH 105/366] Rename some fields of `DirectiveLine` --- src/tools/compiletest/src/header.rs | 50 ++++++++++++++++------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 099e620ffe03..fe1a500e1774 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -57,7 +57,7 @@ impl EarlyProps { &mut poisoned, testfile, rdr, - &mut |DirectiveLine { directive: ln, .. }| { + &mut |DirectiveLine { raw_directive: ln, .. }| { parse_and_update_aux(config, ln, &mut props.aux); config.parse_and_update_revisions(testfile, ln, &mut props.revisions); }, @@ -344,8 +344,8 @@ impl TestProps { &mut poisoned, testfile, file, - &mut |DirectiveLine { header_revision, directive: ln, .. }| { - if header_revision.is_some() && header_revision != test_revision { + &mut |directive @ DirectiveLine { raw_directive: ln, .. }| { + if !directive.applies_to_test_revision(test_revision) { return; } @@ -730,28 +730,37 @@ const KNOWN_HTMLDOCCK_DIRECTIVE_NAMES: &[&str] = &[ const KNOWN_JSONDOCCK_DIRECTIVE_NAMES: &[&str] = &["count", "!count", "has", "!has", "is", "!is", "ismany", "!ismany", "set", "!set"]; -/// The broken-down contents of a line containing a test header directive, +/// The (partly) broken-down contents of a line containing a test directive, /// which [`iter_header`] passes to its callback function. /// /// For example: /// /// ```text /// //@ compile-flags: -O -/// ^^^^^^^^^^^^^^^^^ directive +/// ^^^^^^^^^^^^^^^^^ raw_directive /// /// //@ [foo] compile-flags: -O -/// ^^^ header_revision -/// ^^^^^^^^^^^^^^^^^ directive +/// ^^^ revision +/// ^^^^^^^^^^^^^^^^^ raw_directive /// ``` struct DirectiveLine<'ln> { line_number: usize, - /// Some header directives start with a revision name in square brackets + /// Some test directives start with a revision name in square brackets /// (e.g. `[foo]`), and only apply to that revision of the test. /// If present, this field contains the revision name (e.g. `foo`). - header_revision: Option<&'ln str>, - /// The main part of the header directive, after removing the comment prefix + revision: Option<&'ln str>, + /// The main part of the directive, after removing the comment prefix /// and the optional revision specifier. - directive: &'ln str, + /// + /// This is "raw" because the directive's name and colon-separated value + /// (if present) have not yet been extracted or checked. + raw_directive: &'ln str, +} + +impl<'ln> DirectiveLine<'ln> { + fn applies_to_test_revision(&self, test_revision: Option<&str>) -> bool { + self.revision.is_none() || self.revision == test_revision + } } pub(crate) struct CheckDirectiveResult<'ln> { @@ -819,8 +828,8 @@ fn iter_header( "ignore-cross-compile", ]; // Process the extra implied directives, with a dummy line number of 0. - for directive in extra_directives { - it(DirectiveLine { line_number: 0, header_revision: None, directive }); + for raw_directive in extra_directives { + it(DirectiveLine { line_number: 0, revision: None, raw_directive }); } } @@ -847,14 +856,13 @@ fn iter_header( return; } - let Some((header_revision, non_revisioned_directive_line)) = line_directive(comment, ln) - else { + let Some((revision, raw_directive)) = line_directive(comment, ln) else { continue; }; // Perform unknown directive check on Rust files. if testfile.extension().map(|e| e == "rs").unwrap_or(false) { - let directive_ln = non_revisioned_directive_line.trim(); + let directive_ln = raw_directive.trim(); let CheckDirectiveResult { is_known_directive, trailing_directive } = check_directive(directive_ln, mode, ln); @@ -888,11 +896,7 @@ fn iter_header( } } - it(DirectiveLine { - line_number, - header_revision, - directive: non_revisioned_directive_line, - }); + it(DirectiveLine { line_number, revision, raw_directive }); } } @@ -1292,8 +1296,8 @@ pub fn make_test_description( &mut local_poisoned, path, src, - &mut |DirectiveLine { header_revision, directive: ln, line_number }| { - if header_revision.is_some() && header_revision != test_revision { + &mut |directive @ DirectiveLine { line_number, raw_directive: ln, .. }| { + if !directive.applies_to_test_revision(test_revision) { return; } From 997b7a6ed0630f097f83119d0ddc4e0d8f8d6ea2 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 13 Oct 2024 12:35:52 +1100 Subject: [PATCH 106/366] Make `line_directive` return a `DirectiveLine` This reduces the need to juggle raw tuples, and opens up the possibility of moving more parts of directive parsing into `line_directive`. --- src/tools/compiletest/src/header.rs | 35 ++++++++++++++++------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index fe1a500e1774..d75cdefe635b 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -678,28 +678,35 @@ impl TestProps { } } -/// Extract an `(Option, directive)` directive from a line if comment is present. -/// -/// See [`DirectiveLine`] for a diagram. -pub fn line_directive<'line>( +/// If the given line begins with the appropriate comment prefix for a directive, +/// returns a struct containing various parts of the directive. +fn line_directive<'line>( + line_number: usize, comment: &str, original_line: &'line str, -) -> Option<(Option<&'line str>, &'line str)> { +) -> Option> { // Ignore lines that don't start with the comment prefix. let after_comment = original_line.trim_start().strip_prefix(comment)?.trim_start(); + let revision; + let raw_directive; + if let Some(after_open_bracket) = after_comment.strip_prefix('[') { // A comment like `//@[foo]` only applies to revision `foo`. - let Some((line_revision, directive)) = after_open_bracket.split_once(']') else { + let Some((line_revision, after_close_bracket)) = after_open_bracket.split_once(']') else { panic!( "malformed condition directive: expected `{comment}[foo]`, found `{original_line}`" ) }; - Some((Some(line_revision), directive.trim_start())) + revision = Some(line_revision); + raw_directive = after_close_bracket.trim_start(); } else { - Some((None, after_comment)) - } + revision = None; + raw_directive = after_comment; + }; + + Some(DirectiveLine { line_number, revision, raw_directive }) } // To prevent duplicating the list of commmands between `compiletest`,`htmldocck` and `jsondocck`, @@ -856,23 +863,21 @@ fn iter_header( return; } - let Some((revision, raw_directive)) = line_directive(comment, ln) else { + let Some(directive_line) = line_directive(line_number, comment, ln) else { continue; }; // Perform unknown directive check on Rust files. if testfile.extension().map(|e| e == "rs").unwrap_or(false) { - let directive_ln = raw_directive.trim(); - let CheckDirectiveResult { is_known_directive, trailing_directive } = - check_directive(directive_ln, mode, ln); + check_directive(directive_line.raw_directive, mode, ln); if !is_known_directive { *poisoned = true; eprintln!( "error: detected unknown compiletest test directive `{}` in {}:{}", - directive_ln, + directive_line.raw_directive, testfile.display(), line_number, ); @@ -896,7 +901,7 @@ fn iter_header( } } - it(DirectiveLine { line_number, revision, raw_directive }); + it(directive_line); } } From 273d9d74f92f2c8d633ca120973cc20b31450979 Mon Sep 17 00:00:00 2001 From: Duncan Proctor Date: Tue, 22 Oct 2024 06:54:44 -0400 Subject: [PATCH 107/366] tidy --- src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 1e28990f43ab..9d32229e8f79 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -364,8 +364,7 @@ impl SourceAnalyzer { (RangeOp::Inclusive, None, None) => return None, (RangeOp::Inclusive, Some(_), None) => return None, }; - let s = self.resolver.resolve_known_struct(db.upcast(), &path); - return s; + self.resolver.resolve_known_struct(db.upcast(), &path) } pub(crate) fn resolve_range_expr( From 09068192f86e84bb0dddc105c9f7cc1971684fb7 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 22 Oct 2024 09:46:11 +0100 Subject: [PATCH 108/366] adjust asm test --- tests/assembly/x86-return-float.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/assembly/x86-return-float.rs b/tests/assembly/x86-return-float.rs index 30c5e8696339..acd1af8d38af 100644 --- a/tests/assembly/x86-return-float.rs +++ b/tests/assembly/x86-return-float.rs @@ -305,8 +305,10 @@ pub unsafe fn call_other_f64(x: &mut (usize, f64)) { // CHECK-LABEL: return_f16: #[no_mangle] pub fn return_f16(x: f16) -> f16 { - // CHECK: pinsrw $0, {{.*}}(%ebp), %xmm0 - // CHECK-NOT: xmm0 + // CHECK: pushl %ebp + // CHECK: movl %esp, %ebp + // CHECK: movzwl 8(%ebp), %eax + // CHECK: popl %ebp // CHECK: retl x } From b70feec20652b141e939e9b060bd246d3e22b7b8 Mon Sep 17 00:00:00 2001 From: Khanh Duong Quoc Date: Tue, 22 Oct 2024 20:23:05 +0900 Subject: [PATCH 109/366] feat: render docs from aliased type when docs are missing --- .../rust-analyzer/crates/ide-db/src/defs.rs | 14 +- .../crates/ide/src/hover/tests.rs | 153 ++++++++++++++++++ 2 files changed, 166 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs index 099f26eba78a..0372a58281fc 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs @@ -179,7 +179,19 @@ impl Definition { Definition::Static(it) => it.docs(db), Definition::Trait(it) => it.docs(db), Definition::TraitAlias(it) => it.docs(db), - Definition::TypeAlias(it) => it.docs(db), + Definition::TypeAlias(it) => { + it.docs(db).or_else(|| { + // docs are missing, try to fall back to the docs of the aliased item. + let adt = it.ty(db).as_adt()?; + let docs = adt.docs(db)?; + let docs = format!( + "*This is the documentation for* `{}`\n\n{}", + adt.display(db, edition), + docs.as_str() + ); + Some(Documentation::new(docs)) + }) + } Definition::BuiltinType(it) => { famous_defs.and_then(|fd| { // std exposes prim_{} modules with docstrings on the root to document the builtins diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs index 81397b078552..ef835f5bef8d 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs @@ -9018,3 +9018,156 @@ foo!(BAR_$0); "#]], ); } + +#[test] +fn type_alias_without_docs() { + // Simple. + check( + r#" +/// Docs for B +struct B; + +type A$0 = B; +"#, + expect![[r#" + *A* + + ```rust + test + ``` + + ```rust + // size = 0, align = 1 + type A = B + ``` + + --- + + *This is the documentation for* `struct B` + + Docs for B + "#]], + ); + + // Nested. + check( + r#" +/// Docs for C +struct C; + +type B = C; + +type A$0 = B; +"#, + expect![[r#" + *A* + + ```rust + test + ``` + + ```rust + // size = 0, align = 1 + type A = B + ``` + + --- + + *This is the documentation for* `struct C` + + Docs for C + "#]], + ); + + // Showing the docs for aliased struct instead of intermediate type. + check( + r#" +/// Docs for C +struct C; + +/// Docs for B +type B = C; + +type A$0 = B; +"#, + expect![[r#" + *A* + + ```rust + test + ``` + + ```rust + // size = 0, align = 1 + type A = B + ``` + + --- + + *This is the documentation for* `struct C` + + Docs for C + "#]], + ); + + // No docs found. + check( + r#" +struct C; + +type B = C; + +type A$0 = B; +"#, + expect![[r#" + *A* + + ```rust + test + ``` + + ```rust + // size = 0, align = 1 + type A = B + ``` + "#]], + ); + + // Multiple nested crate. + check( + r#" +//- /lib.rs crate:c +/// Docs for C +pub struct C; + +//- /lib.rs crate:b deps:c +pub use c::C; +pub type B = C; + +//- /lib.rs crate:a deps:b +pub use b::B; +pub type A = B; + +//- /main.rs crate:main deps:a +use a::A$0; +"#, + expect![[r#" + *A* + + ```rust + a + ``` + + ```rust + // size = 0, align = 1 + pub type A = B + ``` + + --- + + *This is the documentation for* `pub struct C` + + Docs for C + "#]], + ); +} From 6f713694282207a743ea4a007547bdc4a4c277f9 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 12:09:06 +0200 Subject: [PATCH 110/366] fix: Fix incorrect parsing of use bounds Also lower them a bit more --- .../crates/hir-def/src/hir/type_ref.rs | 27 ++++++- .../crates/hir-def/src/pretty.rs | 23 +++++- .../crates/hir-ty/src/display.rs | 15 +++- .../rust-analyzer/crates/hir-ty/src/lower.rs | 5 +- .../parser/src/grammar/generic_params.rs | 25 +++++- .../parser/src/syntax_kind/generated.rs | 2 + .../parser/inline/ok/precise_capturing.rast | 16 ++-- .../parser/inline/ok/precise_capturing.rs | 2 +- .../rust-analyzer/crates/syntax/rust.ungram | 9 ++- .../crates/syntax/src/ast/generated/nodes.rs | 79 ++++++++++++++++++- .../crates/syntax/src/ast/node_ext.rs | 6 +- 11 files changed, 184 insertions(+), 25 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs index b74cd90f6933..5fba20669323 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs @@ -157,9 +157,19 @@ pub enum TypeBound { Path(Path, TraitBoundModifier), ForLifetime(Box<[Name]>, Path), Lifetime(LifetimeRef), + Use(Box<[UseArgRef]>), Error, } +#[cfg(target_pointer_width = "64")] +const _: [(); 56] = [(); ::std::mem::size_of::()]; + +#[derive(Clone, PartialEq, Eq, Hash, Debug)] +pub enum UseArgRef { + Name(Name), + Lifetime(LifetimeRef), +} + /// A modifier on a bound, currently this is only used for `?Sized`, where the /// modifier is `Maybe`. #[derive(Clone, PartialEq, Eq, Hash, Debug)] @@ -295,7 +305,7 @@ impl TypeRef { TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => { go_path(path, f) } - TypeBound::Lifetime(_) | TypeBound::Error => (), + TypeBound::Lifetime(_) | TypeBound::Error | TypeBound::Use(_) => (), } } } @@ -328,7 +338,7 @@ impl TypeRef { TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => { go_path(path, f) } - TypeBound::Lifetime(_) | TypeBound::Error => (), + TypeBound::Lifetime(_) | TypeBound::Error | TypeBound::Use(_) => (), } } } @@ -380,7 +390,16 @@ impl TypeBound { None => TypeBound::Error, } } - ast::TypeBoundKind::Use(_) => TypeBound::Error, + ast::TypeBoundKind::Use(gal) => TypeBound::Use( + gal.use_bound_generic_args() + .map(|p| match p { + ast::UseBoundGenericArg::Lifetime(l) => { + UseArgRef::Lifetime(LifetimeRef::new(&l)) + } + ast::UseBoundGenericArg::NameRef(n) => UseArgRef::Name(n.as_name()), + }) + .collect(), + ), ast::TypeBoundKind::Lifetime(lifetime) => { TypeBound::Lifetime(LifetimeRef::new(&lifetime)) } @@ -391,7 +410,7 @@ impl TypeBound { match self { TypeBound::Path(p, m) => Some((p, m)), TypeBound::ForLifetime(_, p) => Some((p, &TraitBoundModifier::None)), - TypeBound::Lifetime(_) | TypeBound::Error => None, + TypeBound::Lifetime(_) | TypeBound::Error | TypeBound::Use(_) => None, } } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs index d5ef17a91fb2..49c0ad412499 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs @@ -1,6 +1,9 @@ //! Display and pretty printing routines. -use std::fmt::{self, Write}; +use std::{ + fmt::{self, Write}, + mem, +}; use hir_expand::mod_path::PathKind; use intern::Interned; @@ -11,7 +14,7 @@ use crate::{ db::DefDatabase, lang_item::LangItemTarget, path::{GenericArg, GenericArgs, Path}, - type_ref::{Mutability, TraitBoundModifier, TypeBound, TypeRef}, + type_ref::{Mutability, TraitBoundModifier, TypeBound, TypeRef, UseArgRef}, }; pub(crate) fn print_path( @@ -273,6 +276,22 @@ pub(crate) fn print_type_bounds( print_path(db, path, buf, edition)?; } TypeBound::Lifetime(lt) => write!(buf, "{}", lt.name.display(db.upcast(), edition))?, + TypeBound::Use(args) => { + write!(buf, "use<")?; + let mut first = true; + for arg in args { + if !mem::take(&mut first) { + write!(buf, ", ")?; + } + match arg { + UseArgRef::Name(it) => write!(buf, "{}", it.display(db.upcast(), edition))?, + UseArgRef::Lifetime(it) => { + write!(buf, "{}", it.name.display(db.upcast(), edition))? + } + } + } + write!(buf, ">")? + } TypeBound::Error => write!(buf, "{{unknown}}")?, } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs index 10f5bcdad860..79861345b8ce 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs @@ -19,7 +19,7 @@ use hir_def::{ lang_item::{LangItem, LangItemTarget}, nameres::DefMap, path::{Path, PathKind}, - type_ref::{TraitBoundModifier, TypeBound, TypeRef}, + type_ref::{TraitBoundModifier, TypeBound, TypeRef, UseArgRef}, visibility::Visibility, GenericDefId, HasModule, ImportPathConfig, ItemContainerId, LocalFieldId, Lookup, ModuleDefId, ModuleId, TraitId, @@ -2025,6 +2025,19 @@ impl HirDisplay for TypeBound { )?; path.hir_fmt(f) } + TypeBound::Use(args) => { + let edition = f.edition(); + write!( + f, + "use<{}> ", + args.iter() + .map(|it| match it { + UseArgRef::Lifetime(lt) => lt.name.display(f.db.upcast(), edition), + UseArgRef::Name(n) => n.display(f.db.upcast(), edition), + }) + .format(", ") + ) + } TypeBound::Error => write!(f, "{{error}}"), } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs index c7ed68448bb4..f7db9489980b 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs @@ -1067,7 +1067,7 @@ impl<'a> TyLoweringContext<'a> { lifetime, }))) } - TypeBound::Error => None, + TypeBound::Use(_) | TypeBound::Error => None, }; clause.into_iter().chain( trait_ref @@ -1087,6 +1087,7 @@ impl<'a> TyLoweringContext<'a> { path.segments().last() } TypeBound::Path(_, TraitBoundModifier::Maybe) + | TypeBound::Use(_) | TypeBound::Error | TypeBound::Lifetime(_) => None, }; @@ -1571,7 +1572,7 @@ pub(crate) fn generic_predicates_for_param_query( }) }) } - TypeBound::Lifetime(_) | TypeBound::Error => false, + TypeBound::Use(_) | TypeBound::Lifetime(_) | TypeBound::Error => false, } } WherePredicate::Lifetime { .. } => false, diff --git a/src/tools/rust-analyzer/crates/parser/src/grammar/generic_params.rs b/src/tools/rust-analyzer/crates/parser/src/grammar/generic_params.rs index ecfabca092c3..92311238c23a 100644 --- a/src/tools/rust-analyzer/crates/parser/src/grammar/generic_params.rs +++ b/src/tools/rust-analyzer/crates/parser/src/grammar/generic_params.rs @@ -144,10 +144,31 @@ fn type_bound(p: &mut Parser<'_>) -> bool { LIFETIME_IDENT => lifetime(p), T![for] => types::for_type(p, false), // test precise_capturing - // fn captures<'a: 'a, 'b: 'b, T>() -> impl Sized + use<'b, T> {} + // fn captures<'a: 'a, 'b: 'b, T>() -> impl Sized + use<'b, T, Self> {} T![use] if p.nth_at(1, T![<]) => { p.bump_any(); - generic_param_list(p) + let m = p.start(); + delimited( + p, + T![<], + T![>], + T![,], + || "expected identifier or lifetime".into(), + TokenSet::new(&[T![Self], IDENT, LIFETIME_IDENT]), + |p| { + if p.at(T![Self]) { + let m = p.start(); + p.bump(T![Self]); + m.complete(p, NAME_REF); + } else if p.at(LIFETIME_IDENT) { + lifetime(p); + } else { + name_ref(p); + } + true + }, + ); + m.complete(p, USE_BOUND_GENERIC_ARGS); } T![?] if p.nth_at(1, T![for]) => { // test question_for_type_trait_bound diff --git a/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs b/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs index 8da338c0a2c5..21730244a339 100644 --- a/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs +++ b/src/tools/rust-analyzer/crates/parser/src/syntax_kind/generated.rs @@ -312,6 +312,8 @@ pub enum SyntaxKind { UNDERSCORE_EXPR, UNION, USE, + USE_BOUND_GENERIC_ARG, + USE_BOUND_GENERIC_ARGS, USE_TREE, USE_TREE_LIST, VARIANT, diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rast b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rast index cf52f1e47995..f9c0a245af86 100644 --- a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rast +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rast @@ -50,16 +50,18 @@ SOURCE_FILE WHITESPACE " " TYPE_BOUND USE_KW "use" - GENERIC_PARAM_LIST + USE_BOUND_GENERIC_ARGS L_ANGLE "<" - LIFETIME_PARAM - LIFETIME - LIFETIME_IDENT "'b" + LIFETIME + LIFETIME_IDENT "'b" COMMA "," WHITESPACE " " - TYPE_PARAM - NAME - IDENT "T" + NAME_REF + IDENT "T" + COMMA "," + WHITESPACE " " + NAME_REF + SELF_TYPE_KW "Self" R_ANGLE ">" WHITESPACE " " BLOCK_EXPR diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rs b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rs index ec208d5062b5..9ac2305f3a0e 100644 --- a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rs +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/precise_capturing.rs @@ -1 +1 @@ -fn captures<'a: 'a, 'b: 'b, T>() -> impl Sized + use<'b, T> {} +fn captures<'a: 'a, 'b: 'b, T>() -> impl Sized + use<'b, T, Self> {} diff --git a/src/tools/rust-analyzer/crates/syntax/rust.ungram b/src/tools/rust-analyzer/crates/syntax/rust.ungram index 90441c27f628..3609da0bb263 100644 --- a/src/tools/rust-analyzer/crates/syntax/rust.ungram +++ b/src/tools/rust-analyzer/crates/syntax/rust.ungram @@ -657,7 +657,14 @@ TypeBoundList = TypeBound = Lifetime | ('~' 'const' | 'const')? 'async'? '?'? Type -| 'use' GenericParamList +| 'use' UseBoundGenericArgs + +UseBoundGenericArgs = + '<' (UseBoundGenericArg (',' UseBoundGenericArg)* ','?)? '>' + +UseBoundGenericArg = + Lifetime +| NameRef //************************// // Patterns // diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs index 4f8bff489cfb..b9eb1abb1129 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs @@ -1993,13 +1993,15 @@ pub struct TypeBound { pub(crate) syntax: SyntaxNode, } impl TypeBound { - #[inline] - pub fn generic_param_list(&self) -> Option { support::child(&self.syntax) } #[inline] pub fn lifetime(&self) -> Option { support::child(&self.syntax) } #[inline] pub fn ty(&self) -> Option { support::child(&self.syntax) } #[inline] + pub fn use_bound_generic_args(&self) -> Option { + support::child(&self.syntax) + } + #[inline] pub fn question_mark_token(&self) -> Option { support::token(&self.syntax, T![?]) } #[inline] pub fn async_token(&self) -> Option { support::token(&self.syntax, T![async]) } @@ -2076,6 +2078,21 @@ impl Use { pub fn use_token(&self) -> Option { support::token(&self.syntax, T![use]) } } +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct UseBoundGenericArgs { + pub(crate) syntax: SyntaxNode, +} +impl UseBoundGenericArgs { + #[inline] + pub fn use_bound_generic_args(&self) -> AstChildren { + support::children(&self.syntax) + } + #[inline] + pub fn l_angle_token(&self) -> Option { support::token(&self.syntax, T![<]) } + #[inline] + pub fn r_angle_token(&self) -> Option { support::token(&self.syntax, T![>]) } +} + #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct UseTree { pub(crate) syntax: SyntaxNode, @@ -2402,6 +2419,12 @@ pub enum Type { TupleType(TupleType), } +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum UseBoundGenericArg { + Lifetime(Lifetime), + NameRef(NameRef), +} + #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct AnyHasArgList { pub(crate) syntax: SyntaxNode, @@ -4435,6 +4458,20 @@ impl AstNode for Use { #[inline] fn syntax(&self) -> &SyntaxNode { &self.syntax } } +impl AstNode for UseBoundGenericArgs { + #[inline] + fn can_cast(kind: SyntaxKind) -> bool { kind == USE_BOUND_GENERIC_ARGS } + #[inline] + fn cast(syntax: SyntaxNode) -> Option { + if Self::can_cast(syntax.kind()) { + Some(Self { syntax }) + } else { + None + } + } + #[inline] + fn syntax(&self) -> &SyntaxNode { &self.syntax } +} impl AstNode for UseTree { #[inline] fn can_cast(kind: SyntaxKind) -> bool { kind == USE_TREE } @@ -5560,6 +5597,34 @@ impl AstNode for Type { } } } +impl From for UseBoundGenericArg { + #[inline] + fn from(node: Lifetime) -> UseBoundGenericArg { UseBoundGenericArg::Lifetime(node) } +} +impl From for UseBoundGenericArg { + #[inline] + fn from(node: NameRef) -> UseBoundGenericArg { UseBoundGenericArg::NameRef(node) } +} +impl AstNode for UseBoundGenericArg { + #[inline] + fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, LIFETIME | NAME_REF) } + #[inline] + fn cast(syntax: SyntaxNode) -> Option { + let res = match syntax.kind() { + LIFETIME => UseBoundGenericArg::Lifetime(Lifetime { syntax }), + NAME_REF => UseBoundGenericArg::NameRef(NameRef { syntax }), + _ => return None, + }; + Some(res) + } + #[inline] + fn syntax(&self) -> &SyntaxNode { + match self { + UseBoundGenericArg::Lifetime(it) => &it.syntax, + UseBoundGenericArg::NameRef(it) => &it.syntax, + } + } +} impl AnyHasArgList { #[inline] pub fn new(node: T) -> AnyHasArgList { @@ -6570,6 +6635,11 @@ impl std::fmt::Display for Type { std::fmt::Display::fmt(self.syntax(), f) } } +impl std::fmt::Display for UseBoundGenericArg { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(self.syntax(), f) + } +} impl std::fmt::Display for Abi { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self.syntax(), f) @@ -7275,6 +7345,11 @@ impl std::fmt::Display for Use { std::fmt::Display::fmt(self.syntax(), f) } } +impl std::fmt::Display for UseBoundGenericArgs { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(self.syntax(), f) + } +} impl std::fmt::Display for UseTree { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self.syntax(), f) diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs index 693bfe330bd9..11f5e662e3d6 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs @@ -795,7 +795,7 @@ pub enum TypeBoundKind { /// for<'a> ... ForType(ast::ForType), /// use - Use(ast::GenericParamList), + Use(ast::UseBoundGenericArgs), /// 'a Lifetime(ast::Lifetime), } @@ -806,8 +806,8 @@ impl ast::TypeBound { TypeBoundKind::PathType(path_type) } else if let Some(for_type) = support::children(self.syntax()).next() { TypeBoundKind::ForType(for_type) - } else if let Some(generic_param_list) = self.generic_param_list() { - TypeBoundKind::Use(generic_param_list) + } else if let Some(args) = self.use_bound_generic_args() { + TypeBoundKind::Use(args) } else if let Some(lifetime) = self.lifetime() { TypeBoundKind::Lifetime(lifetime) } else { From 921e2f8f669afda3b1f217e70f0b57158fb2f7b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Fri, 18 Oct 2024 16:53:43 +0800 Subject: [PATCH 111/366] run_make_support: allow obtaining raw stdout/stderr And match `stdout/stderr` lossy UTF-8 helpers. --- src/tools/run-make-support/src/command.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/tools/run-make-support/src/command.rs b/src/tools/run-make-support/src/command.rs index 6b58173b3430..9e09527d6d08 100644 --- a/src/tools/run-make-support/src/command.rs +++ b/src/tools/run-make-support/src/command.rs @@ -222,6 +222,12 @@ pub struct CompletedProcess { } impl CompletedProcess { + #[must_use] + #[track_caller] + pub fn stdout(&self) -> Vec { + self.output.stdout.clone() + } + #[must_use] #[track_caller] pub fn stdout_utf8(&self) -> String { @@ -234,12 +240,24 @@ impl CompletedProcess { String::from_utf8_lossy(&self.output.stdout.clone()).to_string() } + #[must_use] + #[track_caller] + pub fn stderr(&self) -> Vec { + self.output.stderr.clone() + } + #[must_use] #[track_caller] pub fn stderr_utf8(&self) -> String { String::from_utf8(self.output.stderr.clone()).expect("stderr is not valid UTF-8") } + #[must_use] + #[track_caller] + pub fn invalid_stderr_utf8(&self) -> String { + String::from_utf8_lossy(&self.output.stderr.clone()).to_string() + } + #[must_use] pub fn status(&self) -> ExitStatus { self.output.status From 562d08ee27a4348e7b1ebce2e6c8ac29f9ee213d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Fri, 18 Oct 2024 17:04:01 +0800 Subject: [PATCH 112/366] tests/run-make: fix `cross-lang-lto-riscv-abi` --- .../cross-lang-lto-riscv-abi/rmake.rs | 84 ++++++++++++++----- 1 file changed, 61 insertions(+), 23 deletions(-) diff --git a/tests/run-make/cross-lang-lto-riscv-abi/rmake.rs b/tests/run-make/cross-lang-lto-riscv-abi/rmake.rs index 92573353a741..e595dbea94d6 100644 --- a/tests/run-make/cross-lang-lto-riscv-abi/rmake.rs +++ b/tests/run-make/cross-lang-lto-riscv-abi/rmake.rs @@ -1,21 +1,20 @@ -//! Make sure that cross-language LTO works on riscv targets, -//! which requires extra `target-abi` metadata to be emitted. +//! Make sure that cross-language LTO works on riscv targets, which requires extra `target-abi` +//! metadata to be emitted. //@ needs-force-clang-based-tests -//@ needs-llvm-components riscv +//@ needs-llvm-components: riscv -//@ needs-force-clang-based-tests -// FIXME(#126180): This test can only run on `x86_64-gnu-debug`, because that CI job sets -// RUSTBUILD_FORCE_CLANG_BASED_TESTS and only runs tests which contain "clang" in their -// name. -// However, this test does not run at all as its name does not contain "clang". +// ignore-tidy-linelength -use std::path::PathBuf; -use std::process::{Command, Output}; -use std::{env, str}; +use object::elf; +use object::read::elf as readelf; +use run_make_support::{bin_name, clang, object, rfs, rustc}; -use run_make_support::{bin_name, clang, llvm_readobj, rustc}; - -fn check_target(target: &str, clang_target: &str, carch: &str, is_double_float: bool) { +fn check_target>( + target: &str, + clang_target: &str, + carch: &str, + is_double_float: bool, +) { eprintln!("Checking target {target}"); // Rust part rustc() @@ -39,16 +38,55 @@ fn check_target(target: &str, clang_target: &str, carch: &str, is_double_float: // Check that the built binary has correct float abi let executable = bin_name("riscv-xlto"); - let output = llvm_readobj().input(&executable).file_header().run(); - let stdout = String::from_utf8_lossy(&output.stdout); - eprintln!("obj:\n{}", stdout); - - assert!(!(is_double_float ^ stdout.contains("EF_RISCV_FLOAT_ABI_DOUBLE"))); + let data = rfs::read(&executable); + let header = ::parse(&*data).unwrap(); + let endian = match header.e_ident().data { + elf::ELFDATA2LSB => object::Endianness::Little, + elf::ELFDATA2MSB => object::Endianness::Big, + x => unreachable!("invalid e_ident data: {:#010b}", x), + }; + // Check `(e_flags & EF_RISCV_FLOAT_ABI) == EF_RISCV_FLOAT_ABI_DOUBLE`. + // + // See + // . + if is_double_float { + assert_eq!( + header.e_flags(endian) & elf::EF_RISCV_FLOAT_ABI, + elf::EF_RISCV_FLOAT_ABI_DOUBLE, + "expected {target} to use double ABI, but it did not" + ); + } else { + assert_ne!( + header.e_flags(endian) & elf::EF_RISCV_FLOAT_ABI, + elf::EF_RISCV_FLOAT_ABI_DOUBLE, + "did not expected {target} to use double ABI" + ); + } } fn main() { - check_target("riscv64gc-unknown-linux-gnu", "riscv64-linux-gnu", "rv64gc", true); - check_target("riscv64imac-unknown-none-elf", "riscv64-unknown-elf", "rv64imac", false); - check_target("riscv32imac-unknown-none-elf", "riscv32-unknown-elf", "rv32imac", false); - check_target("riscv32gc-unknown-linux-gnu", "riscv32-linux-gnu", "rv32gc", true); + check_target::>( + "riscv64gc-unknown-linux-gnu", + "riscv64-linux-gnu", + "rv64gc", + true, + ); + check_target::>( + "riscv64imac-unknown-none-elf", + "riscv64-unknown-elf", + "rv64imac", + false, + ); + check_target::>( + "riscv32imac-unknown-none-elf", + "riscv32-unknown-elf", + "rv32imac", + false, + ); + check_target::>( + "riscv32gc-unknown-linux-gnu", + "riscv32-linux-gnu", + "rv32gc", + true, + ); } From ef743af119f9f244d47d3857c33c92ed2e217020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Fri, 18 Oct 2024 17:34:11 +0800 Subject: [PATCH 113/366] run-make-support: add `llvm-dis` and `llvm-objcopy` --- .../src/external_deps/llvm.rs | 66 +++++++++++++++++++ src/tools/run-make-support/src/lib.rs | 11 ++-- 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/src/tools/run-make-support/src/external_deps/llvm.rs b/src/tools/run-make-support/src/external_deps/llvm.rs index 38a9ac923b4d..9a6e35da3fe2 100644 --- a/src/tools/run-make-support/src/external_deps/llvm.rs +++ b/src/tools/run-make-support/src/external_deps/llvm.rs @@ -60,6 +60,18 @@ pub fn llvm_pdbutil() -> LlvmPdbutil { LlvmPdbutil::new() } +/// Construct a new `llvm-dis` invocation. This assumes that `llvm-dis` is available +/// at `$LLVM_BIN_DIR/llvm-dis`. +pub fn llvm_dis() -> LlvmDis { + LlvmDis::new() +} + +/// Construct a new `llvm-objcopy` invocation. This assumes that `llvm-objcopy` is available +/// at `$LLVM_BIN_DIR/llvm-objcopy`. +pub fn llvm_objcopy() -> LlvmObjcopy { + LlvmObjcopy::new() +} + /// A `llvm-readobj` invocation builder. #[derive(Debug)] #[must_use] @@ -123,6 +135,20 @@ pub struct LlvmPdbutil { cmd: Command, } +/// A `llvm-dis` invocation builder. +#[derive(Debug)] +#[must_use] +pub struct LlvmDis { + cmd: Command, +} + +/// A `llvm-objcopy` invocation builder. +#[derive(Debug)] +#[must_use] +pub struct LlvmObjcopy { + cmd: Command, +} + crate::macros::impl_common_helpers!(LlvmReadobj); crate::macros::impl_common_helpers!(LlvmProfdata); crate::macros::impl_common_helpers!(LlvmFilecheck); @@ -132,6 +158,8 @@ crate::macros::impl_common_helpers!(LlvmNm); crate::macros::impl_common_helpers!(LlvmBcanalyzer); crate::macros::impl_common_helpers!(LlvmDwarfdump); crate::macros::impl_common_helpers!(LlvmPdbutil); +crate::macros::impl_common_helpers!(LlvmDis); +crate::macros::impl_common_helpers!(LlvmObjcopy); /// Generate the path to the bin directory of LLVM. #[must_use] @@ -390,3 +418,41 @@ impl LlvmPdbutil { self } } + +impl LlvmObjcopy { + /// Construct a new `llvm-objcopy` invocation. This assumes that `llvm-objcopy` is available + /// at `$LLVM_BIN_DIR/llvm-objcopy`. + pub fn new() -> Self { + let llvm_objcopy = llvm_bin_dir().join("llvm-objcopy"); + let cmd = Command::new(llvm_objcopy); + Self { cmd } + } + + /// Dump the contents of `section` into the file at `path`. + #[track_caller] + pub fn dump_section, P: AsRef>( + &mut self, + section_name: S, + path: P, + ) -> &mut Self { + self.cmd.arg("--dump-section"); + self.cmd.arg(format!("{}={}", section_name.as_ref(), path.as_ref().to_str().unwrap())); + self + } +} + +impl LlvmDis { + /// Construct a new `llvm-dis` invocation. This assumes that `llvm-dis` is available + /// at `$LLVM_BIN_DIR/llvm-dis`. + pub fn new() -> Self { + let llvm_dis = llvm_bin_dir().join("llvm-dis"); + let cmd = Command::new(llvm_dis); + Self { cmd } + } + + /// Provide an input file. + pub fn input>(&mut self, path: P) -> &mut Self { + self.cmd.arg(path.as_ref()); + self + } +} diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index 15d813ccf530..368b98c9f0df 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -49,14 +49,17 @@ pub use external_deps::{c_build, cc, clang, htmldocck, llvm, python, rustc, rust // These rely on external dependencies. pub use cc::{cc, cxx, extra_c_flags, extra_cxx_flags, Cc}; -pub use c_build::{build_native_dynamic_lib, build_native_static_lib, build_native_static_lib_optimized, build_native_static_lib_cxx}; +pub use c_build::{ + build_native_dynamic_lib, build_native_static_lib, build_native_static_lib_cxx, + build_native_static_lib_optimized, +}; pub use cargo::cargo; pub use clang::{clang, Clang}; pub use htmldocck::htmldocck; pub use llvm::{ - llvm_ar, llvm_bcanalyzer, llvm_dwarfdump, llvm_filecheck, llvm_nm, llvm_objdump, llvm_profdata, - llvm_readobj, LlvmAr, LlvmBcanalyzer, LlvmDwarfdump, LlvmFilecheck, LlvmNm, LlvmObjdump, - LlvmProfdata, LlvmReadobj, + llvm_ar, llvm_bcanalyzer, llvm_dis, llvm_dwarfdump, llvm_filecheck, llvm_nm, llvm_objcopy, + llvm_objdump, llvm_profdata, llvm_readobj, LlvmAr, LlvmBcanalyzer, LlvmDis, LlvmDwarfdump, + LlvmFilecheck, LlvmNm, LlvmObjcopy, LlvmObjdump, LlvmProfdata, LlvmReadobj, }; pub use python::python_command; pub use rustc::{aux_build, bare_rustc, rustc, rustc_path, Rustc}; From e641b6c2bda63b22e9fc6d4a4e975fd02b5f79d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Fri, 18 Oct 2024 17:34:47 +0800 Subject: [PATCH 114/366] tests/run-make: port `issue-84395-lto-embed-bitcode` to rmake.rs Co-authored-by: Oneirical --- .../tidy/src/allowed_run_make_makefiles.txt | 1 - .../issue-84395-lto-embed-bitcode/Makefile | 14 ---------- .../issue-84395-lto-embed-bitcode/rmake.rs | 27 +++++++++++++++++++ 3 files changed, 27 insertions(+), 15 deletions(-) delete mode 100644 tests/run-make/issue-84395-lto-embed-bitcode/Makefile create mode 100644 tests/run-make/issue-84395-lto-embed-bitcode/rmake.rs diff --git a/src/tools/tidy/src/allowed_run_make_makefiles.txt b/src/tools/tidy/src/allowed_run_make_makefiles.txt index 7a0f98d59f00..0e156b9d1ac9 100644 --- a/src/tools/tidy/src/allowed_run_make_makefiles.txt +++ b/src/tools/tidy/src/allowed_run_make_makefiles.txt @@ -2,7 +2,6 @@ run-make/branch-protection-check-IBT/Makefile run-make/cat-and-grep-sanity-check/Makefile run-make/extern-fn-reachable/Makefile run-make/incr-add-rust-src-component/Makefile -run-make/issue-84395-lto-embed-bitcode/Makefile run-make/jobserver-error/Makefile run-make/libs-through-symlinks/Makefile run-make/split-debuginfo/Makefile diff --git a/tests/run-make/issue-84395-lto-embed-bitcode/Makefile b/tests/run-make/issue-84395-lto-embed-bitcode/Makefile deleted file mode 100644 index aabe90754a65..000000000000 --- a/tests/run-make/issue-84395-lto-embed-bitcode/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -# needs-force-clang-based-tests - -# FIXME(#126180): This test doesn't actually run anywhere, because the only -# CI job that sets RUSTBUILD_FORCE_CLANG_BASED_TESTS runs very few tests. - -# This test makes sure the embed bitcode in elf created with -# lto-embed-bitcode=optimized is valid llvm BC module. - -include ../tools.mk - -all: - $(RUSTC) test.rs --target $(TARGET) -Clink-arg=-fuse-ld=lld -Clinker-plugin-lto -Clinker=$(CLANG) -Clink-arg=-Wl,--plugin-opt=-lto-embed-bitcode=optimized -Zemit-thin-lto=no - $(LLVM_BIN_DIR)/objcopy --dump-section .llvmbc=$(TMPDIR)/test.bc $(TMPDIR)/test - $(LLVM_BIN_DIR)/llvm-dis $(TMPDIR)/test.bc diff --git a/tests/run-make/issue-84395-lto-embed-bitcode/rmake.rs b/tests/run-make/issue-84395-lto-embed-bitcode/rmake.rs new file mode 100644 index 000000000000..450d8a9f099b --- /dev/null +++ b/tests/run-make/issue-84395-lto-embed-bitcode/rmake.rs @@ -0,0 +1,27 @@ +//! Smoke test to make sure the embed bitcode in elf created with +//! `--plugin-opt=-lto-embed-bitcode=optimized` is valid llvm BC module. +//! +//! See where passing +//! `-lto-embed-bitcode=optimized` to lld when linking rust code via `linker-plugin-lto` doesn't +//! produce the expected result. +//! +//! See PR which initially introduced this test. + +//@ needs-force-clang-based-tests + +use run_make_support::{env_var, llvm_dis, llvm_objcopy, rustc}; + +fn main() { + rustc() + .input("test.rs") + .arg("-Clink-arg=-fuse-ld=lld") + .arg("-Clinker-plugin-lto") + .arg(format!("-Clinker={}", env_var("CLANG"))) + .arg("-Clink-arg=-Wl,--plugin-opt=-lto-embed-bitcode=optimized") + .arg("-Zemit-thin-lto=no") + .run(); + + llvm_objcopy().dump_section(".llvmbc", "test.bc").arg("test").run(); + + llvm_dis().arg("test.bc").run(); +} From 0ccc62a5dcbc38546791aed591fcc9314712574b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Fri, 18 Oct 2024 14:04:28 +0800 Subject: [PATCH 115/366] ci: run the full `run-make` test suite Instead of filtering `run-make` tests whose test names contain the `clang` substring. --- src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile b/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile index fa31801269af..292dbfd20a50 100644 --- a/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile +++ b/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile @@ -49,9 +49,7 @@ ENV RUST_CONFIGURE_ARGS \ # (without necessarily testing the result). # - That the tests with `//@ needs-force-clang-based-tests` pass, since they # don't run by default unless RUSTBUILD_FORCE_CLANG_BASED_TESTS is set. -# - FIXME(https://github.com/rust-lang/rust/pull/126155#issuecomment-2156314273): -# Currently we only run the subset of tests with "clang" in their name. ENV SCRIPT \ python3 ../x.py --stage 2 build && \ - python3 ../x.py --stage 2 test tests/run-make --test-args clang + python3 ../x.py --stage 2 test tests/run-make From 03c7f992cd3b955bde2cdffc30ed44bcdb4f972f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Tue, 22 Oct 2024 19:44:30 +0800 Subject: [PATCH 116/366] ci: switch `x86_64-gnu-debug` to use a large disk runner Full stage 2 build + run-make with full debug info seems to overwhelm the standard 4c runner's storage capacity. --- src/ci/github-actions/jobs.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index 2b6366040490..52c97907b6a2 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -253,7 +253,9 @@ auto: <<: *job-linux-4c - image: x86_64-gnu-debug - <<: *job-linux-4c + # This seems to be needed because a full stage 2 build + run-make tests + # overwhelms the storage capacity of the standard 4c runner. + <<: *job-linux-4c-largedisk - image: x86_64-gnu-distcheck <<: *job-linux-8c From 7c315cfbe6cf21ba5a3cc1fcf7e061b6b49eb719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Oct 2024 14:04:24 +0200 Subject: [PATCH 117/366] Switch CI from bors to merge queues --- .../rust-analyzer/.github/workflows/ci.yaml | 37 +++++++++---------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index 5cf4a8fd4393..d82e46016dc2 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -1,14 +1,10 @@ -# Please make sure that the `needs` fields for both `end-success` and `end-failure` +# Please make sure that the `needs` field for the `conclusion` job # are updated when adding new jobs! name: CI on: pull_request: - push: - branches: - - auto - - try - - automation/bors/try + merge_group: env: CARGO_INCREMENTAL: 0 @@ -237,20 +233,21 @@ jobs: - name: check for typos run: typos - end-success: - name: bors build finished - if: github.event.pusher.name == 'bors' && success() - runs-on: ubuntu-latest + conclusion: needs: [rust, rust-cross, typescript, typo-check] - steps: - - name: Mark the job as successful - run: exit 0 - - end-failure: - name: bors build finished - if: github.event.pusher.name == 'bors' && !success() + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + # + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + if: ${{ !cancelled() }} runs-on: ubuntu-latest - needs: [rust, rust-cross, typescript, typo-check] steps: - - name: Mark the job as a failure - run: exit 1 + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' From 8f85b90ca6d57459eb19accb6aaf781dd1c7bf6c Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Wed, 11 Sep 2024 12:27:08 +0000 Subject: [PATCH 118/366] Rename Receiver -> LegacyReceiver As part of the "arbitrary self types v2" project, we are going to replace the current `Receiver` trait with a new mechanism based on a new, different `Receiver` trait. This PR renames the old trait to get it out the way. Naming is hard. Options considered included: * HardCodedReceiver (because it should only be used for things in the standard library, and hence is sort-of hard coded) * LegacyReceiver * TargetLessReceiver * OldReceiver These are all bad names, but fortunately this will be temporary. Assuming the new mechanism proceeds to stabilization as intended, the legacy trait will be removed altogether. Although we expect this trait to be used only in the standard library, we suspect it may be in use elsehwere, so we're landing this change separately to identify any surprising breakages. It's known that this trait is used within the Rust for Linux project; a patch is in progress to remove their dependency. This is a part of the arbitrary self types v2 project, https://github.com/rust-lang/rfcs/pull/3519 https://github.com/rust-lang/rust/issues/44874 r? @wesleywiser --- .../example/mini_core.rs | 10 +++++----- .../rustc_codegen_gcc/example/mini_core.rs | 10 +++++----- compiler/rustc_hir/src/lang_items.rs | 2 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 2 +- compiler/rustc_span/src/symbol.rs | 2 +- library/alloc/src/boxed.rs | 6 +++--- library/alloc/src/lib.rs | 2 +- library/alloc/src/rc.rs | 6 +++--- library/alloc/src/sync.rs | 6 +++--- library/core/src/ops/deref.rs | 20 ++++++++++++------- library/core/src/ops/mod.rs | 4 ++-- library/core/src/pin.rs | 6 +++--- tests/codegen/avr/avr-func-addrspace.rs | 4 ++-- .../kcfi/emit-type-metadata-trait-objects.rs | 4 ++-- tests/rustdoc-json/impls/auto.rs | 4 ++-- tests/ui/abi/compatibility.rs | 8 ++++---- tests/ui/privacy/privacy1.rs | 6 +++--- .../const-traits/const-fns-are-early-bound.rs | 8 ++++---- .../traits/const-traits/effects/minicore.rs | 10 +++++----- 19 files changed, 63 insertions(+), 57 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/example/mini_core.rs b/compiler/rustc_codegen_cranelift/example/mini_core.rs index 9fc0318df5dc..42c7f5f0dc69 100644 --- a/compiler/rustc_codegen_cranelift/example/mini_core.rs +++ b/compiler/rustc_codegen_cranelift/example/mini_core.rs @@ -47,12 +47,12 @@ impl, U: ?Sized> DispatchFromDyn<*const U> for *const T {} impl, U: ?Sized> DispatchFromDyn<*mut U> for *mut T {} impl, U: ?Sized> DispatchFromDyn> for Box {} -#[lang = "receiver"] -pub trait Receiver {} +#[lang = "legacy_receiver"] +pub trait LegacyReceiver {} -impl Receiver for &T {} -impl Receiver for &mut T {} -impl Receiver for Box {} +impl LegacyReceiver for &T {} +impl LegacyReceiver for &mut T {} +impl LegacyReceiver for Box {} #[lang = "copy"] pub unsafe trait Copy {} diff --git a/compiler/rustc_codegen_gcc/example/mini_core.rs b/compiler/rustc_codegen_gcc/example/mini_core.rs index f47bfdad1312..0576b64ef6fa 100644 --- a/compiler/rustc_codegen_gcc/example/mini_core.rs +++ b/compiler/rustc_codegen_gcc/example/mini_core.rs @@ -44,12 +44,12 @@ impl, U: ?Sized> DispatchFromDyn<*const U> for *const T {} impl, U: ?Sized> DispatchFromDyn<*mut U> for *mut T {} impl, U: ?Sized> DispatchFromDyn> for Box {} -#[lang = "receiver"] -pub trait Receiver {} +#[lang = "legacy_receiver"] +pub trait LegacyReceiver {} -impl Receiver for &T {} -impl Receiver for &mut T {} -impl Receiver for Box {} +impl LegacyReceiver for &T {} +impl LegacyReceiver for &mut T {} +impl LegacyReceiver for Box {} #[lang = "copy"] pub unsafe trait Copy {} diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index b161e6ba0fa5..ae046c09ebea 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -241,7 +241,7 @@ language_item_table! { DerefMut, sym::deref_mut, deref_mut_trait, Target::Trait, GenericRequirement::Exact(0); DerefPure, sym::deref_pure, deref_pure_trait, Target::Trait, GenericRequirement::Exact(0); DerefTarget, sym::deref_target, deref_target, Target::AssocTy, GenericRequirement::None; - Receiver, sym::receiver, receiver_trait, Target::Trait, GenericRequirement::None; + LegacyReceiver, sym::legacy_receiver, legacy_receiver_trait, Target::Trait, GenericRequirement::None; Fn, kw::Fn, fn_trait, Target::Trait, GenericRequirement::Exact(1); FnMut, sym::fn_mut, fn_mut_trait, Target::Trait, GenericRequirement::Exact(1); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index f788456d4e9e..ee46a1ffc7b8 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1801,7 +1801,7 @@ fn receiver_is_valid<'tcx>( autoderef = autoderef.include_raw_pointers(); } - let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, Some(span)); + let receiver_trait_def_id = tcx.require_lang_item(LangItem::LegacyReceiver, Some(span)); // Keep dereferencing `receiver_ty` until we get to `self_ty`. while let Some((potential_self_ty, _)) = autoderef.next() { diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 3ab482072b8f..aa05b88ea0c4 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1133,6 +1133,7 @@ symbols! { lazy_normalization_consts, lazy_type_alias, le, + legacy_receiver, len, let_chains, let_else, @@ -1573,7 +1574,6 @@ symbols! { readonly, realloc, reason, - receiver, recursion_limit, reexport_test_harness_main, ref_pat_eat_one_layer_2024, diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 3e791416820e..bc354650a8eb 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -196,7 +196,7 @@ use core::marker::{Tuple, Unsize}; use core::mem::{self, SizedTypeProperties}; use core::ops::{ AsyncFn, AsyncFnMut, AsyncFnOnce, CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut, - DerefPure, DispatchFromDyn, Receiver, + DerefPure, DispatchFromDyn, LegacyReceiver, }; use core::pin::{Pin, PinCoerceUnsized}; use core::ptr::{self, NonNull, Unique}; @@ -2378,8 +2378,8 @@ impl DerefMut for Box { #[unstable(feature = "deref_pure_trait", issue = "87121")] unsafe impl DerefPure for Box {} -#[unstable(feature = "receiver_trait", issue = "none")] -impl Receiver for Box {} +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Box {} #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for Box { diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 50a5f3c5b1e0..dd9dfa3f5e26 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -129,6 +129,7 @@ #![feature(iter_advance_by)] #![feature(iter_next_chunk)] #![feature(layout_for_ptr)] +#![feature(legacy_receiver_trait)] #![feature(local_waker)] #![feature(maybe_uninit_slice)] #![feature(maybe_uninit_uninit_array_transpose)] @@ -138,7 +139,6 @@ #![feature(ptr_internals)] #![feature(ptr_metadata)] #![feature(ptr_sub_ptr)] -#![feature(receiver_trait)] #![feature(set_ptr_value)] #![feature(sized_type_properties)] #![feature(slice_from_ptr_range)] diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index e98ae7c31ad0..686a93bf9378 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -252,7 +252,7 @@ use core::intrinsics::abort; use core::iter; use core::marker::{PhantomData, Unsize}; use core::mem::{self, ManuallyDrop, align_of_val_raw}; -use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; +use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; #[cfg(not(no_global_oom_handling))] use core::pin::Pin; @@ -2222,8 +2222,8 @@ unsafe impl PinCoerceUnsized for Weak {} #[unstable(feature = "deref_pure_trait", issue = "87121")] unsafe impl DerefPure for Rc {} -#[unstable(feature = "receiver_trait", issue = "none")] -impl Receiver for Rc {} +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Rc {} #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc { diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index acbc325a5141..a15d7c2a4423 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -18,7 +18,7 @@ use core::intrinsics::abort; use core::iter; use core::marker::{PhantomData, Unsize}; use core::mem::{self, ManuallyDrop, align_of_val_raw}; -use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, Receiver}; +use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, LegacyReceiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; use core::pin::{Pin, PinCoerceUnsized}; use core::ptr::{self, NonNull}; @@ -2189,8 +2189,8 @@ unsafe impl PinCoerceUnsized for Weak {} #[unstable(feature = "deref_pure_trait", issue = "87121")] unsafe impl DerefPure for Arc {} -#[unstable(feature = "receiver_trait", issue = "none")] -impl Receiver for Arc {} +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Arc {} #[cfg(not(no_global_oom_handling))] impl Arc { diff --git a/library/core/src/ops/deref.rs b/library/core/src/ops/deref.rs index f0d2c761ef35..49b380e45749 100644 --- a/library/core/src/ops/deref.rs +++ b/library/core/src/ops/deref.rs @@ -297,15 +297,21 @@ unsafe impl DerefPure for &mut T {} /// Indicates that a struct can be used as a method receiver, without the /// `arbitrary_self_types` feature. This is implemented by stdlib pointer types like `Box`, /// `Rc`, `&T`, and `Pin

`. -#[lang = "receiver"] -#[unstable(feature = "receiver_trait", issue = "none")] +/// +/// This trait will shortly be removed and replaced with a more generic +/// facility based around the current "arbitrary self types" unstable feature. +/// That new facility will use a replacement trait called `Receiver` which is +/// why this is now named `LegacyReceiver`. +#[cfg_attr(bootstrap, lang = "receiver")] +#[cfg_attr(not(bootstrap), lang = "legacy_receiver")] +#[unstable(feature = "legacy_receiver_trait", issue = "none")] #[doc(hidden)] -pub trait Receiver { +pub trait LegacyReceiver { // Empty. } -#[unstable(feature = "receiver_trait", issue = "none")] -impl Receiver for &T {} +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for &T {} -#[unstable(feature = "receiver_trait", issue = "none")] -impl Receiver for &mut T {} +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for &mut T {} diff --git a/library/core/src/ops/mod.rs b/library/core/src/ops/mod.rs index 5464bf645d97..c9f47e5daadd 100644 --- a/library/core/src/ops/mod.rs +++ b/library/core/src/ops/mod.rs @@ -168,8 +168,8 @@ pub use self::control_flow::ControlFlow; pub use self::coroutine::{Coroutine, CoroutineState}; #[unstable(feature = "deref_pure_trait", issue = "87121")] pub use self::deref::DerefPure; -#[unstable(feature = "receiver_trait", issue = "none")] -pub use self::deref::Receiver; +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +pub use self::deref::LegacyReceiver; #[stable(feature = "rust1", since = "1.0.0")] pub use self::deref::{Deref, DerefMut}; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index 5d5733d38fca..254b306fcaaf 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -921,7 +921,7 @@ #![stable(feature = "pin", since = "1.33.0")] use crate::hash::{Hash, Hasher}; -use crate::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; +use crate::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver}; #[allow(unused_imports)] use crate::{ cell::{RefCell, UnsafeCell}, @@ -1692,8 +1692,8 @@ impl> DerefMut for Pin { #[unstable(feature = "deref_pure_trait", issue = "87121")] unsafe impl DerefPure for Pin {} -#[unstable(feature = "receiver_trait", issue = "none")] -impl Receiver for Pin {} +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Pin {} #[stable(feature = "pin", since = "1.33.0")] impl fmt::Debug for Pin { diff --git a/tests/codegen/avr/avr-func-addrspace.rs b/tests/codegen/avr/avr-func-addrspace.rs index 7f9a7e6e8110..a2dcb1c09247 100644 --- a/tests/codegen/avr/avr-func-addrspace.rs +++ b/tests/codegen/avr/avr-func-addrspace.rs @@ -18,8 +18,8 @@ pub trait Sized {} #[lang = "copy"] pub trait Copy {} impl Copy for *const T {} -#[lang = "receiver"] -pub trait Receiver {} +#[lang = "legacy_receiver"] +pub trait LegacyReceiver {} #[lang = "tuple_trait"] pub trait Tuple {} diff --git a/tests/codegen/sanitizer/kcfi/emit-type-metadata-trait-objects.rs b/tests/codegen/sanitizer/kcfi/emit-type-metadata-trait-objects.rs index c1967e55e75b..5ab55a467268 100644 --- a/tests/codegen/sanitizer/kcfi/emit-type-metadata-trait-objects.rs +++ b/tests/codegen/sanitizer/kcfi/emit-type-metadata-trait-objects.rs @@ -16,8 +16,8 @@ trait Sized {} #[lang = "copy"] trait Copy {} impl Copy for &T {} -#[lang = "receiver"] -trait Receiver {} +#[lang = "legacy_receiver"] +trait LegacyReceiver {} #[lang = "dispatch_from_dyn"] trait DispatchFromDyn {} impl<'a, T: ?Sized + Unsize, U: ?Sized> DispatchFromDyn<&'a U> for &'a T {} diff --git a/tests/rustdoc-json/impls/auto.rs b/tests/rustdoc-json/impls/auto.rs index e14c935b23b8..f37dae4c1ed4 100644 --- a/tests/rustdoc-json/impls/auto.rs +++ b/tests/rustdoc-json/impls/auto.rs @@ -4,8 +4,8 @@ #[lang = "sized"] trait Sized {} -#[lang = "receiver"] -pub trait Receiver {} +#[lang = "legacy_receiver"] +pub trait LegacyReceiver {} pub auto trait Bar {} diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index 28c8063a9231..fc50560226a7 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -79,10 +79,10 @@ mod prelude { #[lang = "sized"] pub trait Sized {} - #[lang = "receiver"] - pub trait Receiver {} - impl Receiver for &T {} - impl Receiver for &mut T {} + #[lang = "legacy_receiver"] + pub trait LegacyReceiver {} + impl LegacyReceiver for &T {} + impl LegacyReceiver for &mut T {} #[lang = "copy"] pub trait Copy: Sized {} diff --git a/tests/ui/privacy/privacy1.rs b/tests/ui/privacy/privacy1.rs index fcb2108ab5fe..31f396010037 100644 --- a/tests/ui/privacy/privacy1.rs +++ b/tests/ui/privacy/privacy1.rs @@ -12,14 +12,14 @@ pub trait Deref { type Target; } -#[lang="receiver"] -pub trait Receiver: Deref {} +#[lang="legacy_receiver"] +pub trait LegacyReceiver: Deref {} impl<'a, T> Deref for &'a T { type Target = T; } -impl<'a, T> Receiver for &'a T {} +impl<'a, T> LegacyReceiver for &'a T {} mod bar { // shouldn't bring in too much diff --git a/tests/ui/traits/const-traits/const-fns-are-early-bound.rs b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs index b3087349e4d3..b87387f4d5de 100644 --- a/tests/ui/traits/const-traits/const-fns-are-early-bound.rs +++ b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs @@ -82,12 +82,12 @@ trait Copy {} #[lang = "tuple_trait"] trait Tuple {} -#[lang = "receiver"] -trait Receiver {} +#[lang = "legacy_receiver"] +trait LegacyReceiver {} -impl Receiver for &T {} +impl LegacyReceiver for &T {} -impl Receiver for &mut T {} +impl LegacyReceiver for &mut T {} #[stable(feature = "minicore", since = "1.0.0")] pub mod effects { diff --git a/tests/ui/traits/const-traits/effects/minicore.rs b/tests/ui/traits/const-traits/effects/minicore.rs index 1c3c66bc3ce7..9b615450c68f 100644 --- a/tests/ui/traits/const-traits/effects/minicore.rs +++ b/tests/ui/traits/const-traits/effects/minicore.rs @@ -137,12 +137,12 @@ macro_rules! impl_fn_mut_tuple { //impl_fn_mut_tuple!(A B C D); //impl_fn_mut_tuple!(A B C D E); -#[lang = "receiver"] -trait Receiver {} +#[lang = "legacy_receiver"] +trait LegacyReceiver {} -impl Receiver for &T {} +impl LegacyReceiver for &T {} -impl Receiver for &mut T {} +impl LegacyReceiver for &mut T {} #[lang = "destruct"] #[const_trait] @@ -454,7 +454,7 @@ impl /* const */ Deref for Option { } } -impl Receiver for Pin

{} +impl LegacyReceiver for Pin

{} impl Clone for RefCell { fn clone(&self) -> RefCell { From 7aad1a2c4e16155435b3e545aec661c4279f7831 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 16:27:57 +0200 Subject: [PATCH 119/366] Merge closure capture inlay hints into one --- .../crates/ide/src/inlay_hints.rs | 12 ++ .../ide/src/inlay_hints/closure_captures.rs | 119 +++++------------- 2 files changed, 41 insertions(+), 90 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index 97e712356b54..fcf262877dd1 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -475,6 +475,18 @@ impl InlayHintLabel { } } + pub fn append_part(&mut self, part: InlayHintLabelPart) { + if part.linked_location.is_none() && part.tooltip.is_none() { + if let Some(InlayHintLabelPart { text, linked_location: None, tooltip: None }) = + self.parts.last_mut() + { + text.push_str(&part.text); + return; + } + } + self.parts.push(part); + } + pub fn needs_resolve(&self) -> bool { self.parts.iter().any(|part| part.linked_location.is_some() || part.tooltip.is_some()) } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_captures.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_captures.rs index f399bd01d071..628ddc6154c6 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_captures.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_captures.rs @@ -7,7 +7,9 @@ use stdx::{never, TupleExt}; use syntax::ast::{self, AstNode}; use text_edit::{TextRange, TextSize}; -use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind}; +use crate::{ + InlayHint, InlayHintLabel, InlayHintLabelPart, InlayHintPosition, InlayHintsConfig, InlayKind, +}; pub(super) fn hints( acc: &mut Vec, @@ -27,34 +29,27 @@ pub(super) fn hints( return None; } - let move_kw_range = match closure.move_token() { - Some(t) => t.text_range(), + let (range, label) = match closure.move_token() { + Some(t) => (t.text_range(), InlayHintLabel::default()), None => { - let range = closure.syntax().first_token()?.prev_token()?.text_range(); - let range = TextRange::new(range.end() - TextSize::from(1), range.end()); - acc.push(InlayHint { - range, - kind: InlayKind::ClosureCapture, - label: InlayHintLabel::from("move"), - text_edit: None, - position: InlayHintPosition::After, - pad_left: false, - pad_right: false, - resolve_parent: Some(closure.syntax().text_range()), - }); - range + let prev_token = closure.syntax().first_token()?.prev_token()?.text_range(); + ( + TextRange::new(prev_token.end() - TextSize::from(1), prev_token.end()), + InlayHintLabel::from("move"), + ) } }; - acc.push(InlayHint { - range: move_kw_range, + let mut hint = InlayHint { + range, kind: InlayKind::ClosureCapture, - label: InlayHintLabel::from("("), + label, text_edit: None, position: InlayHintPosition::After, pad_left: false, - pad_right: false, - resolve_parent: None, - }); + pad_right: true, + resolve_parent: Some(closure.syntax().text_range()), + }; + hint.label.append_str("("); let last = captures.len() - 1; for (idx, capture) in captures.into_iter().enumerate() { let local = capture.local(); @@ -76,48 +71,20 @@ pub(super) fn hints( if never!(label.is_empty()) { continue; } - let label = InlayHintLabel::simple( - label, - None, - source.name().and_then(|name| { + hint.label.append_part(InlayHintLabelPart { + text: label, + linked_location: source.name().and_then(|name| { name.syntax().original_file_range_opt(sema.db).map(TupleExt::head).map(Into::into) }), - ); - acc.push(InlayHint { - range: move_kw_range, - kind: InlayKind::ClosureCapture, - label, - text_edit: None, - position: InlayHintPosition::After, - pad_left: false, - pad_right: false, - resolve_parent: Some(closure.syntax().text_range()), + tooltip: None, }); if idx != last { - acc.push(InlayHint { - range: move_kw_range, - kind: InlayKind::ClosureCapture, - label: InlayHintLabel::from(", "), - text_edit: None, - position: InlayHintPosition::After, - pad_left: false, - pad_right: false, - resolve_parent: None, - }); + hint.label.append_str(", "); } } - acc.push(InlayHint { - range: move_kw_range, - kind: InlayKind::ClosureCapture, - label: InlayHintLabel::from(")"), - text_edit: None, - position: InlayHintPosition::After, - pad_left: false, - pad_right: true, - resolve_parent: None, - }); - + hint.label.append_str(")"); + acc.push(hint); Some(()) } @@ -147,51 +114,25 @@ fn main() { let mut baz = NonCopy; let qux = &mut NonCopy; || { -// ^ move -// ^ ( -// ^ &foo -// ^ , $ -// ^ bar -// ^ , $ -// ^ baz -// ^ , $ -// ^ qux -// ^ ) +// ^ move(&foo, bar, baz, qux) foo; bar; baz; qux; }; || { -// ^ move -// ^ ( -// ^ &foo -// ^ , $ -// ^ &bar -// ^ , $ -// ^ &baz -// ^ , $ -// ^ &qux -// ^ ) +// ^ move(&foo, &bar, &baz, &qux) &foo; &bar; &baz; &qux; }; || { -// ^ move -// ^ ( -// ^ &mut baz -// ^ ) +// ^ move(&mut baz) &mut baz; }; || { -// ^ move -// ^ ( -// ^ &mut baz -// ^ , $ -// ^ &mut *qux -// ^ ) +// ^ move(&mut baz, &mut *qux) baz = NonCopy; *qux = NonCopy; }; @@ -209,9 +150,7 @@ fn main() { fn main() { let foo = u32; move || { -// ^^^^ ( -// ^^^^ foo -// ^^^^ ) +// ^^^^ (foo) foo; }; } From 7c29f8c5b77abd0dd23a3bcdd50fff7086f8370a Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 16:56:13 +0200 Subject: [PATCH 120/366] Merge adjustment inlay hints into one --- .../crates/ide/src/inlay_hints/adjustment.rs | 228 +++++++----------- 1 file changed, 83 insertions(+), 145 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs index c37c469dff4e..ab44d8c3b500 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs @@ -17,8 +17,8 @@ use syntax::{ }; use crate::{ - AdjustmentHints, AdjustmentHintsMode, InlayHint, InlayHintLabel, InlayHintPosition, - InlayHintsConfig, InlayKind, InlayTooltip, + AdjustmentHints, AdjustmentHintsMode, InlayHint, InlayHintLabel, InlayHintLabelPart, + InlayHintPosition, InlayHintsConfig, InlayKind, InlayTooltip, }; pub(super) fn hints( @@ -64,19 +64,34 @@ pub(super) fn hints( let (postfix, needs_outer_parens, needs_inner_parens) = mode_and_needs_parens_for_adjustment_hints(expr, config.adjustment_hints_mode); - if needs_outer_parens { - acc.push(InlayHint::opening_paren_before( - InlayKind::Adjustment, - expr.syntax().text_range(), - )); + let range = expr.syntax().text_range(); + let mut pre = InlayHint { + range, + position: InlayHintPosition::Before, + pad_left: false, + pad_right: false, + kind: InlayKind::Adjustment, + label: InlayHintLabel::default(), + text_edit: None, + resolve_parent: Some(range), + }; + let mut post = InlayHint { + range, + position: InlayHintPosition::After, + pad_left: false, + pad_right: false, + kind: InlayKind::Adjustment, + label: InlayHintLabel::default(), + text_edit: None, + resolve_parent: Some(range), + }; + + if needs_outer_parens || (postfix && needs_inner_parens) { + pre.label.append_str("("); } if postfix && needs_inner_parens { - acc.push(InlayHint::opening_paren_before( - InlayKind::Adjustment, - expr.syntax().text_range(), - )); - acc.push(InlayHint::closing_paren_after(InlayKind::Adjustment, expr.syntax().text_range())); + post.label.append_str(")"); } let mut iter = if postfix { @@ -138,35 +153,28 @@ pub(super) fn hints( } _ => continue, }; - let label = InlayHintLabel::simple( - if postfix { format!(".{}", text.trim_end()) } else { text.to_owned() }, - Some(InlayTooltip::Markdown(format!( + let label = InlayHintLabelPart { + text: if postfix { format!(".{}", text.trim_end()) } else { text.to_owned() }, + linked_location: None, + tooltip: Some(InlayTooltip::Markdown(format!( "`{}` → `{}` ({coercion} coercion)", source.display(sema.db, file_id.edition()), target.display(sema.db, file_id.edition()), ))), - None, - ); - acc.push(InlayHint { - range: expr.syntax().text_range(), - pad_left: false, - pad_right: false, - position: if postfix { InlayHintPosition::After } else { InlayHintPosition::Before }, - kind: InlayKind::Adjustment, - label, - text_edit: None, - resolve_parent: Some(expr.syntax().text_range()), - }); + }; + if postfix { &mut post } else { &mut pre }.label.append_part(label); } if !postfix && needs_inner_parens { - acc.push(InlayHint::opening_paren_before( - InlayKind::Adjustment, - expr.syntax().text_range(), - )); - acc.push(InlayHint::closing_paren_after(InlayKind::Adjustment, expr.syntax().text_range())); + pre.label.append_str("("); } - if needs_outer_parens { - acc.push(InlayHint::closing_paren_after(InlayKind::Adjustment, expr.syntax().text_range())); + if needs_outer_parens || (!postfix && needs_inner_parens) { + post.label.append_str(")"); + } + if !pre.label.parts.is_empty() { + acc.push(pre); + } + if !post.label.parts.is_empty() { + acc.push(post); } Some(()) } @@ -293,25 +301,19 @@ fn main() { let _: u32 = loop {}; //^^^^^^^ let _: &u32 = &mut 0; - //^^^^^^& - //^^^^^^* + //^^^^^^&* let _: &mut u32 = &mut 0; - //^^^^^^&mut $ - //^^^^^^* + //^^^^^^&mut * let _: *const u32 = &mut 0; - //^^^^^^&raw const $ - //^^^^^^* + //^^^^^^&raw const * let _: *mut u32 = &mut 0; - //^^^^^^&raw mut $ - //^^^^^^* + //^^^^^^&raw mut * let _: fn() = main; //^^^^ let _: unsafe fn() = main; - //^^^^ - //^^^^ + //^^^^ let _: unsafe fn() = main as fn(); - //^^^^^^^^^^^^ - //^^^^^^^^^^^^( + //^^^^^^^^^^^^( //^^^^^^^^^^^^) //^^^^ let _: fn() = || {}; @@ -319,72 +321,51 @@ fn main() { let _: unsafe fn() = || {}; //^^^^^ let _: *const u32 = &mut 0u32 as *mut u32; - //^^^^^^^^^^^^^^^^^^^^^ - //^^^^^^^^^^^^^^^^^^^^^( + //^^^^^^^^^^^^^^^^^^^^^( //^^^^^^^^^^^^^^^^^^^^^) - //^^^^^^^^^&raw mut $ - //^^^^^^^^^* + //^^^^^^^^^&raw mut * let _: &mut [_] = &mut [0; 0]; - //^^^^^^^^^^^ - //^^^^^^^^^^^&mut $ - //^^^^^^^^^^^* + //^^^^^^^^^^^&mut * Struct.consume(); Struct.by_ref(); - //^^^^^^( - //^^^^^^& + //^^^^^^(& //^^^^^^) Struct.by_ref_mut(); - //^^^^^^( - //^^^^^^&mut $ + //^^^^^^(&mut $ //^^^^^^) (&Struct).consume(); //^^^^^^^* (&Struct).by_ref(); - //^^^^^^^& - //^^^^^^^* + //^^^^^^^&* (&mut Struct).consume(); //^^^^^^^^^^^* (&mut Struct).by_ref(); - //^^^^^^^^^^^& - //^^^^^^^^^^^* + //^^^^^^^^^^^&* (&mut Struct).by_ref_mut(); - //^^^^^^^^^^^&mut $ - //^^^^^^^^^^^* + //^^^^^^^^^^^&mut * // Check that block-like expressions don't duplicate hints let _: &mut [u32] = (&mut []); - //^^^^^^^ - //^^^^^^^&mut $ - //^^^^^^^* + //^^^^^^^&mut * let _: &mut [u32] = { &mut [] }; - //^^^^^^^ - //^^^^^^^&mut $ - //^^^^^^^* + //^^^^^^^&mut * let _: &mut [u32] = unsafe { &mut [] }; - //^^^^^^^ - //^^^^^^^&mut $ - //^^^^^^^* + //^^^^^^^&mut * let _: &mut [u32] = if true { &mut [] - //^^^^^^^ - //^^^^^^^&mut $ - //^^^^^^^* + //^^^^^^^&mut * } else { loop {} //^^^^^^^ }; let _: &mut [u32] = match () { () => &mut [] }; - //^^^^^^^ - //^^^^^^^&mut $ - //^^^^^^^* + //^^^^^^^&mut * let _: &mut dyn Fn() = &mut || (); - //^^^^^^^^^^ - //^^^^^^^^^^&mut $ - //^^^^^^^^^^* + //^^^^^^^^^^&mut * () == (); // ^^& // ^^& @@ -393,16 +374,13 @@ fn main() { // ^^^^& let closure: dyn Fn = || (); closure(); - //^^^^^^^( - //^^^^^^^& + //^^^^^^^(& //^^^^^^^) Struct[0]; - //^^^^^^( - //^^^^^^& + //^^^^^^(& //^^^^^^) &mut Struct[0]; - //^^^^^^( - //^^^^^^&mut $ + //^^^^^^(&mut $ //^^^^^^) } @@ -442,72 +420,46 @@ fn main() { (&Struct).consume(); //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* + //^^^^^^^).* (&Struct).by_ref(); //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* - //^^^^^^^.& + //^^^^^^^).*.& (&mut Struct).consume(); //^^^^^^^^^^^( - //^^^^^^^^^^^) - //^^^^^^^^^^^.* + //^^^^^^^^^^^).* (&mut Struct).by_ref(); //^^^^^^^^^^^( - //^^^^^^^^^^^) - //^^^^^^^^^^^.* - //^^^^^^^^^^^.& + //^^^^^^^^^^^).*.& (&mut Struct).by_ref_mut(); //^^^^^^^^^^^( - //^^^^^^^^^^^) - //^^^^^^^^^^^.* - //^^^^^^^^^^^.&mut + //^^^^^^^^^^^).*.&mut // Check that block-like expressions don't duplicate hints let _: &mut [u32] = (&mut []); //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* - //^^^^^^^.&mut - //^^^^^^^. + //^^^^^^^).*.&mut. let _: &mut [u32] = { &mut [] }; //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* - //^^^^^^^.&mut - //^^^^^^^. + //^^^^^^^).*.&mut. let _: &mut [u32] = unsafe { &mut [] }; //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* - //^^^^^^^.&mut - //^^^^^^^. + //^^^^^^^).*.&mut. let _: &mut [u32] = if true { &mut [] //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* - //^^^^^^^.&mut - //^^^^^^^. + //^^^^^^^).*.&mut. } else { loop {} //^^^^^^^. }; let _: &mut [u32] = match () { () => &mut [] }; //^^^^^^^( - //^^^^^^^) - //^^^^^^^.* - //^^^^^^^.&mut - //^^^^^^^. + //^^^^^^^).*.&mut. let _: &mut dyn Fn() = &mut || (); //^^^^^^^^^^( - //^^^^^^^^^^) - //^^^^^^^^^^.* - //^^^^^^^^^^.&mut - //^^^^^^^^^^. + //^^^^^^^^^^).*.&mut. () == (); // ^^.& // ^^.& @@ -619,9 +571,7 @@ fn or_else() { r#" unsafe fn enabled() { f(&&()); - //^^^^& - //^^^^* - //^^^^* + //^^^^&** } fn disabled() { @@ -633,9 +583,7 @@ fn mixed() { unsafe { f(&&()); - //^^^^& - //^^^^* - //^^^^* + //^^^^&** } } @@ -644,9 +592,7 @@ const _: () = { unsafe { f(&&()); - //^^^^& - //^^^^* - //^^^^* + //^^^^&** } }; @@ -655,18 +601,14 @@ static STATIC: () = { unsafe { f(&&()); - //^^^^& - //^^^^* - //^^^^* + //^^^^&** } }; enum E { Disable = { f(&&()); 0 }, Enable = unsafe { f(&&()); 1 }, - //^^^^& - //^^^^* - //^^^^* + //^^^^&** } const fn f(_: &()) {} @@ -692,8 +634,7 @@ fn a() { _ = Struct.by_ref(); _ = unsafe { Struct.by_ref() }; - //^^^^^^( - //^^^^^^& + //^^^^^^(& //^^^^^^) } "#, @@ -726,10 +667,7 @@ trait T {} fn hello(it: &&[impl T]) { it.len(); - //^^( - //^^& - //^^* - //^^* + //^^(&** //^^) } "#, From 770df7ffbb75b0ab53a50c2612000e2374789a92 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 22 Oct 2024 17:00:30 +0200 Subject: [PATCH 121/366] Merge binding_mode inlay hints into one --- .../ide/src/inlay_hints/binding_mode.rs | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs index d1c0677863db..beba2ad748cf 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs @@ -2,13 +2,15 @@ //! ```no_run //! let /* & */ (/* ref */ x,) = &(0,); //! ``` +use std::mem; + use hir::Mutability; use ide_db::famous_defs::FamousDefs; use span::EditionedFileId; use syntax::ast::{self, AstNode}; -use crate::{InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind}; +use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind}; pub(super) fn hints( acc: &mut Vec, @@ -42,7 +44,18 @@ pub(super) fn hints( }, |it| it.syntax().text_range(), ); + let mut hint = InlayHint { + range, + kind: InlayKind::BindingMode, + label: InlayHintLabel::default(), + text_edit: None, + position: InlayHintPosition::Before, + pad_left: false, + pad_right: false, + resolve_parent: Some(pat.syntax().text_range()), + }; let pattern_adjustments = sema.pattern_adjustments(pat); + let mut was_mut_last = false; pattern_adjustments.iter().for_each(|ty| { let reference = ty.is_reference(); let mut_reference = ty.is_mutable_reference(); @@ -51,17 +64,15 @@ pub(super) fn hints( (true, false) => "&", _ => return, }; - acc.push(InlayHint { - range, - kind: InlayKind::BindingMode, - label: r.into(), - text_edit: None, - position: InlayHintPosition::Before, - pad_left: false, - pad_right: mut_reference, - resolve_parent: Some(pat.syntax().text_range()), - }); + if mem::replace(&mut was_mut_last, mut_reference) { + hint.label.append_str(" "); + } + hint.label.append_str(r); }); + hint.pad_right = was_mut_last; + if !hint.label.parts.is_empty() { + acc.push(hint); + } match pat { ast::Pat::IdentPat(pat) if pat.ref_token().is_none() && pat.mut_token().is_none() => { let bm = sema.binding_mode_of_pat(pat)?; @@ -117,6 +128,13 @@ fn __( (x,): &mut (u32,) //^^^^&mut //^ ref mut + (x,): &mut &mut (u32,) + //^^^^&mut &mut + //^ ref mut + (x,): &&(u32,) + //^^^^&& + //^ ref + ) { let (x,) = (0,); let (x,) = &(0,); From c8391802afc158759dfe234e22f665d39091ea8d Mon Sep 17 00:00:00 2001 From: Laiho Date: Sat, 19 Oct 2024 16:49:07 +0300 Subject: [PATCH 122/366] better default capacity for str::replace --- library/alloc/src/str.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index 52ceb8b45f91..26c1ba2a5c48 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -269,8 +269,7 @@ impl str { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn replace(&self, from: P, to: &str) -> String { - // Fast path for ASCII to ASCII case. - + // Fast path for replacing a single ASCII character with another. if let Some(from_byte) = match from.as_utf8_pattern() { Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte), Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()), @@ -280,8 +279,13 @@ impl str { return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) }; } } - - let mut result = String::new(); + // Set result capacity to self.len() when from.len() <= to.len() + let default_capacity = match from.as_utf8_pattern() { + Some(Utf8Pattern::StringPattern(s)) if s.len() <= to.len() => self.len(), + Some(Utf8Pattern::CharPattern(c)) if c.len_utf8() <= to.len() => self.len(), + _ => 0, + }; + let mut result = String::with_capacity(default_capacity); let mut last_end = 0; for (start, part) in self.match_indices(from) { result.push_str(unsafe { self.get_unchecked(last_end..start) }); From 73238301f452a801fc66b63eaa8fb463bfbac0d1 Mon Sep 17 00:00:00 2001 From: Orion Gonzalez Date: Thu, 3 Oct 2024 03:15:32 +0200 Subject: [PATCH 123/366] add an option for a custom differ --- src/tools/compiletest/src/common.rs | 2 ++ src/tools/compiletest/src/lib.rs | 1 + 2 files changed, 3 insertions(+) diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index ff059940f7cc..5e50e227dede 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -387,6 +387,8 @@ pub struct Config { /// True if the profiler runtime is enabled for this target. /// Used by the "needs-profiler-runtime" directive in test files. pub profiler_runtime: bool, + + pub diff_command: Option, } impl Config { diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index 7d6ede9bcdac..5046eea63e25 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -364,6 +364,7 @@ pub fn parse_config(args: Vec) -> Config { git_merge_commit_email: matches.opt_str("git-merge-commit-email").unwrap(), profiler_runtime: matches.opt_present("profiler-runtime"), + diff_command: env::var("COMPILETEST_DIFF_TOOL").ok(), } } From ef4325eb85766f15916520ee8f6150e93cb45064 Mon Sep 17 00:00:00 2001 From: Orion Gonzalez Date: Thu, 3 Oct 2024 03:21:45 +0200 Subject: [PATCH 124/366] implemented custom differ --- config.example.toml | 3 + src/bootstrap/src/core/build_steps/test.rs | 3 + src/bootstrap/src/core/config/config.rs | 6 ++ src/tools/compiletest/src/lib.rs | 6 +- src/tools/compiletest/src/runtest.rs | 86 ++++++++++++---------- 5 files changed, 64 insertions(+), 40 deletions(-) diff --git a/config.example.toml b/config.example.toml index 168ac353cff7..b155e4731b06 100644 --- a/config.example.toml +++ b/config.example.toml @@ -419,6 +419,9 @@ # passed to cargo invocations. #jobs = 0 +# What custom diff tool to use for displaying compiletest tests. +#display-diff-tool = "difft --color=always --background=light --display=side-by-side" + # ============================================================================= # General install configuration options # ============================================================================= diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index e25b571acbac..c6c40b0f7f7d 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1834,6 +1834,9 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the if builder.config.cmd.only_modified() { cmd.arg("--only-modified"); } + if let Some(display_diff_tool) = &builder.config.display_diff_tool { + cmd.arg("--display-diff-tool").arg(display_diff_tool); + } let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] }; flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests)); diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index aeb81b146382..ba2ec8181f99 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -368,6 +368,9 @@ pub struct Config { /// The paths to work with. For example: with `./x check foo bar` we get /// `paths=["foo", "bar"]`. pub paths: Vec, + + /// What custom diff tool to use for displaying compiletest tests. + pub display_diff_tool: Option, } #[derive(Clone, Debug, Default)] @@ -892,6 +895,7 @@ define_config! { android_ndk: Option = "android-ndk", optimized_compiler_builtins: Option = "optimized-compiler-builtins", jobs: Option = "jobs", + display_diff_tool: Option = "display-diff-tool", } } @@ -1512,6 +1516,7 @@ impl Config { android_ndk, optimized_compiler_builtins, jobs, + display_diff_tool, } = toml.build.unwrap_or_default(); config.jobs = Some(threads_from_config(flags.jobs.unwrap_or(jobs.unwrap_or(0)))); @@ -2158,6 +2163,7 @@ impl Config { config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None); config.optimized_compiler_builtins = optimized_compiler_builtins.unwrap_or(config.channel != "dev"); + config.display_diff_tool = display_diff_tool; let download_rustc = config.download_rustc_commit.is_some(); // See https://github.com/rust-lang/compiler-team/issues/326 diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index 5046eea63e25..debc59109e74 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -175,7 +175,9 @@ pub fn parse_config(args: Vec) -> Config { "git-merge-commit-email", "email address used for finding merge commits", "EMAIL", - ); + ) + .optopt("", "display-diff-tool", "What custom diff tool to use for displaying compiletest tests.", "COMMAND") + ; let (argv0, args_) = args.split_first().unwrap(); if args.len() == 1 || args[1] == "-h" || args[1] == "--help" { @@ -364,7 +366,7 @@ pub fn parse_config(args: Vec) -> Config { git_merge_commit_email: matches.opt_str("git-merge-commit-email").unwrap(), profiler_runtime: matches.opt_present("profiler-runtime"), - diff_command: env::var("COMPILETEST_DIFF_TOOL").ok(), + diff_command: matches.opt_str("display-diff-tool"), } } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 36c5106ddad0..4aca3b34313d 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2459,7 +2459,7 @@ impl<'test> TestCx<'test> { } } - fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize { + fn compare_output(&self, stream: &str, actual: &str, expected: &str) -> usize { let are_different = match (self.force_color_svg(), expected.find('\n'), actual.find('\n')) { // FIXME: We ignore the first line of SVG files // because the width parameter is non-deterministic. @@ -2499,56 +2499,66 @@ impl<'test> TestCx<'test> { (expected, actual) }; - if !self.config.bless { - if expected.is_empty() { - println!("normalized {}:\n{}\n", kind, actual); - } else { - println!("diff of {}:\n", kind); - print!("{}", write_diff(expected, actual, 3)); - } - } - - let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str()); - let output_file = self + // Write the actual output to a file in build/ + let test_name = self.config.compare_mode.as_ref().map_or("", |m| m.to_str()); + let actual_path = self .output_base_name() .with_extra_extension(self.revision.unwrap_or("")) - .with_extra_extension(mode) - .with_extra_extension(kind); + .with_extra_extension(test_name) + .with_extra_extension(stream); - let mut files = vec![output_file]; - if self.config.bless { + if let Err(err) = fs::write(&actual_path, &actual) { + self.fatal(&format!("failed to write {stream} to `{actual_path:?}`: {err}",)); + } + println!("Saved the actual {stream} to {actual_path:?}"); + + let expected_path = + expected_output_path(self.testpaths, self.revision, &self.config.compare_mode, stream); + + if !self.config.bless { + if expected.is_empty() { + println!("normalized {}:\n{}\n", stream, actual); + } else { + println!("diff of {stream}:\n"); + if let Some(diff_command) = self.config.diff_command.as_deref() { + let mut args = diff_command.split_whitespace(); + let name = args.next().unwrap(); + match Command::new(name) + .args(args) + .args([&expected_path, &actual_path]) + .output() + { + Err(err) => { + self.fatal(&format!( + "failed to call custom diff command `{diff_command}`: {err}" + )); + } + Ok(output) => { + let output = String::from_utf8_lossy_owned(output.stdout).unwrap(); + print!("{output}"); + } + } + } else { + print!("{}", write_diff(expected, actual, 3)); + } + } + } else { // Delete non-revision .stderr/.stdout file if revisions are used. // Without this, we'd just generate the new files and leave the old files around. if self.revision.is_some() { let old = - expected_output_path(self.testpaths, None, &self.config.compare_mode, kind); + expected_output_path(self.testpaths, None, &self.config.compare_mode, stream); self.delete_file(&old); } - files.push(expected_output_path( - self.testpaths, - self.revision, - &self.config.compare_mode, - kind, - )); - } - for output_file in &files { - if actual.is_empty() { - self.delete_file(output_file); - } else if let Err(err) = fs::write(&output_file, &actual) { - self.fatal(&format!( - "failed to write {} to `{}`: {}", - kind, - output_file.display(), - err, - )); + if let Err(err) = fs::write(&expected_path, &actual) { + self.fatal(&format!("failed to write {stream} to `{expected_path:?}`: {err}")); } + println!("Blessing the {stream} of {test_name} in {expected_path:?}"); } - println!("\nThe actual {0} differed from the expected {0}.", kind); - for output_file in files { - println!("Actual {} saved to {}", kind, output_file.display()); - } + println!("\nThe actual {0} differed from the expected {0}.", stream); + if self.config.bless { 0 } else { 1 } } From 37ffb94093828676d88178063c8930ea83a29386 Mon Sep 17 00:00:00 2001 From: Orion Gonzalez Date: Thu, 3 Oct 2024 17:11:01 +0200 Subject: [PATCH 125/366] update CONFIG_CHANGE_HISTORY --- src/bootstrap/src/utils/change_tracker.rs | 5 +++++ src/tools/compiletest/src/lib.rs | 8 ++++++-- src/tools/compiletest/src/runtest.rs | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 9169bc90a45d..fac24572a878 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -280,4 +280,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "Allow setting `--jobs` in config.toml with `build.jobs`.", }, + ChangeInfo { + change_id: 131181, + severity: ChangeSeverity::Info, + summary: "New option `build.compiletest-diff-tool` that adds support for a custom differ for compiletest", + }, ]; diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index debc59109e74..a008410e34bd 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -176,8 +176,12 @@ pub fn parse_config(args: Vec) -> Config { "email address used for finding merge commits", "EMAIL", ) - .optopt("", "display-diff-tool", "What custom diff tool to use for displaying compiletest tests.", "COMMAND") - ; + .optopt( + "", + "display-diff-tool", + "What custom diff tool to use for displaying compiletest tests.", + "COMMAND", + ); let (argv0, args_) = args.split_first().unwrap(); if args.len() == 1 || args[1] == "-h" || args[1] == "--help" { diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 4aca3b34313d..7db37af60d2c 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2534,7 +2534,7 @@ impl<'test> TestCx<'test> { )); } Ok(output) => { - let output = String::from_utf8_lossy_owned(output.stdout).unwrap(); + let output = String::from_utf8_lossy(&output.stdout); print!("{output}"); } } From c8de61b50de7ca755b704c0314ff3a119be01ae6 Mon Sep 17 00:00:00 2001 From: Orion Gonzalez Date: Fri, 4 Oct 2024 10:54:34 +0200 Subject: [PATCH 126/366] s/display-diff-tool/compiletest-diff-tool/ --- config.example.toml | 2 +- src/bootstrap/src/core/build_steps/test.rs | 4 ++-- src/bootstrap/src/core/config/config.rs | 10 +++++----- src/tools/compiletest/src/common.rs | 1 + src/tools/compiletest/src/lib.rs | 4 ++-- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/config.example.toml b/config.example.toml index b155e4731b06..77efdb6d392e 100644 --- a/config.example.toml +++ b/config.example.toml @@ -420,7 +420,7 @@ #jobs = 0 # What custom diff tool to use for displaying compiletest tests. -#display-diff-tool = "difft --color=always --background=light --display=side-by-side" +#compiletest-diff-tool = "difft --color=always --background=light --display=side-by-side" # ============================================================================= # General install configuration options diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index c6c40b0f7f7d..f671b0dcfe6f 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1834,8 +1834,8 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the if builder.config.cmd.only_modified() { cmd.arg("--only-modified"); } - if let Some(display_diff_tool) = &builder.config.display_diff_tool { - cmd.arg("--display-diff-tool").arg(display_diff_tool); + if let Some(compiletest_diff_tool) = &builder.config.compiletest_diff_tool { + cmd.arg("--compiletest-diff-tool").arg(compiletest_diff_tool); } let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] }; diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index ba2ec8181f99..ec3a0a6de847 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -369,8 +369,8 @@ pub struct Config { /// `paths=["foo", "bar"]`. pub paths: Vec, - /// What custom diff tool to use for displaying compiletest tests. - pub display_diff_tool: Option, + /// Command for visual diff display, e.g. `diff-tool --color=always`. + pub compiletest_diff_tool: Option, } #[derive(Clone, Debug, Default)] @@ -895,7 +895,7 @@ define_config! { android_ndk: Option = "android-ndk", optimized_compiler_builtins: Option = "optimized-compiler-builtins", jobs: Option = "jobs", - display_diff_tool: Option = "display-diff-tool", + compiletest_diff_tool: Option = "compiletest-diff-tool", } } @@ -1516,7 +1516,7 @@ impl Config { android_ndk, optimized_compiler_builtins, jobs, - display_diff_tool, + compiletest_diff_tool, } = toml.build.unwrap_or_default(); config.jobs = Some(threads_from_config(flags.jobs.unwrap_or(jobs.unwrap_or(0)))); @@ -2163,7 +2163,7 @@ impl Config { config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None); config.optimized_compiler_builtins = optimized_compiler_builtins.unwrap_or(config.channel != "dev"); - config.display_diff_tool = display_diff_tool; + config.compiletest_diff_tool = compiletest_diff_tool; let download_rustc = config.download_rustc_commit.is_some(); // See https://github.com/rust-lang/compiler-team/issues/326 diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index 5e50e227dede..5070f016d3c6 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -388,6 +388,7 @@ pub struct Config { /// Used by the "needs-profiler-runtime" directive in test files. pub profiler_runtime: bool, + /// Command for visual diff display, e.g. `diff-tool --color=always`. pub diff_command: Option, } diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index a008410e34bd..0f514db42bf9 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -178,7 +178,7 @@ pub fn parse_config(args: Vec) -> Config { ) .optopt( "", - "display-diff-tool", + "compiletest-diff-tool", "What custom diff tool to use for displaying compiletest tests.", "COMMAND", ); @@ -370,7 +370,7 @@ pub fn parse_config(args: Vec) -> Config { git_merge_commit_email: matches.opt_str("git-merge-commit-email").unwrap(), profiler_runtime: matches.opt_present("profiler-runtime"), - diff_command: matches.opt_str("display-diff-tool"), + diff_command: matches.opt_str("compiletest-diff-tool"), } } From 28095bc54142f9fbfd4a2cac0a7fadf0ae6e9b9e Mon Sep 17 00:00:00 2001 From: Orion Gonzalez Date: Fri, 4 Oct 2024 10:56:08 +0200 Subject: [PATCH 127/366] real default value --- config.example.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.example.toml b/config.example.toml index 77efdb6d392e..a52968e9a414 100644 --- a/config.example.toml +++ b/config.example.toml @@ -420,7 +420,7 @@ #jobs = 0 # What custom diff tool to use for displaying compiletest tests. -#compiletest-diff-tool = "difft --color=always --background=light --display=side-by-side" +#compiletest-diff-tool = # ============================================================================= # General install configuration options From 983383f957d219d08303900f28fcee4d9dd1e291 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Tue, 22 Oct 2024 20:27:09 +0300 Subject: [PATCH 128/366] Add test for tuple struct destructuring assignment where the path comes from a macro --- .../crates/hir-def/src/body/tests.rs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/tests.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/tests.rs index dd3e79c874d8..3b29d98d198f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/tests.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/tests.rs @@ -370,3 +370,37 @@ fn f(a: i32, b: u32) -> String { }"#]] .assert_eq(&body.pretty_print(&db, def, Edition::CURRENT)) } + +#[test] +fn destructuring_assignment_tuple_macro() { + // This is a funny one. `let m!()() = Bar()` is an error in rustc, because `m!()()` isn't a valid pattern, + // but in destructuring assignment it is valid, because `m!()()` is a valid expression, and destructuring + // assignments start their lives as expressions. So we have to do the same. + + let (db, body, def) = lower( + r#" +struct Bar(); + +macro_rules! m { + () => { Bar }; +} + +fn foo() { + m!()() = Bar(); +} +"#, + ); + + let (_, source_map) = db.body_with_source_map(def); + assert_eq!(source_map.diagnostics(), &[]); + + for (_, def_map) in body.blocks(&db) { + assert_eq!(def_map.diagnostics(), &[]); + } + + expect![[r#" + fn foo() -> () { + Bar() = Bar(); + }"#]] + .assert_eq(&body.pretty_print(&db, def, Edition::CURRENT)) +} From 1909668a88fdea755f82d143fca00e6ab5394cbe Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Tue, 22 Oct 2024 10:47:42 -0700 Subject: [PATCH 129/366] relnotes: fix stabilizations of `assume_init` Ref: https://github.com/rust-lang/blog.rust-lang.org/pull/1416 --- RELEASES.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index ac72a1d885cb..40ddba6dbc52 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -68,15 +68,15 @@ Stabilized APIs - [`impl Default for std::collections::vec_deque::Iter`](https://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.Iter.html#impl-Default-for-Iter%3C'_,+T%3E) - [`impl Default for std::collections::vec_deque::IterMut`](https://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.IterMut.html#impl-Default-for-IterMut%3C'_,+T%3E) - [`Rc::new_uninit`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new_uninit) -- [`Rc::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init) +- [`Rc>::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init) - [`Rc<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new_uninit_slice) - [`Rc<[MaybeUninit]>::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init-1) - [`Arc::new_uninit`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.new_uninit) -- [`Arc::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init) +- [`Arc>::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init) - [`Arc<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.new_uninit_slice) - [`Arc<[MaybeUninit]>::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init-1) - [`Box::new_uninit`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.new_uninit) -- [`Box::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init) +- [`Box>::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init) - [`Box<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.new_uninit_slice) - [`Box<[MaybeUninit]>::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init-1) - [`core::arch::x86_64::_bextri_u64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bextri_u64.html) From 7ee25a0d70bb92b9e55c75c84775a3b6c378a49a Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Mon, 7 Oct 2024 23:02:02 +0300 Subject: [PATCH 130/366] Implement semitransparent hygiene Or macro_rules hygiene, or mixed site hygiene. In other words, hygiene for variables and labels but not items. The realization that made me implement this was that while "full" hygiene (aka. def site hygiene) is really hard for us to implement, and will likely involve intrusive changes and performance losses, since every `Name` will have to carry hygiene, mixed site hygiene is very local: it applies only to bodies, and we very well can save it in a side map with minor losses. This fixes one diagnostic in r-a that was about `izip!()` using hygiene (yay!) but it introduces a huge number of others, because of #18262. Up until now this issue wasn't a major problem because it only affected few cases, but with hygiene identifiers referred by macros like that are not resolved at all. The next commit will fix that. --- src/tools/rust-analyzer/Cargo.lock | 1 + .../rust-analyzer/crates/hir-def/Cargo.toml | 1 + .../rust-analyzer/crates/hir-def/src/body.rs | 82 +++++-- .../crates/hir-def/src/body/lower.rs | 206 ++++++++++++++---- .../crates/hir-def/src/body/scope.rs | 23 +- .../crates/hir-def/src/expander.rs | 4 + .../crates/hir-def/src/resolver.rs | 18 +- .../crates/hir-expand/src/name.rs | 2 + .../crates/hir-ty/src/consteval.rs | 4 +- .../crates/hir-ty/src/diagnostics/expr.rs | 10 +- .../hir-ty/src/diagnostics/unsafe_check.rs | 3 +- .../rust-analyzer/crates/hir-ty/src/infer.rs | 4 +- .../crates/hir-ty/src/infer/closure.rs | 10 +- .../crates/hir-ty/src/infer/expr.rs | 6 +- .../crates/hir-ty/src/infer/path.rs | 3 +- .../crates/hir-ty/src/mir/eval.rs | 2 + .../crates/hir-ty/src/mir/lower.rs | 7 +- .../crates/hir-ty/src/mir/lower/as_place.rs | 4 +- .../hir-ty/src/mir/lower/pattern_matching.rs | 3 +- .../crates/hir-ty/src/tests/simple.rs | 17 ++ .../rust-analyzer/crates/hir/src/semantics.rs | 13 +- .../crates/hir/src/source_analyzer.rs | 75 ++++--- .../crates/ide/src/goto_definition.rs | 20 ++ 23 files changed, 394 insertions(+), 124 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index fd569571b38b..368e1828953b 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -556,6 +556,7 @@ dependencies = [ "syntax-bridge", "test-fixture", "test-utils", + "text-size", "tracing", "triomphe", "tt", diff --git a/src/tools/rust-analyzer/crates/hir-def/Cargo.toml b/src/tools/rust-analyzer/crates/hir-def/Cargo.toml index c8ba5da449e9..375f18d9fe1f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/Cargo.toml +++ b/src/tools/rust-analyzer/crates/hir-def/Cargo.toml @@ -29,6 +29,7 @@ smallvec.workspace = true hashbrown.workspace = true triomphe.workspace = true rustc_apfloat = "0.2.0" +text-size.workspace = true ra-ap-rustc_parse_format.workspace = true ra-ap-rustc_abi.workspace = true diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body.rs b/src/tools/rust-analyzer/crates/hir-def/src/body.rs index 684eaf1c3b08..27fe5c87ccba 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body.rs @@ -33,6 +33,22 @@ use crate::{ BlockId, DefWithBodyId, HasModule, Lookup, }; +/// A wrapper around [`span::SyntaxContextId`] that is intended only for comparisons. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct HygieneId(span::SyntaxContextId); + +impl HygieneId { + pub const ROOT: Self = Self(span::SyntaxContextId::ROOT); + + pub fn new(ctx: span::SyntaxContextId) -> Self { + Self(ctx) + } + + fn is_root(self) -> bool { + self.0.is_root() + } +} + /// The body of an item (function, const etc.). #[derive(Debug, Eq, PartialEq)] pub struct Body { @@ -55,6 +71,22 @@ pub struct Body { pub body_expr: ExprId, /// Block expressions in this body that may contain inner items. block_scopes: Vec, + + /// A map from binding to its hygiene ID. + /// + /// Bindings that don't come from macro expansion are not allocated to save space, so not all bindings appear here. + /// If a binding does not appear here it has `SyntaxContextId::ROOT`. + /// + /// Note that this may not be the direct `SyntaxContextId` of the binding's expansion, because transparent + /// expansions are attributed to their parent expansion (recursively). + binding_hygiene: FxHashMap, + /// A map from an variable usages to their hygiene ID. + /// + /// Expressions that can be recorded here are single segment path, although not all single segments path refer + /// to variables and have hygiene (some refer to items, we don't know at this stage). + expr_hygiene: FxHashMap, + /// A map from a destructuring assignment possible variable usages to their hygiene ID. + pat_hygiene: FxHashMap, } pub type ExprPtr = AstPtr; @@ -107,10 +139,11 @@ pub struct BodySourceMap { field_map_back: FxHashMap, pat_field_map_back: FxHashMap, + // FIXME: Make this a sane struct. template_map: Option< Box<( // format_args! - FxHashMap>, + FxHashMap)>, // asm! FxHashMap>>, )>, @@ -268,6 +301,9 @@ impl Body { pats, bindings, binding_owners, + binding_hygiene, + expr_hygiene, + pat_hygiene, } = self; block_scopes.shrink_to_fit(); exprs.shrink_to_fit(); @@ -275,6 +311,9 @@ impl Body { pats.shrink_to_fit(); bindings.shrink_to_fit(); binding_owners.shrink_to_fit(); + binding_hygiene.shrink_to_fit(); + expr_hygiene.shrink_to_fit(); + pat_hygiene.shrink_to_fit(); } pub fn walk_bindings_in_pat(&self, pat_id: PatId, mut f: impl FnMut(BindingId)) { @@ -467,6 +506,25 @@ impl Body { } }); } + + fn binding_hygiene(&self, binding: BindingId) -> HygieneId { + self.binding_hygiene.get(&binding).copied().unwrap_or(HygieneId::ROOT) + } + + pub fn expr_path_hygiene(&self, expr: ExprId) -> HygieneId { + self.expr_hygiene.get(&expr).copied().unwrap_or(HygieneId::ROOT) + } + + pub fn pat_path_hygiene(&self, pat: PatId) -> HygieneId { + self.pat_hygiene.get(&pat).copied().unwrap_or(HygieneId::ROOT) + } + + pub fn expr_or_pat_path_hygiene(&self, id: ExprOrPatId) -> HygieneId { + match id { + ExprOrPatId::ExprId(id) => self.expr_path_hygiene(id), + ExprOrPatId::PatId(id) => self.pat_path_hygiene(id), + } + } } impl Default for Body { @@ -481,6 +539,9 @@ impl Default for Body { block_scopes: Default::default(), binding_owners: Default::default(), self_param: Default::default(), + binding_hygiene: Default::default(), + expr_hygiene: Default::default(), + pat_hygiene: Default::default(), } } } @@ -594,13 +655,11 @@ impl BodySourceMap { pub fn implicit_format_args( &self, node: InFile<&ast::FormatArgsExpr>, - ) -> Option<&[(syntax::TextRange, Name)]> { + ) -> Option<(HygieneId, &[(syntax::TextRange, Name)])> { let src = node.map(AstPtr::new).map(AstPtr::upcast::); - self.template_map - .as_ref()? - .0 - .get(&self.expr_map.get(&src)?.as_expr()?) - .map(std::ops::Deref::deref) + let (hygiene, names) = + self.template_map.as_ref()?.0.get(&self.expr_map.get(&src)?.as_expr()?)?; + Some((*hygiene, &**names)) } pub fn asm_template_args( @@ -649,13 +708,4 @@ impl BodySourceMap { diagnostics.shrink_to_fit(); binding_definitions.shrink_to_fit(); } - - pub fn template_map( - &self, - ) -> Option<&( - FxHashMap, Vec<(tt::TextRange, Name)>>, - FxHashMap, Vec>>, - )> { - self.template_map.as_deref() - } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index 4b74028b83a6..cdc7b141717f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -9,6 +9,7 @@ use base_db::CrateId; use either::Either; use hir_expand::{ name::{AsName, Name}, + span_map::{ExpansionSpanMap, SpanMap}, InFile, }; use intern::{sym, Interned, Symbol}; @@ -22,10 +23,11 @@ use syntax::{ }, AstNode, AstPtr, AstToken as _, SyntaxNodePtr, }; +use text_size::TextSize; use triomphe::Arc; use crate::{ - body::{Body, BodyDiagnostic, BodySourceMap, ExprPtr, LabelPtr, PatPtr}, + body::{Body, BodyDiagnostic, BodySourceMap, ExprPtr, HygieneId, LabelPtr, PatPtr}, builtin_type::BuiltinUint, data::adt::StructKind, db::DefDatabase, @@ -60,6 +62,17 @@ pub(super) fn lower( krate: CrateId, is_async_fn: bool, ) -> (Body, BodySourceMap) { + // We cannot leave the root span map empty and let any identifier from it be treated as root, + // because when inside nested macros `SyntaxContextId`s from the outer macro will be interleaved + // with the inner macro, and that will cause confusion because they won't be the same as `ROOT` + // even though they should be the same. Also, when the body comes from multiple expansions, their + // hygiene is different. + let span_map = expander.current_file_id().macro_file().map(|_| { + let SpanMap::ExpansionSpanMap(span_map) = expander.span_map(db) else { + panic!("in a macro file there should be `ExpansionSpanMap`"); + }; + Arc::clone(span_map) + }); ExprCollector { db, owner, @@ -74,6 +87,7 @@ pub(super) fn lower( label_ribs: Vec::new(), current_binding_owner: None, awaitable_context: None, + current_span_map: span_map, } .collect(params, body, is_async_fn) } @@ -90,6 +104,8 @@ struct ExprCollector<'a> { is_lowering_coroutine: bool, + current_span_map: Option>, + current_try_block_label: Option, // points to the expression that a try expression will target (replaces current_try_block_label) // catch_scope: Option, @@ -109,14 +125,14 @@ struct ExprCollector<'a> { struct LabelRib { kind: RibKind, // Once we handle macro hygiene this will need to be a map - label: Option<(Name, LabelId)>, + label: Option<(Name, LabelId, HygieneId)>, } impl LabelRib { fn new(kind: RibKind) -> Self { LabelRib { kind, label: None } } - fn new_normal(label: (Name, LabelId)) -> Self { + fn new_normal(label: (Name, LabelId, HygieneId)) -> Self { LabelRib { kind: RibKind::Normal, label: Some(label) } } } @@ -145,7 +161,7 @@ enum Awaitable { #[derive(Debug, Default)] struct BindingList { - map: FxHashMap, + map: FxHashMap<(Name, HygieneId), BindingId>, is_used: FxHashMap, reject_new: bool, } @@ -155,9 +171,16 @@ impl BindingList { &mut self, ec: &mut ExprCollector<'_>, name: Name, + hygiene: HygieneId, mode: BindingAnnotation, ) -> BindingId { - let id = *self.map.entry(name).or_insert_with_key(|n| ec.alloc_binding(n.clone(), mode)); + let id = *self.map.entry((name, hygiene)).or_insert_with_key(|(name, _)| { + let id = ec.alloc_binding(name.clone(), mode); + if !hygiene.is_root() { + ec.body.binding_hygiene.insert(id, hygiene); + } + id + }); if ec.body.bindings[id].mode != mode { ec.body.bindings[id].problems = Some(BindingProblems::BoundInconsistently); } @@ -211,6 +234,13 @@ impl ExprCollector<'_> { Name::new_symbol_root(sym::self_.clone()), BindingAnnotation::new(is_mutable, false), ); + let hygiene = self_param + .name() + .map(|name| self.hygiene_id_for(name.syntax().text_range().start())) + .unwrap_or(HygieneId::ROOT); + if !hygiene.is_root() { + self.body.binding_hygiene.insert(binding_id, hygiene); + } self.body.self_param = Some(binding_id); self.source_map.self_param = Some(self.expander.in_file(AstPtr::new(&self_param))); } @@ -288,13 +318,14 @@ impl ExprCollector<'_> { }) } Some(ast::BlockModifier::Label(label)) => { - let label = self.collect_label(label); - self.with_labeled_rib(label, |this| { + let label_hygiene = self.hygiene_id_for(label.syntax().text_range().start()); + let label_id = self.collect_label(label); + self.with_labeled_rib(label_id, label_hygiene, |this| { this.collect_block_(e, |id, statements, tail| Expr::Block { id, statements, tail, - label: Some(label), + label: Some(label_id), }) }) } @@ -336,9 +367,14 @@ impl ExprCollector<'_> { None => self.collect_block(e), }, ast::Expr::LoopExpr(e) => { - let label = e.label().map(|label| self.collect_label(label)); + let label = e.label().map(|label| { + ( + self.hygiene_id_for(label.syntax().text_range().start()), + self.collect_label(label), + ) + }); let body = self.collect_labelled_block_opt(label, e.loop_body()); - self.alloc_expr(Expr::Loop { body, label }, syntax_ptr) + self.alloc_expr(Expr::Loop { body, label: label.map(|it| it.1) }, syntax_ptr) } ast::Expr::WhileExpr(e) => self.collect_while_loop(syntax_ptr, e), ast::Expr::ForExpr(e) => self.collect_for_loop(syntax_ptr, e), @@ -398,12 +434,15 @@ impl ExprCollector<'_> { self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr) } ast::Expr::PathExpr(e) => { - let path = e - .path() - .and_then(|path| self.expander.parse_path(self.db, path)) - .map(Expr::Path) - .unwrap_or(Expr::Missing); - self.alloc_expr(path, syntax_ptr) + let (path, hygiene) = self + .collect_expr_path(&e) + .map(|(path, hygiene)| (Expr::Path(path), hygiene)) + .unwrap_or((Expr::Missing, HygieneId::ROOT)); + let expr_id = self.alloc_expr(path, syntax_ptr); + if !hygiene.is_root() { + self.body.expr_hygiene.insert(expr_id, hygiene); + } + expr_id } ast::Expr::ContinueExpr(e) => { let label = self.resolve_label(e.lifetime()).unwrap_or_else(|e| { @@ -677,6 +716,24 @@ impl ExprCollector<'_> { }) } + fn collect_expr_path(&mut self, e: &ast::PathExpr) -> Option<(Path, HygieneId)> { + e.path().and_then(|path| { + let path = self.expander.parse_path(self.db, path)?; + let Path::Normal { type_anchor, mod_path, generic_args } = &path else { + panic!("path parsing produced a non-normal path"); + }; + // Need to enable `mod_path.len() < 1` for `self`. + let may_be_variable = + type_anchor.is_none() && mod_path.len() <= 1 && generic_args.is_none(); + let hygiene = if may_be_variable { + self.hygiene_id_for(e.syntax().text_range().start()) + } else { + HygieneId::ROOT + }; + Some((path, hygiene)) + }) + } + fn collect_expr_as_pat_opt(&mut self, expr: Option) -> PatId { match expr { Some(expr) => self.collect_expr_as_pat(expr), @@ -740,8 +797,15 @@ impl ExprCollector<'_> { self.alloc_pat_from_expr(Pat::TupleStruct { path, args, ellipsis }, syntax_ptr) } ast::Expr::PathExpr(e) => { - let path = Box::new(self.expander.parse_path(self.db, e.path()?)?); - self.alloc_pat_from_expr(Pat::Path(path), syntax_ptr) + let (path, hygiene) = self + .collect_expr_path(e) + .map(|(path, hygiene)| (Pat::Path(Box::new(path)), hygiene)) + .unwrap_or((Pat::Missing, HygieneId::ROOT)); + let pat_id = self.alloc_pat_from_expr(path, syntax_ptr); + if !hygiene.is_root() { + self.body.pat_hygiene.insert(pat_id, hygiene); + } + pat_id } ast::Expr::MacroExpr(e) => { let e = e.macro_call()?; @@ -889,7 +953,7 @@ impl ExprCollector<'_> { let old_label = self.current_try_block_label.replace(label); let ptr = AstPtr::new(&e).upcast(); - let (btail, expr_id) = self.with_labeled_rib(label, |this| { + let (btail, expr_id) = self.with_labeled_rib(label, HygieneId::ROOT, |this| { let mut btail = None; let block = this.collect_block_(e, |id, statements, tail| { btail = tail; @@ -933,7 +997,9 @@ impl ExprCollector<'_> { /// FIXME: Rustc wraps the condition in a construct equivalent to `{ let _t = ; _t }` /// to preserve drop semantics. We should probably do the same in future. fn collect_while_loop(&mut self, syntax_ptr: AstPtr, e: ast::WhileExpr) -> ExprId { - let label = e.label().map(|label| self.collect_label(label)); + let label = e.label().map(|label| { + (self.hygiene_id_for(label.syntax().text_range().start()), self.collect_label(label)) + }); let body = self.collect_labelled_block_opt(label, e.loop_body()); // Labels can also be used in the condition expression, like this: @@ -950,9 +1016,9 @@ impl ExprCollector<'_> { // } // ``` let condition = match label { - Some(label) => { - self.with_labeled_rib(label, |this| this.collect_expr_opt(e.condition())) - } + Some((label_hygiene, label)) => self.with_labeled_rib(label, label_hygiene, |this| { + this.collect_expr_opt(e.condition()) + }), None => self.collect_expr_opt(e.condition()), }; @@ -961,7 +1027,7 @@ impl ExprCollector<'_> { Expr::If { condition, then_branch: body, else_branch: Some(break_expr) }, syntax_ptr, ); - self.alloc_expr(Expr::Loop { body: if_expr, label }, syntax_ptr) + self.alloc_expr(Expr::Loop { body: if_expr, label: label.map(|it| it.1) }, syntax_ptr) } /// Desugar `ast::ForExpr` from: `[opt_ident]: for in ` into: @@ -1005,7 +1071,9 @@ impl ExprCollector<'_> { args: Box::new([self.collect_pat_top(e.pat())]), ellipsis: None, }; - let label = e.label().map(|label| self.collect_label(label)); + let label = e.label().map(|label| { + (self.hygiene_id_for(label.syntax().text_range().start()), self.collect_label(label)) + }); let some_arm = MatchArm { pat: self.alloc_pat_desugared(some_pat), guard: None, @@ -1037,7 +1105,8 @@ impl ExprCollector<'_> { }, syntax_ptr, ); - let loop_outer = self.alloc_expr(Expr::Loop { body: loop_inner, label }, syntax_ptr); + let loop_outer = self + .alloc_expr(Expr::Loop { body: loop_inner, label: label.map(|it| it.1) }, syntax_ptr); let iter_binding = self.alloc_binding(iter_name, BindingAnnotation::Mutable); let iter_pat = self.alloc_pat_desugared(Pat::Bind { id: iter_binding, subpat: None }); self.add_definition_to_binding(iter_binding, iter_pat); @@ -1194,7 +1263,14 @@ impl ExprCollector<'_> { // FIXME: Report parse errors here } + let SpanMap::ExpansionSpanMap(new_span_map) = self.expander.span_map(self.db) + else { + panic!("just expanded a macro, ExpansionSpanMap should be available"); + }; + let old_span_map = + mem::replace(&mut self.current_span_map, Some(new_span_map.clone())); let id = collector(self, Some(expansion.tree())); + self.current_span_map = old_span_map; self.ast_id_map = prev_ast_id_map; self.expander.exit(mark); id @@ -1357,11 +1433,13 @@ impl ExprCollector<'_> { fn collect_labelled_block_opt( &mut self, - label: Option, + label: Option<(HygieneId, LabelId)>, expr: Option, ) -> ExprId { match label { - Some(label) => self.with_labeled_rib(label, |this| this.collect_block_opt(expr)), + Some((hygiene, label)) => { + self.with_labeled_rib(label, hygiene, |this| this.collect_block_opt(expr)) + } None => self.collect_block_opt(expr), } } @@ -1379,6 +1457,10 @@ impl ExprCollector<'_> { let pattern = match &pat { ast::Pat::IdentPat(bp) => { let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing); + let hygiene = bp + .name() + .map(|name| self.hygiene_id_for(name.syntax().text_range().start())) + .unwrap_or(HygieneId::ROOT); let annotation = BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some()); @@ -1414,12 +1496,12 @@ impl ExprCollector<'_> { } // shadowing statics is an error as well, so we just ignore that case here _ => { - let id = binding_list.find(self, name, annotation); + let id = binding_list.find(self, name, hygiene, annotation); (Some(id), Pat::Bind { id, subpat }) } } } else { - let id = binding_list.find(self, name, annotation); + let id = binding_list.find(self, name, hygiene, annotation); (Some(id), Pat::Bind { id, subpat }) }; @@ -1698,11 +1780,12 @@ impl ExprCollector<'_> { lifetime: Option, ) -> Result, BodyDiagnostic> { let Some(lifetime) = lifetime else { return Ok(None) }; + let hygiene = self.hygiene_id_for(lifetime.syntax().text_range().start()); let name = Name::new_lifetime(&lifetime); for (rib_idx, rib) in self.label_ribs.iter().enumerate().rev() { - if let Some((label_name, id)) = &rib.label { - if *label_name == name { + if let Some((label_name, id, label_hygiene)) = &rib.label { + if *label_name == name && *label_hygiene == hygiene { return if self.is_label_valid_from_rib(rib_idx) { Ok(Some(*id)) } else { @@ -1732,8 +1815,13 @@ impl ExprCollector<'_> { res } - fn with_labeled_rib(&mut self, label: LabelId, f: impl FnOnce(&mut Self) -> T) -> T { - self.label_ribs.push(LabelRib::new_normal((self.body[label].name.clone(), label))); + fn with_labeled_rib( + &mut self, + label: LabelId, + hygiene: HygieneId, + f: impl FnOnce(&mut Self) -> T, + ) -> T { + self.label_ribs.push(LabelRib::new_normal((self.body[label].name.clone(), label, hygiene))); let res = f(self); self.label_ribs.pop(); res @@ -1741,12 +1829,12 @@ impl ExprCollector<'_> { fn with_opt_labeled_rib( &mut self, - label: Option, + label: Option<(HygieneId, LabelId)>, f: impl FnOnce(&mut Self) -> T, ) -> T { match label { None => f(self), - Some(label) => self.with_labeled_rib(label, f), + Some((hygiene, label)) => self.with_labeled_rib(label, hygiene, f), } } // endregion: labels @@ -1795,28 +1883,39 @@ impl ExprCollector<'_> { _ => None, }); let mut mappings = vec![]; - let fmt = match template.and_then(|it| self.expand_macros_to_string(it)) { + let (fmt, hygiene) = match template.and_then(|it| self.expand_macros_to_string(it)) { Some((s, is_direct_literal)) => { let call_ctx = self.expander.syntax_context(); - format_args::parse( + let hygiene = self.hygiene_id_for(s.syntax().text_range().start()); + let fmt = format_args::parse( &s, fmt_snippet, args, is_direct_literal, - |name| self.alloc_expr_desugared(Expr::Path(Path::from(name))), + |name| { + let expr_id = self.alloc_expr_desugared(Expr::Path(Path::from(name))); + if !hygiene.is_root() { + self.body.expr_hygiene.insert(expr_id, hygiene); + } + expr_id + }, |name, span| { if let Some(span) = span { mappings.push((span, name)) } }, call_ctx, - ) + ); + (fmt, hygiene) } - None => FormatArgs { - template: Default::default(), - arguments: args.finish(), - orphans: Default::default(), - }, + None => ( + FormatArgs { + template: Default::default(), + arguments: args.finish(), + orphans: Default::default(), + }, + HygieneId::ROOT, + ), }; // Create a list of all _unique_ (argument, format trait) combinations. @@ -1963,7 +2062,11 @@ impl ExprCollector<'_> { }, syntax_ptr, ); - self.source_map.template_map.get_or_insert_with(Default::default).0.insert(idx, mappings); + self.source_map + .template_map + .get_or_insert_with(Default::default) + .0 + .insert(idx, (hygiene, mappings)); idx } @@ -2264,6 +2367,17 @@ impl ExprCollector<'_> { self.awaitable_context = orig; res } + + /// If this returns `HygieneId::ROOT`, do not allocate to save space. + fn hygiene_id_for(&self, span_start: TextSize) -> HygieneId { + match &self.current_span_map { + None => HygieneId::ROOT, + Some(span_map) => { + let ctx = span_map.span_at(span_start).ctx; + HygieneId(self.db.lookup_intern_syntax_context(ctx).opaque_and_semitransparent) + } + } + } } fn comma_follows_token(t: Option) -> bool { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs index c6967961b33f..7802bfe51a47 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs @@ -4,7 +4,7 @@ use la_arena::{Arena, ArenaMap, Idx, IdxRange, RawIdx}; use triomphe::Arc; use crate::{ - body::Body, + body::{Body, HygieneId}, db::DefDatabase, hir::{Binding, BindingId, Expr, ExprId, LabelId, Pat, PatId, Statement}, BlockId, ConstBlockId, DefWithBodyId, @@ -22,6 +22,7 @@ pub struct ExprScopes { #[derive(Debug, PartialEq, Eq)] pub struct ScopeEntry { name: Name, + hygiene: HygieneId, binding: BindingId, } @@ -30,6 +31,10 @@ impl ScopeEntry { &self.name } + pub(crate) fn hygiene(&self) -> HygieneId { + self.hygiene + } + pub fn binding(&self) -> BindingId { self.binding } @@ -102,7 +107,7 @@ impl ExprScopes { }; let mut root = scopes.root_scope(); if let Some(self_param) = body.self_param { - scopes.add_bindings(body, root, self_param); + scopes.add_bindings(body, root, self_param, body.binding_hygiene(self_param)); } scopes.add_params_bindings(body, root, &body.params); compute_expr_scopes(body.body_expr, body, &mut scopes, &mut root, resolve_const_block); @@ -150,17 +155,23 @@ impl ExprScopes { }) } - fn add_bindings(&mut self, body: &Body, scope: ScopeId, binding: BindingId) { + fn add_bindings( + &mut self, + body: &Body, + scope: ScopeId, + binding: BindingId, + hygiene: HygieneId, + ) { let Binding { name, .. } = &body.bindings[binding]; - let entry = self.scope_entries.alloc(ScopeEntry { name: name.clone(), binding }); + let entry = self.scope_entries.alloc(ScopeEntry { name: name.clone(), binding, hygiene }); self.scopes[scope].entries = IdxRange::new_inclusive(self.scopes[scope].entries.start()..=entry); } fn add_pat_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) { let pattern = &body[pat]; - if let Pat::Bind { id, .. } = pattern { - self.add_bindings(body, scope, *id); + if let Pat::Bind { id, .. } = *pattern { + self.add_bindings(body, scope, id, body.binding_hygiene(id)); } pattern.walk_child_pats(|pat| self.add_pat_bindings(body, scope, pat)); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/expander.rs b/src/tools/rust-analyzer/crates/hir-def/src/expander.rs index 6d8b4445f75b..6f200021baa9 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/expander.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/expander.rs @@ -49,6 +49,10 @@ impl Expander { } } + pub(crate) fn span_map(&self, db: &dyn DefDatabase) -> &SpanMap { + self.span_map.get_or_init(|| db.span_map(self.current_file_id)) + } + pub fn krate(&self) -> CrateId { self.module.krate } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs index f0f2210ec2c5..cf93958ecbb2 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs @@ -10,7 +10,10 @@ use smallvec::{smallvec, SmallVec}; use triomphe::Arc; use crate::{ - body::scope::{ExprScopes, ScopeId}, + body::{ + scope::{ExprScopes, ScopeId}, + HygieneId, + }, builtin_type::BuiltinType, data::ExternCrateDeclData, db::DefDatabase, @@ -257,6 +260,7 @@ impl Resolver { &self, db: &dyn DefDatabase, path: &Path, + hygiene: HygieneId, ) -> Option { let path = match path { Path::Normal { mod_path, .. } => mod_path, @@ -303,11 +307,10 @@ impl Resolver { for scope in self.scopes() { match scope { Scope::ExprScope(scope) => { - let entry = scope - .expr_scopes - .entries(scope.scope_id) - .iter() - .find(|entry| entry.name() == first_name); + let entry = + scope.expr_scopes.entries(scope.scope_id).iter().find(|entry| { + entry.name() == first_name && entry.hygiene() == hygiene + }); if let Some(e) = entry { return Some(ResolveValueResult::ValueNs( @@ -393,8 +396,9 @@ impl Resolver { &self, db: &dyn DefDatabase, path: &Path, + hygiene: HygieneId, ) -> Option { - match self.resolve_path_in_value_ns(db, path)? { + match self.resolve_path_in_value_ns(db, path, hygiene)? { ResolveValueResult::ValueNs(it, _) => Some(it), ResolveValueResult::Partial(..) => None, } diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/name.rs b/src/tools/rust-analyzer/crates/hir-expand/src/name.rs index 54313904a7ec..267d54583338 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/name.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/name.rs @@ -18,6 +18,8 @@ use syntax::utils::is_raw_identifier; #[derive(Clone, PartialEq, Eq, Hash)] pub struct Name { symbol: Symbol, + // If you are making this carry actual hygiene, beware that the special handling for variables and labels + // in bodies can go. ctx: (), } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs index 6a8598884404..9b0044f5c4f3 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs @@ -3,7 +3,7 @@ use base_db::{ra_salsa::Cycle, CrateId}; use chalk_ir::{cast::Cast, BoundVar, DebruijnIndex}; use hir_def::{ - body::Body, + body::{Body, HygieneId}, hir::{Expr, ExprId}, path::Path, resolver::{Resolver, ValueNs}, @@ -80,7 +80,7 @@ pub(crate) fn path_to_const<'g>( debruijn: DebruijnIndex, expected_ty: Ty, ) -> Option { - match resolver.resolve_path_in_value_ns_fully(db.upcast(), path) { + match resolver.resolve_path_in_value_ns_fully(db.upcast(), path, HygieneId::ROOT) { Some(ValueNs::GenericParam(p)) => { let ty = db.const_param_ty(p); let value = match mode { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs index 75dce7783163..92404e3a10e2 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs @@ -289,10 +289,12 @@ impl ExprValidator { match &self.body[scrutinee_expr] { Expr::UnaryOp { op: UnaryOp::Deref, .. } => false, Expr::Path(path) => { - let value_or_partial = self - .owner - .resolver(db.upcast()) - .resolve_path_in_value_ns_fully(db.upcast(), path); + let value_or_partial = + self.owner.resolver(db.upcast()).resolve_path_in_value_ns_fully( + db.upcast(), + path, + self.body.expr_path_hygiene(scrutinee_expr), + ); value_or_partial.map_or(true, |v| !matches!(v, ValueNs::StaticId(_))) } Expr::Field { expr, .. } => match self.infer.type_of_expr[*expr].kind(Interner) { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs index 492262c7a4cf..c7f7fb7ad3d3 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -77,7 +77,8 @@ fn walk_unsafe( ) { let mut mark_unsafe_path = |path, node| { let g = resolver.update_to_inner_scope(db.upcast(), def, current); - let value_or_partial = resolver.resolve_path_in_value_ns(db.upcast(), path); + let hygiene = body.expr_or_pat_path_hygiene(node); + let value_or_partial = resolver.resolve_path_in_value_ns(db.upcast(), path, hygiene); if let Some(ResolveValueResult::ValueNs(ValueNs::StaticId(id), _)) = value_or_partial { let static_data = db.static_data(id); if static_data.mutable || (static_data.is_extern && !static_data.has_safe_kw) { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index 6859c2d9c342..3cb0d89e01c4 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -33,7 +33,7 @@ use chalk_ir::{ }; use either::Either; use hir_def::{ - body::Body, + body::{Body, HygieneId}, builtin_type::{BuiltinInt, BuiltinType, BuiltinUint}, data::{ConstData, StaticData}, hir::{BindingAnnotation, BindingId, ExprId, ExprOrPatId, LabelId, PatId}, @@ -1398,7 +1398,7 @@ impl<'a> InferenceContext<'a> { }; let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()); let (resolution, unresolved) = if value_ns { - match self.resolver.resolve_path_in_value_ns(self.db.upcast(), path) { + match self.resolver.resolve_path_in_value_ns(self.db.upcast(), path, HygieneId::ROOT) { Some(ResolveValueResult::ValueNs(value, _)) => match value { ValueNs::EnumVariantId(var) => { let substs = ctx.substs_from_path(path, var.into(), true); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs index 91ba2af85e9e..6fc82f6743ca 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs @@ -514,8 +514,11 @@ impl InferenceContext<'_> { if path.type_anchor().is_some() { return None; } - let result = self.resolver.resolve_path_in_value_ns_fully(self.db.upcast(), path).and_then( - |result| match result { + let hygiene = self.body.expr_or_pat_path_hygiene(id); + let result = self + .resolver + .resolve_path_in_value_ns_fully(self.db.upcast(), path, hygiene) + .and_then(|result| match result { ValueNs::LocalBinding(binding) => { let mir_span = match id { ExprOrPatId::ExprId(id) => MirSpan::ExprId(id), @@ -525,8 +528,7 @@ impl InferenceContext<'_> { Some(HirPlace { local: binding, projections: Vec::new() }) } _ => None, - }, - ); + }); result } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs index 5c822fd22e1c..12b3ab671ade 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs @@ -201,7 +201,11 @@ impl InferenceContext<'_> { Expr::Path(Path::Normal { type_anchor: Some(_), .. }) => false, Expr::Path(path) => self .resolver - .resolve_path_in_value_ns_fully(self.db.upcast(), path) + .resolve_path_in_value_ns_fully( + self.db.upcast(), + path, + self.body.expr_path_hygiene(expr), + ) .map_or(true, |res| matches!(res, ValueNs::LocalBinding(_) | ValueNs::StaticId(_))), Expr::Underscore => true, Expr::UnaryOp { op: UnaryOp::Deref, .. } => true, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs index e4841c7b15b6..44c496c05421 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs @@ -164,9 +164,10 @@ impl InferenceContext<'_> { let ty = self.table.normalize_associated_types_in(ty); self.resolve_ty_assoc_item(ty, last.name, id).map(|(it, substs)| (it, Some(substs)))? } else { + let hygiene = self.body.expr_or_pat_path_hygiene(id); // FIXME: report error, unresolved first path segment let value_or_partial = - self.resolver.resolve_path_in_value_ns(self.db.upcast(), path)?; + self.resolver.resolve_path_in_value_ns(self.db.upcast(), path, hygiene)?; match value_or_partial { ResolveValueResult::ValueNs(it, _) => (it, None), diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs index 7580f042adc7..b7b565dece8d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs @@ -6,6 +6,7 @@ use base_db::CrateId; use chalk_ir::{cast::Cast, Mutability}; use either::Either; use hir_def::{ + body::HygieneId, builtin_type::BuiltinType, data::adt::{StructFlags, VariantData}, lang_item::LangItem, @@ -2953,6 +2954,7 @@ pub fn render_const_using_debug_impl( let Some(ValueNs::FunctionId(format_fn)) = resolver.resolve_path_in_value_ns_fully( db.upcast(), &hir_def::path::Path::from_known_path_with_no_generic(path![std::fmt::format]), + HygieneId::ROOT, ) else { not_supported!("std::fmt::format not found"); }; diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs index a8a927c2c5c7..6343406b83de 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs @@ -5,7 +5,7 @@ use std::{fmt::Write, iter, mem}; use base_db::ra_salsa::Cycle; use chalk_ir::{BoundVar, ConstData, DebruijnIndex, TyKind}; use hir_def::{ - body::Body, + body::{Body, HygieneId}, data::adt::{StructKind, VariantData}, hir::{ ArithOp, Array, BinaryOp, BindingAnnotation, BindingId, ExprId, LabelId, Literal, @@ -446,9 +446,10 @@ impl<'ctx> MirLowerCtx<'ctx> { } else { let resolver_guard = self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); + let hygiene = self.body.expr_path_hygiene(expr_id); let result = self .resolver - .resolve_path_in_value_ns_fully(self.db.upcast(), p) + .resolve_path_in_value_ns_fully(self.db.upcast(), p, hygiene) .ok_or_else(|| { MirLowerError::unresolved_path(self.db, p, self.edition()) })?; @@ -1361,7 +1362,7 @@ impl<'ctx> MirLowerCtx<'ctx> { || MirLowerError::unresolved_path(self.db, c.as_ref(), edition); let pr = self .resolver - .resolve_path_in_value_ns(self.db.upcast(), c.as_ref()) + .resolve_path_in_value_ns(self.db.upcast(), c.as_ref(), HygieneId::ROOT) .ok_or_else(unresolved_name)?; match pr { ResolveValueResult::ValueNs(v, _) => { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs index 91086e805798..420f2aaff46d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs @@ -137,7 +137,9 @@ impl MirLowerCtx<'_> { Expr::Path(p) => { let resolver_guard = self.resolver.update_to_inner_scope(self.db.upcast(), self.owner, expr_id); - let resolved = self.resolver.resolve_path_in_value_ns_fully(self.db.upcast(), p); + let hygiene = self.body.expr_path_hygiene(expr_id); + let resolved = + self.resolver.resolve_path_in_value_ns_fully(self.db.upcast(), p, hygiene); self.resolver.reset_to_guard(resolver_guard); let Some(pr) = resolved else { return try_rvalue(self); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs index 63bb3367771f..d985a6451b7d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -351,9 +351,10 @@ impl MirLowerCtx<'_> { None => { let unresolved_name = || MirLowerError::unresolved_path(self.db, p, self.edition()); + let hygiene = self.body.pat_path_hygiene(pattern); let pr = self .resolver - .resolve_path_in_value_ns(self.db.upcast(), p) + .resolve_path_in_value_ns(self.db.upcast(), p, hygiene) .ok_or_else(unresolved_name)?; if let ( diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs b/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs index e6ef56b80d93..7ea666986ab3 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs @@ -3720,3 +3720,20 @@ fn test() -> bool { "#]], ); } + +#[test] +fn macro_semitransparent_hygiene() { + check_types( + r#" +macro_rules! m { + () => { let bar: i32; }; +} +fn foo() { + let bar: bool; + m!(); + bar; + // ^^^ bool +} + "#, + ); +} diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index d34a0d8f51b7..860754d5e704 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -45,7 +45,7 @@ use syntax::{ use crate::{ db::HirDatabase, semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx}, - source_analyzer::{resolve_hir_path, SourceAnalyzer}, + source_analyzer::{name_hygiene, resolve_hir_path, SourceAnalyzer}, Access, Adjust, Adjustment, Adt, AutoBorrow, BindingMode, BuiltinAttr, Callable, Const, ConstParam, Crate, DeriveHelper, Enum, Field, Function, HasSource, HirFileId, Impl, InFile, InlineAsmOperand, ItemInNs, Label, LifetimeParam, Local, Macro, Module, ModuleDef, Name, @@ -1952,10 +1952,15 @@ impl SemanticsScope<'_> { /// Resolve a path as-if it was written at the given scope. This is /// necessary a heuristic, as it doesn't take hygiene into account. - pub fn speculative_resolve(&self, path: &ast::Path) -> Option { + pub fn speculative_resolve(&self, ast_path: &ast::Path) -> Option { let ctx = LowerCtx::new(self.db.upcast(), self.file_id); - let path = Path::from_src(&ctx, path.clone())?; - resolve_hir_path(self.db, &self.resolver, &path) + let path = Path::from_src(&ctx, ast_path.clone())?; + resolve_hir_path( + self.db, + &self.resolver, + &path, + name_hygiene(self.db, InFile::new(self.file_id, ast_path.syntax())), + ) } /// Iterates over associated types that may be specified after the given path (using diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 430b646e97cb..f5b57d57dfc7 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -16,7 +16,7 @@ use either::Either; use hir_def::{ body::{ scope::{ExprScopes, ScopeId}, - Body, BodySourceMap, + Body, BodySourceMap, HygieneId, }, hir::{BindingId, ExprId, ExprOrPatId, Pat, PatId}, lang_item::LangItem, @@ -562,7 +562,8 @@ impl SourceAnalyzer { let expr = ast::Expr::from(record_expr); let expr_id = self.body_source_map()?.node_expr(InFile::new(self.file_id, &expr))?; - let local_name = field.field_name()?.as_name(); + let ast_name = field.field_name()?; + let local_name = ast_name.as_name(); let local = if field.name_ref().is_some() { None } else { @@ -571,7 +572,11 @@ impl SourceAnalyzer { PathKind::Plain, once(local_name.clone()), )); - match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) { + match self.resolver.resolve_path_in_value_ns_fully( + db.upcast(), + &path, + name_hygiene(db, InFile::new(self.file_id, ast_name.syntax())), + ) { Some(ValueNs::LocalBinding(binding_id)) => { Some(Local { binding_id, parent: self.resolver.body_owner()? }) } @@ -627,7 +632,7 @@ impl SourceAnalyzer { Pat::Path(path) => path, _ => return None, }; - let res = resolve_hir_path(db, &self.resolver, path)?; + let res = resolve_hir_path(db, &self.resolver, path, HygieneId::ROOT)?; match res { PathResolution::Def(def) => Some(def), _ => None, @@ -818,7 +823,13 @@ impl SourceAnalyzer { if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) { resolve_hir_path_qualifier(db, &self.resolver, &hir_path) } else { - resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns) + resolve_hir_path_( + db, + &self.resolver, + &hir_path, + prefer_value_ns, + name_hygiene(db, InFile::new(self.file_id, path.syntax())), + ) } } @@ -944,7 +955,7 @@ impl SourceAnalyzer { format_args: InFile<&ast::FormatArgsExpr>, offset: TextSize, ) -> Option<(TextRange, Option)> { - let implicits = self.body_source_map()?.implicit_format_args(format_args)?; + let (hygiene, implicits) = self.body_source_map()?.implicit_format_args(format_args)?; implicits.iter().find(|(range, _)| range.contains_inclusive(offset)).map(|(range, name)| { ( *range, @@ -956,6 +967,7 @@ impl SourceAnalyzer { PathKind::Plain, Some(name.clone()), )), + hygiene, ), ) }) @@ -982,22 +994,22 @@ impl SourceAnalyzer { db: &'a dyn HirDatabase, format_args: InFile<&ast::FormatArgsExpr>, ) -> Option)> + 'a> { - Some(self.body_source_map()?.implicit_format_args(format_args)?.iter().map( - move |(range, name)| { - ( - *range, - resolve_hir_value_path( - db, - &self.resolver, - self.resolver.body_owner(), - &Path::from_known_path_with_no_generic(ModPath::from_segments( - PathKind::Plain, - Some(name.clone()), - )), - ), - ) - }, - )) + let (hygiene, names) = self.body_source_map()?.implicit_format_args(format_args)?; + Some(names.iter().map(move |(range, name)| { + ( + *range, + resolve_hir_value_path( + db, + &self.resolver, + self.resolver.body_owner(), + &Path::from_known_path_with_no_generic(ModPath::from_segments( + PathKind::Plain, + Some(name.clone()), + )), + hygiene, + ), + ) + })) } pub(crate) fn as_asm_parts( @@ -1143,8 +1155,9 @@ pub(crate) fn resolve_hir_path( db: &dyn HirDatabase, resolver: &Resolver, path: &Path, + hygiene: HygieneId, ) -> Option { - resolve_hir_path_(db, resolver, path, false) + resolve_hir_path_(db, resolver, path, false, hygiene) } #[inline] @@ -1164,6 +1177,7 @@ fn resolve_hir_path_( resolver: &Resolver, path: &Path, prefer_value_ns: bool, + hygiene: HygieneId, ) -> Option { let types = || { let (ty, unresolved) = match path.type_anchor() { @@ -1229,7 +1243,7 @@ fn resolve_hir_path_( }; let body_owner = resolver.body_owner(); - let values = || resolve_hir_value_path(db, resolver, body_owner, path); + let values = || resolve_hir_value_path(db, resolver, body_owner, path, hygiene); let items = || { resolver @@ -1254,8 +1268,9 @@ fn resolve_hir_value_path( resolver: &Resolver, body_owner: Option, path: &Path, + hygiene: HygieneId, ) -> Option { - resolver.resolve_path_in_value_ns_fully(db.upcast(), path).and_then(|val| { + resolver.resolve_path_in_value_ns_fully(db.upcast(), path, hygiene).and_then(|val| { let res = match val { ValueNs::LocalBinding(binding_id) => { let var = Local { parent: body_owner?, binding_id }; @@ -1360,3 +1375,13 @@ fn resolve_hir_path_qualifier( .map(|it| PathResolution::Def(it.into())) }) } + +pub(crate) fn name_hygiene(db: &dyn HirDatabase, name: InFile<&SyntaxNode>) -> HygieneId { + let Some(macro_file) = name.file_id.macro_file() else { + return HygieneId::ROOT; + }; + let span_map = db.expansion_span_map(macro_file); + let ctx = span_map.span_at(name.value.text_range().start()).ctx; + let ctx = db.lookup_intern_syntax_context(ctx); + HygieneId::new(ctx.opaque_and_semitransparent) +} diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 1d42a66995b7..363f852e0e4b 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -2999,6 +2999,26 @@ mod bar { mod m {} use foo::m; +"#, + ); + } + + #[test] + fn macro_label_hygiene() { + check( + r#" +macro_rules! m { + ($x:stmt) => { + 'bar: loop { $x } + }; +} + +fn foo() { + 'bar: loop { + // ^^^^ + m!(continue 'bar$0); + } +} "#, ); } From 8f36d1c94ad0d046f0e25906f521f8587e775b9b Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Tue, 22 Oct 2024 20:58:25 +0300 Subject: [PATCH 131/366] Correctly resolve variables and labels from before macro definition in macro expansion E.g.: ```rust let v; macro_rules! m { () => { v }; } ``` This was an existing bug, but it was less severe because unless the variable was shadowed it would be correctly resolved. With hygiene however, without this fix the variable is never resolved. --- .../rust-analyzer/crates/hir-def/src/body.rs | 6 +- .../crates/hir-def/src/body/lower.rs | 138 ++++++++++++++---- .../crates/hir-def/src/body/pretty.rs | 2 +- .../crates/hir-def/src/body/scope.rs | 31 +++- .../rust-analyzer/crates/hir-def/src/hir.rs | 12 +- .../crates/hir-def/src/resolver.rs | 45 +++++- .../crates/hir-ty/src/infer/closure.rs | 2 +- .../crates/hir-ty/src/infer/expr.rs | 2 +- .../crates/hir-ty/src/infer/mutability.rs | 2 +- .../crates/hir-ty/src/mir/lower.rs | 2 +- .../crates/hir-ty/src/tests/simple.rs | 65 +++++++++ .../src/handlers/undeclared_label.rs | 30 ++++ 12 files changed, 287 insertions(+), 50 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body.rs b/src/tools/rust-analyzer/crates/hir-def/src/body.rs index 27fe5c87ccba..1bfd7d2b7319 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body.rs @@ -35,7 +35,7 @@ use crate::{ /// A wrapper around [`span::SyntaxContextId`] that is intended only for comparisons. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct HygieneId(span::SyntaxContextId); +pub struct HygieneId(pub(crate) span::SyntaxContextId); impl HygieneId { pub const ROOT: Self = Self(span::SyntaxContextId::ROOT); @@ -44,7 +44,7 @@ impl HygieneId { Self(ctx) } - fn is_root(self) -> bool { + pub(crate) fn is_root(self) -> bool { self.0.is_root() } } @@ -420,7 +420,7 @@ impl Body { self.walk_exprs_in_pat(*pat, &mut f); } Statement::Expr { expr: expression, .. } => f(*expression), - Statement::Item => (), + Statement::Item(_) => (), } } if let &Some(expr) = tail { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index cdc7b141717f..b87e94f9c51d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -10,7 +10,7 @@ use either::Either; use hir_expand::{ name::{AsName, Name}, span_map::{ExpansionSpanMap, SpanMap}, - InFile, + InFile, MacroDefId, }; use intern::{sym, Interned, Symbol}; use rustc_hash::FxHashMap; @@ -39,8 +39,8 @@ use crate::{ FormatPlaceholder, FormatSign, FormatTrait, }, Array, Binding, BindingAnnotation, BindingId, BindingProblems, CaptureBy, ClosureKind, - Expr, ExprId, Label, LabelId, Literal, LiteralOrConst, MatchArm, Movability, OffsetOf, Pat, - PatId, RecordFieldPat, RecordLitField, Statement, + Expr, ExprId, Item, Label, LabelId, Literal, LiteralOrConst, MatchArm, Movability, + OffsetOf, Pat, PatId, RecordFieldPat, RecordLitField, Statement, }, item_scope::BuiltinShadowMode, lang_item::LangItem, @@ -48,7 +48,7 @@ use crate::{ nameres::{DefMap, MacroSubNs}, path::{GenericArgs, Path}, type_ref::{Mutability, Rawness, TypeRef}, - AdtId, BlockId, BlockLoc, ConstBlockLoc, DefWithBodyId, ModuleDefId, UnresolvedMacro, + AdtId, BlockId, BlockLoc, ConstBlockLoc, DefWithBodyId, MacroId, ModuleDefId, UnresolvedMacro, }; type FxIndexSet = indexmap::IndexSet>; @@ -88,6 +88,7 @@ pub(super) fn lower( current_binding_owner: None, awaitable_context: None, current_span_map: span_map, + current_block_legacy_macro_defs_count: FxHashMap::default(), } .collect(params, body, is_async_fn) } @@ -104,6 +105,10 @@ struct ExprCollector<'a> { is_lowering_coroutine: bool, + /// Legacy (`macro_rules!`) macros can have multiple definitions and shadow each other, + /// and we need to find the current definition. So we track the number of definitions we saw. + current_block_legacy_macro_defs_count: FxHashMap, + current_span_map: Option>, current_try_block_label: Option, @@ -124,31 +129,27 @@ struct ExprCollector<'a> { #[derive(Clone, Debug)] struct LabelRib { kind: RibKind, - // Once we handle macro hygiene this will need to be a map - label: Option<(Name, LabelId, HygieneId)>, } impl LabelRib { fn new(kind: RibKind) -> Self { - LabelRib { kind, label: None } - } - fn new_normal(label: (Name, LabelId, HygieneId)) -> Self { - LabelRib { kind: RibKind::Normal, label: Some(label) } + LabelRib { kind } } } -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] enum RibKind { - Normal, + Normal(Name, LabelId, HygieneId), Closure, Constant, + MacroDef(Box), } impl RibKind { /// This rib forbids referring to labels defined in upwards ribs. - fn is_label_barrier(self) -> bool { + fn is_label_barrier(&self) -> bool { match self { - RibKind::Normal => false, + RibKind::Normal(..) | RibKind::MacroDef(_) => false, RibKind::Closure | RibKind::Constant => true, } } @@ -1350,10 +1351,46 @@ impl ExprCollector<'_> { statements.push(Statement::Expr { expr, has_semi }); } } - ast::Stmt::Item(_item) => statements.push(Statement::Item), + ast::Stmt::Item(ast::Item::MacroDef(macro_)) => { + let Some(name) = macro_.name() else { + statements.push(Statement::Item(Item::Other)); + return; + }; + let name = name.as_name(); + let macro_id = self.def_map.modules[DefMap::ROOT].scope.get(&name).take_macros(); + self.collect_macro_def(statements, macro_id); + } + ast::Stmt::Item(ast::Item::MacroRules(macro_)) => { + let Some(name) = macro_.name() else { + statements.push(Statement::Item(Item::Other)); + return; + }; + let name = name.as_name(); + let macro_defs_count = + self.current_block_legacy_macro_defs_count.entry(name.clone()).or_insert(0); + let macro_id = self.def_map.modules[DefMap::ROOT] + .scope + .get_legacy_macro(&name) + .and_then(|it| it.get(*macro_defs_count)) + .copied(); + *macro_defs_count += 1; + self.collect_macro_def(statements, macro_id); + } + ast::Stmt::Item(_item) => statements.push(Statement::Item(Item::Other)), } } + fn collect_macro_def(&mut self, statements: &mut Vec, macro_id: Option) { + let Some(macro_id) = macro_id else { + never!("def map should have macro definition, but it doesn't"); + statements.push(Statement::Item(Item::Other)); + return; + }; + let macro_id = self.db.macro_def(macro_id); + statements.push(Statement::Item(Item::MacroDef(Box::new(macro_id)))); + self.label_ribs.push(LabelRib::new(RibKind::MacroDef(Box::new(macro_id)))); + } + fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId { self.collect_block_(block, |id, statements, tail| Expr::Block { id, @@ -1399,6 +1436,7 @@ impl ExprCollector<'_> { }; let prev_def_map = mem::replace(&mut self.def_map, def_map); let prev_local_module = mem::replace(&mut self.expander.module, module); + let prev_legacy_macros_count = mem::take(&mut self.current_block_legacy_macro_defs_count); let mut statements = Vec::new(); block.statements().for_each(|s| self.collect_stmt(&mut statements, s)); @@ -1421,6 +1459,7 @@ impl ExprCollector<'_> { self.def_map = prev_def_map; self.expander.module = prev_local_module; + self.current_block_legacy_macro_defs_count = prev_legacy_macros_count; expr_id } @@ -1780,21 +1819,51 @@ impl ExprCollector<'_> { lifetime: Option, ) -> Result, BodyDiagnostic> { let Some(lifetime) = lifetime else { return Ok(None) }; - let hygiene = self.hygiene_id_for(lifetime.syntax().text_range().start()); + let (mut hygiene_id, mut hygiene_info) = match &self.current_span_map { + None => (HygieneId::ROOT, None), + Some(span_map) => { + let span = span_map.span_at(lifetime.syntax().text_range().start()); + let ctx = self.db.lookup_intern_syntax_context(span.ctx); + let hygiene_id = HygieneId::new(ctx.opaque_and_semitransparent); + let hygiene_info = ctx.outer_expn.map(|expansion| { + let expansion = self.db.lookup_intern_macro_call(expansion); + (ctx.parent, expansion.def) + }); + (hygiene_id, hygiene_info) + } + }; let name = Name::new_lifetime(&lifetime); for (rib_idx, rib) in self.label_ribs.iter().enumerate().rev() { - if let Some((label_name, id, label_hygiene)) = &rib.label { - if *label_name == name && *label_hygiene == hygiene { - return if self.is_label_valid_from_rib(rib_idx) { - Ok(Some(*id)) - } else { - Err(BodyDiagnostic::UnreachableLabel { - name, - node: self.expander.in_file(AstPtr::new(&lifetime)), - }) - }; + match &rib.kind { + RibKind::Normal(label_name, id, label_hygiene) => { + if *label_name == name && *label_hygiene == hygiene_id { + return if self.is_label_valid_from_rib(rib_idx) { + Ok(Some(*id)) + } else { + Err(BodyDiagnostic::UnreachableLabel { + name, + node: self.expander.in_file(AstPtr::new(&lifetime)), + }) + }; + } } + RibKind::MacroDef(macro_id) => { + if let Some((parent_ctx, label_macro_id)) = hygiene_info { + if label_macro_id == **macro_id { + // A macro is allowed to refer to labels from before its declaration. + // Therefore, if we got to the rib of its declaration, give up its hygiene + // and use its parent expansion. + let parent_ctx = self.db.lookup_intern_syntax_context(parent_ctx); + hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent); + hygiene_info = parent_ctx.outer_expn.map(|expansion| { + let expansion = self.db.lookup_intern_macro_call(expansion); + (parent_ctx.parent, expansion.def) + }); + } + } + } + _ => {} } } @@ -1808,10 +1877,17 @@ impl ExprCollector<'_> { !self.label_ribs[rib_index + 1..].iter().any(|rib| rib.kind.is_label_barrier()) } + fn pop_label_rib(&mut self) { + // We need to pop all macro defs, plus one rib. + while let Some(LabelRib { kind: RibKind::MacroDef(_) }) = self.label_ribs.pop() { + // Do nothing. + } + } + fn with_label_rib(&mut self, kind: RibKind, f: impl FnOnce(&mut Self) -> T) -> T { self.label_ribs.push(LabelRib::new(kind)); let res = f(self); - self.label_ribs.pop(); + self.pop_label_rib(); res } @@ -1821,9 +1897,13 @@ impl ExprCollector<'_> { hygiene: HygieneId, f: impl FnOnce(&mut Self) -> T, ) -> T { - self.label_ribs.push(LabelRib::new_normal((self.body[label].name.clone(), label, hygiene))); + self.label_ribs.push(LabelRib::new(RibKind::Normal( + self.body[label].name.clone(), + label, + hygiene, + ))); let res = f(self); - self.label_ribs.pop(); + self.pop_label_rib(); res } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs index 2419862b7617..591bb64af5a8 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs @@ -753,7 +753,7 @@ impl Printer<'_> { } wln!(self); } - Statement::Item => (), + Statement::Item(_) => (), } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs index 7802bfe51a47..63a7a9af201d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs @@ -1,12 +1,12 @@ //! Name resolution for expressions. -use hir_expand::name::Name; +use hir_expand::{name::Name, MacroDefId}; use la_arena::{Arena, ArenaMap, Idx, IdxRange, RawIdx}; use triomphe::Arc; use crate::{ body::{Body, HygieneId}, db::DefDatabase, - hir::{Binding, BindingId, Expr, ExprId, LabelId, Pat, PatId, Statement}, + hir::{Binding, BindingId, Expr, ExprId, Item, LabelId, Pat, PatId, Statement}, BlockId, ConstBlockId, DefWithBodyId, }; @@ -45,6 +45,8 @@ pub struct ScopeData { parent: Option, block: Option, label: Option<(LabelId, Name)>, + // FIXME: We can compress this with an enum for this and `label`/`block` if memory usage matters. + macro_def: Option>, entries: IdxRange, } @@ -67,6 +69,12 @@ impl ExprScopes { self.scopes[scope].block } + /// If `scope` refers to a macro def scope, returns the corresponding `MacroId`. + #[allow(clippy::borrowed_box)] // If we return `&MacroDefId` we need to move it, this way we just clone the `Box`. + pub fn macro_def(&self, scope: ScopeId) -> Option<&Box> { + self.scopes[scope].macro_def.as_ref() + } + /// If `scope` refers to a labeled expression scope, returns the corresponding `Label`. pub fn label(&self, scope: ScopeId) -> Option<(LabelId, Name)> { self.scopes[scope].label.clone() @@ -119,6 +127,7 @@ impl ExprScopes { parent: None, block: None, label: None, + macro_def: None, entries: empty_entries(self.scope_entries.len()), }) } @@ -128,6 +137,7 @@ impl ExprScopes { parent: Some(parent), block: None, label: None, + macro_def: None, entries: empty_entries(self.scope_entries.len()), }) } @@ -137,6 +147,7 @@ impl ExprScopes { parent: Some(parent), block: None, label, + macro_def: None, entries: empty_entries(self.scope_entries.len()), }) } @@ -151,6 +162,17 @@ impl ExprScopes { parent: Some(parent), block, label, + macro_def: None, + entries: empty_entries(self.scope_entries.len()), + }) + } + + fn new_macro_def_scope(&mut self, parent: ScopeId, macro_id: Box) -> ScopeId { + self.scopes.alloc(ScopeData { + parent: Some(parent), + block: None, + label: None, + macro_def: Some(macro_id), entries: empty_entries(self.scope_entries.len()), }) } @@ -217,7 +239,10 @@ fn compute_block_scopes( Statement::Expr { expr, .. } => { compute_expr_scopes(*expr, body, scopes, scope, resolve_const_block); } - Statement::Item => (), + Statement::Item(Item::MacroDef(macro_id)) => { + *scope = scopes.new_macro_def_scope(*scope, macro_id.clone()); + } + Statement::Item(Item::Other) => (), } } if let Some(expr) = tail { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs index a575a2d19913..c1d3e255bb5b 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs @@ -17,7 +17,7 @@ pub mod type_ref; use std::fmt; -use hir_expand::name::Name; +use hir_expand::{name::Name, MacroDefId}; use intern::{Interned, Symbol}; use la_arena::{Idx, RawIdx}; use rustc_apfloat::ieee::{Half as f16, Quad as f128}; @@ -492,9 +492,13 @@ pub enum Statement { expr: ExprId, has_semi: bool, }, - // At the moment, we only use this to figure out if a return expression - // is really the last statement of a block. See #16566 - Item, + Item(Item), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Item { + MacroDef(Box), + Other, } /// Explicit binding annotations given in the HIR for a binding. Note diff --git a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs index cf93958ecbb2..266851e3c0d5 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs @@ -83,6 +83,8 @@ enum Scope { AdtScope(AdtId), /// Local bindings ExprScope(ExprScope), + /// Macro definition inside bodies that affects all paths after it in the same block. + MacroDefScope(Box), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -191,7 +193,7 @@ impl Resolver { for scope in self.scopes() { match scope { - Scope::ExprScope(_) => continue, + Scope::ExprScope(_) | Scope::MacroDefScope(_) => continue, Scope::GenericParams { params, def } => { if let Some(id) = params.find_type_by_name(first_name, *def) { return Some((TypeNs::GenericParam(id), remaining_idx(), None)); @@ -260,7 +262,7 @@ impl Resolver { &self, db: &dyn DefDatabase, path: &Path, - hygiene: HygieneId, + mut hygiene_id: HygieneId, ) -> Option { let path = match path { Path::Normal { mod_path, .. } => mod_path, @@ -304,12 +306,21 @@ impl Resolver { } if n_segments <= 1 { + let mut hygiene_info = if !hygiene_id.is_root() { + let ctx = db.lookup_intern_syntax_context(hygiene_id.0); + ctx.outer_expn.map(|expansion| { + let expansion = db.lookup_intern_macro_call(expansion); + (ctx.parent, expansion.def) + }) + } else { + None + }; for scope in self.scopes() { match scope { Scope::ExprScope(scope) => { let entry = scope.expr_scopes.entries(scope.scope_id).iter().find(|entry| { - entry.name() == first_name && entry.hygiene() == hygiene + entry.name() == first_name && entry.hygiene() == hygiene_id }); if let Some(e) = entry { @@ -319,6 +330,21 @@ impl Resolver { )); } } + Scope::MacroDefScope(macro_id) => { + if let Some((parent_ctx, label_macro_id)) = hygiene_info { + if label_macro_id == **macro_id { + // A macro is allowed to refer to variables from before its declaration. + // Therefore, if we got to the rib of its declaration, give up its hygiene + // and use its parent expansion. + let parent_ctx = db.lookup_intern_syntax_context(parent_ctx); + hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent); + hygiene_info = parent_ctx.outer_expn.map(|expansion| { + let expansion = db.lookup_intern_macro_call(expansion); + (parent_ctx.parent, expansion.def) + }); + } + } + } Scope::GenericParams { params, def } => { if let Some(id) = params.find_const_by_name(first_name, *def) { let val = ValueNs::GenericParam(id); @@ -345,7 +371,7 @@ impl Resolver { } else { for scope in self.scopes() { match scope { - Scope::ExprScope(_) => continue, + Scope::ExprScope(_) | Scope::MacroDefScope(_) => continue, Scope::GenericParams { params, def } => { if let Some(id) = params.find_type_by_name(first_name, *def) { let ty = TypeNs::GenericParam(id); @@ -626,7 +652,7 @@ impl Resolver { pub fn type_owner(&self) -> Option { self.scopes().find_map(|scope| match scope { - Scope::BlockScope(_) => None, + Scope::BlockScope(_) | Scope::MacroDefScope(_) => None, &Scope::GenericParams { def, .. } => Some(def.into()), &Scope::ImplDefScope(id) => Some(id.into()), &Scope::AdtScope(adt) => Some(adt.into()), @@ -657,6 +683,9 @@ impl Resolver { expr_scopes: &Arc, scope_id: ScopeId, ) { + if let Some(macro_id) = expr_scopes.macro_def(scope_id) { + resolver.scopes.push(Scope::MacroDefScope(macro_id.clone())); + } resolver.scopes.push(Scope::ExprScope(ExprScope { owner, expr_scopes: expr_scopes.clone(), @@ -674,7 +703,7 @@ impl Resolver { } let start = self.scopes.len(); - let innermost_scope = self.scopes().next(); + let innermost_scope = self.scopes().find(|scope| !matches!(scope, Scope::MacroDefScope(_))); match innermost_scope { Some(&Scope::ExprScope(ExprScope { scope_id, ref expr_scopes, owner })) => { let expr_scopes = expr_scopes.clone(); @@ -798,6 +827,7 @@ impl Scope { acc.add_local(e.name(), e.binding()); }); } + Scope::MacroDefScope(_) => {} } } } @@ -837,6 +867,9 @@ fn resolver_for_scope_( // already traverses all parents, so this is O(n²). I think we could only store the // innermost module scope instead? } + if let Some(macro_id) = scopes.macro_def(scope) { + r = r.push_scope(Scope::MacroDefScope(macro_id.clone())); + } r = r.push_expr_scope(owner, Arc::clone(&scopes), scope); } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs index 6fc82f6743ca..f5face07d860 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs @@ -747,7 +747,7 @@ impl InferenceContext<'_> { Statement::Expr { expr, has_semi: _ } => { self.consume_expr(*expr); } - Statement::Item => (), + Statement::Item(_) => (), } } if let Some(tail) = tail { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs index 12b3ab671ade..e55ddad4e969 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs @@ -1656,7 +1656,7 @@ impl InferenceContext<'_> { ); } } - Statement::Item => (), + Statement::Item(_) => (), } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs index 9fef582d85de..d74a383f44ef 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs @@ -89,7 +89,7 @@ impl InferenceContext<'_> { Statement::Expr { expr, has_semi: _ } => { self.infer_mut_expr(*expr, Mutability::Not); } - Statement::Item => (), + Statement::Item(_) => (), } } if let Some(tail) = tail { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs index 6343406b83de..99a4e112f8b2 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs @@ -1783,7 +1783,7 @@ impl<'ctx> MirLowerCtx<'ctx> { self.push_fake_read(c, p, expr.into()); current = scope2.pop_and_drop(self, c, expr.into()); } - hir_def::hir::Statement::Item => (), + hir_def::hir::Statement::Item(_) => (), } } if let Some(tail) = tail { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs b/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs index 7ea666986ab3..5f0f341f393e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/tests/simple.rs @@ -3737,3 +3737,68 @@ fn foo() { "#, ); } + +#[test] +fn macro_expansion_can_refer_variables_defined_before_macro_definition() { + check_types( + r#" +fn foo() { + let v: i32 = 0; + macro_rules! m { + () => { v }; + } + let v: bool = true; + m!(); + // ^^^^ i32 +} + "#, + ); +} + +#[test] +fn macro_rules_shadowing_works_with_hygiene() { + check_types( + r#" +fn foo() { + let v: bool; + macro_rules! m { () => { v } } + m!(); + // ^^^^ bool + + let v: char; + macro_rules! m { () => { v } } + m!(); + // ^^^^ char + + { + let v: u8; + macro_rules! m { () => { v } } + m!(); + // ^^^^ u8 + + let v: i8; + macro_rules! m { () => { v } } + m!(); + // ^^^^ i8 + + let v: i16; + macro_rules! m { () => { v } } + m!(); + // ^^^^ i16 + + { + let v: u32; + macro_rules! m { () => { v } } + m!(); + // ^^^^ u32 + + let v: u64; + macro_rules! m { () => { v } } + m!(); + // ^^^^ u64 + } + } +} + "#, + ); +} diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/undeclared_label.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/undeclared_label.rs index 6af36fb9e739..d16bfb800240 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/undeclared_label.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/undeclared_label.rs @@ -104,6 +104,36 @@ async fn foo() { async fn foo() { || None?; } +"#, + ); + } + + #[test] + fn macro_expansion_can_refer_label_defined_before_macro_definition() { + check_diagnostics( + r#" +fn foo() { + 'bar: loop { + macro_rules! m { + () => { break 'bar }; + } + m!(); + } +} +"#, + ); + check_diagnostics( + r#" +fn foo() { + 'bar: loop { + macro_rules! m { + () => { break 'bar }; + } + 'bar: loop { + m!(); + } + } +} "#, ); } From febb3f7c8814432f5905ecf31137a804c8a5cb1a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 20 Oct 2024 20:35:18 +0000 Subject: [PATCH 132/366] Represent TraitBoundModifiers as distinct parts in HIR --- compiler/rustc_ast/src/ast.rs | 4 +-- compiler/rustc_ast_lowering/src/lib.rs | 22 +++--------- compiler/rustc_hir/src/hir.rs | 29 +++++++-------- .../src/hir_ty_lowering/bounds.rs | 35 +++++++++---------- .../src/hir_ty_lowering/dyn_compatibility.rs | 3 +- compiler/rustc_hir_pretty/src/lib.rs | 14 +++++--- compiler/rustc_lint/src/traits.rs | 5 +-- compiler/rustc_middle/src/ty/diagnostics.rs | 2 +- .../error_reporting/infer/note_and_explain.rs | 2 +- src/librustdoc/clean/mod.rs | 4 +-- src/librustdoc/clean/types.rs | 19 ++++++---- src/librustdoc/html/format.rs | 14 ++++---- src/librustdoc/json/conversions.rs | 24 ++++++------- .../src/implied_bounds_in_impls.rs | 6 ++-- .../clippy_lints/src/needless_maybe_sized.rs | 6 ++-- .../clippy/clippy_lints/src/trait_bounds.rs | 14 ++++---- .../clippy/clippy_utils/src/hir_utils.rs | 14 +++++++- tests/ui/stats/hir-stats.stderr | 16 ++++----- 18 files changed, 116 insertions(+), 117 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 02cb6f188a71..8e4f4c8e71a2 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2697,7 +2697,7 @@ impl fmt::Debug for ImplPolarity { } /// The polarity of a trait bound. -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)] #[derive(HashStable_Generic)] pub enum BoundPolarity { /// `Type: Trait` @@ -2719,7 +2719,7 @@ impl BoundPolarity { } /// The constness of a trait bound. -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)] #[derive(HashStable_Generic)] pub enum BoundConstness { /// `Type: Trait` diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 4d8d22e09d92..28523bcb3bf7 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1956,7 +1956,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::GenericBound::Trait(hir::PolyTraitRef { bound_generic_params: &[], - modifiers: hir::TraitBoundModifier::None, + modifiers: hir::TraitBoundModifiers::NONE, trait_ref: hir::TraitRef { path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)), hir_ref_id: self.next_id(), @@ -2445,22 +2445,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_trait_bound_modifiers( &mut self, modifiers: TraitBoundModifiers, - ) -> hir::TraitBoundModifier { - // Invalid modifier combinations will cause an error during AST validation. - // Arbitrarily pick a placeholder for them to make compilation proceed. - match (modifiers.constness, modifiers.polarity) { - (BoundConstness::Never, BoundPolarity::Positive) => hir::TraitBoundModifier::None, - (_, BoundPolarity::Maybe(_)) => hir::TraitBoundModifier::Maybe, - (BoundConstness::Never, BoundPolarity::Negative(_)) => { - if self.tcx.features().negative_bounds { - hir::TraitBoundModifier::Negative - } else { - hir::TraitBoundModifier::None - } - } - (BoundConstness::Always(_), _) => hir::TraitBoundModifier::Const, - (BoundConstness::Maybe(_), _) => hir::TraitBoundModifier::MaybeConst, - } + ) -> hir::TraitBoundModifiers { + hir::TraitBoundModifiers { constness: modifiers.constness, polarity: modifiers.polarity } } // Helper methods for building HIR. @@ -2626,7 +2612,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => { let principal = hir::PolyTraitRef { bound_generic_params: &[], - modifiers: hir::TraitBoundModifier::None, + modifiers: hir::TraitBoundModifiers::NONE, trait_ref: hir::TraitRef { path, hir_ref_id: hir_id }, span: self.lower_span(span), }; diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 009c6c4aea55..45be04c6db9c 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -6,8 +6,8 @@ use rustc_ast::{ LitKind, TraitObjectSyntax, UintTy, }; pub use rustc_ast::{ - BinOp, BinOpKind, BindingMode, BorrowKind, ByRef, CaptureBy, ImplPolarity, IsAuto, Movability, - Mutability, UnOp, + BinOp, BinOpKind, BindingMode, BorrowKind, BoundConstness, BoundPolarity, ByRef, CaptureBy, + ImplPolarity, IsAuto, Movability, Mutability, UnOp, }; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; @@ -502,19 +502,16 @@ pub enum GenericArgsParentheses { ParenSugar, } -/// A modifier on a trait bound. +/// The modifiers on a trait bound. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)] -pub enum TraitBoundModifier { - /// `Type: Trait` - None, - /// `Type: !Trait` - Negative, - /// `Type: ?Trait` - Maybe, - /// `Type: const Trait` - Const, - /// `Type: ~const Trait` - MaybeConst, +pub struct TraitBoundModifiers { + pub constness: BoundConstness, + pub polarity: BoundPolarity, +} + +impl TraitBoundModifiers { + pub const NONE: Self = + TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive }; } #[derive(Clone, Copy, Debug, HashStable_Generic)] @@ -3180,7 +3177,7 @@ pub struct PolyTraitRef<'hir> { /// The constness and polarity of the trait ref. /// /// The `async` modifier is lowered directly into a different trait for now. - pub modifiers: TraitBoundModifier, + pub modifiers: TraitBoundModifiers, /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`. pub trait_ref: TraitRef<'hir>, @@ -4085,7 +4082,7 @@ mod size_asserts { static_assert_size!(ForeignItem<'_>, 88); static_assert_size!(ForeignItemKind<'_>, 56); static_assert_size!(GenericArg<'_>, 16); - static_assert_size!(GenericBound<'_>, 48); + static_assert_size!(GenericBound<'_>, 64); static_assert_size!(Generics<'_>, 56); static_assert_size!(Impl<'_>, 80); static_assert_size!(ImplItem<'_>, 88); diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 4721a3a0cf5a..a8b2b9b7c0ac 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -45,23 +45,22 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let hir::GenericBound::Trait(ptr) = hir_bound else { continue; }; - match ptr.modifiers { - hir::TraitBoundModifier::Maybe => unbounds.push(ptr), - hir::TraitBoundModifier::Negative => { + match ptr.modifiers.polarity { + hir::BoundPolarity::Maybe(_) => unbounds.push(ptr), + hir::BoundPolarity::Negative(_) => { if let Some(sized_def_id) = sized_def_id && ptr.trait_ref.path.res == Res::Def(DefKind::Trait, sized_def_id) { seen_negative_sized_bound = true; } } - hir::TraitBoundModifier::None => { + hir::BoundPolarity::Positive => { if let Some(sized_def_id) = sized_def_id && ptr.trait_ref.path.res == Res::Def(DefKind::Trait, sized_def_id) { seen_positive_sized_bound = true; } } - _ => {} } } }; @@ -169,20 +168,20 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { match hir_bound { hir::GenericBound::Trait(poly_trait_ref) => { - let (constness, polarity) = match poly_trait_ref.modifiers { - hir::TraitBoundModifier::Const => { - (Some(ty::BoundConstness::Const), ty::PredicatePolarity::Positive) - } - hir::TraitBoundModifier::MaybeConst => ( - Some(ty::BoundConstness::ConstIfConst), - ty::PredicatePolarity::Positive, - ), - hir::TraitBoundModifier::None => (None, ty::PredicatePolarity::Positive), - hir::TraitBoundModifier::Negative => { - (None, ty::PredicatePolarity::Negative) - } - hir::TraitBoundModifier::Maybe => continue, + let hir::TraitBoundModifiers { constness, polarity } = poly_trait_ref.modifiers; + // FIXME: We could pass these directly into `lower_poly_trait_ref` + // so that we could use these spans in diagnostics within that function... + let constness = match constness { + hir::BoundConstness::Never => None, + hir::BoundConstness::Always(_) => Some(ty::BoundConstness::Const), + hir::BoundConstness::Maybe(_) => Some(ty::BoundConstness::ConstIfConst), }; + let polarity = match polarity { + rustc_ast::BoundPolarity::Positive => ty::PredicatePolarity::Positive, + rustc_ast::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative, + rustc_ast::BoundPolarity::Maybe(_) => continue, + }; + let _ = self.lower_poly_trait_ref( &poly_trait_ref.trait_ref, poly_trait_ref.span, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index 4cb55ec8c890..2cee7c77aa53 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -40,8 +40,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut potential_assoc_types = Vec::new(); let dummy_self = self.tcx().types.trait_object_dummy_self; for trait_bound in hir_trait_bounds.iter().rev() { - // FIXME: This doesn't handle `? const`. - if trait_bound.modifiers == hir::TraitBoundModifier::Maybe { + if let hir::BoundPolarity::Maybe(_) = trait_bound.modifiers.polarity { continue; } if let GenericArgCountResult { diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 9ebfd4f15abd..3ba9c76bcee3 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -16,7 +16,6 @@ use rustc_ast_pretty::pprust::{Comments, PrintState}; use rustc_hir::{ BindingMode, ByRef, ConstArgKind, GenericArg, GenericBound, GenericParam, GenericParamKind, HirId, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term, - TraitBoundModifier, }; use rustc_span::FileName; use rustc_span::source_map::SourceMap; @@ -676,9 +675,16 @@ impl<'a> State<'a> { } fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) { - // FIXME: This isn't correct! - if t.modifiers == TraitBoundModifier::Maybe { - self.word("?"); + let hir::TraitBoundModifiers { constness, polarity } = t.modifiers; + match constness { + hir::BoundConstness::Never => {} + hir::BoundConstness::Always(_) => self.word("const"), + hir::BoundConstness::Maybe(_) => self.word("~const"), + } + match polarity { + hir::BoundPolarity::Positive => {} + hir::BoundPolarity::Negative(_) => self.word("!"), + hir::BoundPolarity::Maybe(_) => self.word("?"), } self.print_formal_generic_params(t.bound_generic_params); self.print_trait_ref(&t.trait_ref); diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index 5a3666dcbd43..b793ec6a4939 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -114,10 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { return }; for bound in &bounds[..] { let def_id = bound.trait_ref.trait_def_id(); - if def_id.is_some_and(|def_id| cx.tcx.is_lang_item(def_id, LangItem::Drop)) - // FIXME: ?Drop is not a thing. - && bound.modifiers != hir::TraitBoundModifier::Maybe - { + if def_id.is_some_and(|def_id| cx.tcx.is_lang_item(def_id, LangItem::Drop)) { let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; cx.emit_span_lint(DYN_DROP, bound.span, DropGlue { tcx: cx.tcx, def_id }); } diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 4f408ee15748..8bd2ae9128f7 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -193,7 +193,7 @@ fn suggest_changing_unsized_bound( .enumerate() .filter(|(_, bound)| { if let hir::GenericBound::Trait(poly) = bound - && poly.modifiers == hir::TraitBoundModifier::Maybe + && let hir::BoundPolarity::Maybe(_) = poly.modifiers.polarity && poly.trait_ref.trait_def_id() == def_id { true diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index 62204f63dd09..0cf7c43beb54 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -894,7 +894,7 @@ fn foo(&self) -> Self::T { String::new() } // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting. let trait_bounds = bounds.iter().filter_map(|bound| match bound { - hir::GenericBound::Trait(ptr) if ptr.modifiers == hir::TraitBoundModifier::None => { + hir::GenericBound::Trait(ptr) if ptr.modifiers == hir::TraitBoundModifiers::NONE => { Some(ptr) } _ => None, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7d4d8d8941dc..848f2abe6a9f 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -216,7 +216,7 @@ fn clean_generic_bound<'tcx>( hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)), hir::GenericBound::Trait(ref t) => { // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op. - if t.modifiers == hir::TraitBoundModifier::MaybeConst + if let hir::BoundConstness::Maybe(_) = t.modifiers.constness && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap()) { return None; @@ -263,7 +263,7 @@ fn clean_poly_trait_ref_with_constraints<'tcx>( trait_: clean_trait_ref_with_constraints(cx, poly_trait_ref, constraints), generic_params: clean_bound_vars(poly_trait_ref.bound_vars()), }, - hir::TraitBoundModifier::None, + hir::TraitBoundModifiers::NONE, ) } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 675507a44c9c..2e3050eee2fb 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1257,7 +1257,7 @@ impl Eq for Attributes {} #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) enum GenericBound { - TraitBound(PolyTrait, hir::TraitBoundModifier), + TraitBound(PolyTrait, hir::TraitBoundModifiers), Outlives(Lifetime), /// `use<'a, T>` precise-capturing bound syntax Use(Vec), @@ -1265,19 +1265,22 @@ pub(crate) enum GenericBound { impl GenericBound { pub(crate) fn sized(cx: &mut DocContext<'_>) -> GenericBound { - Self::sized_with(cx, hir::TraitBoundModifier::None) + Self::sized_with(cx, hir::TraitBoundModifiers::NONE) } pub(crate) fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound { - Self::sized_with(cx, hir::TraitBoundModifier::Maybe) + Self::sized_with(cx, hir::TraitBoundModifiers { + polarity: hir::BoundPolarity::Maybe(DUMMY_SP), + constness: hir::BoundConstness::Never, + }) } - fn sized_with(cx: &mut DocContext<'_>, modifier: hir::TraitBoundModifier) -> GenericBound { + fn sized_with(cx: &mut DocContext<'_>, modifiers: hir::TraitBoundModifiers) -> GenericBound { let did = cx.tcx.require_lang_item(LangItem::Sized, None); let empty = ty::Binder::dummy(ty::GenericArgs::empty()); let path = clean_middle_path(cx, did, false, ThinVec::new(), empty); inline::record_extern_fqn(cx, did, ItemType::Trait); - GenericBound::TraitBound(PolyTrait { trait_: path, generic_params: Vec::new() }, modifier) + GenericBound::TraitBound(PolyTrait { trait_: path, generic_params: Vec::new() }, modifiers) } pub(crate) fn is_trait_bound(&self) -> bool { @@ -1285,8 +1288,10 @@ impl GenericBound { } pub(crate) fn is_sized_bound(&self, cx: &DocContext<'_>) -> bool { - use rustc_hir::TraitBoundModifier as TBM; - if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self + if let GenericBound::TraitBound( + PolyTrait { ref trait_, .. }, + rustc_hir::TraitBoundModifiers::NONE, + ) = *self && Some(trait_.def_id()) == cx.tcx.lang_items().sized_trait() { return true; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 2e70a8c080de..5c599f20f9fd 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -399,13 +399,13 @@ impl clean::GenericBound { ) -> impl Display + 'a + Captures<'tcx> { display_fn(move |f| match self { clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()), - clean::GenericBound::TraitBound(ty, modifier) => { - f.write_str(match modifier { - hir::TraitBoundModifier::None => "", - hir::TraitBoundModifier::Maybe => "?", - hir::TraitBoundModifier::Negative => "!", - // `const` and `~const` trait bounds are experimental; don't render them. - hir::TraitBoundModifier::Const | hir::TraitBoundModifier::MaybeConst => "", + clean::GenericBound::TraitBound(ty, modifiers) => { + // `const` and `~const` trait bounds are experimental; don't render them. + let hir::TraitBoundModifiers { polarity, constness: _ } = modifiers; + f.write_str(match polarity { + hir::BoundPolarity::Positive => "", + hir::BoundPolarity::Maybe(_) => "?", + hir::BoundPolarity::Negative(_) => "!", })?; ty.print(cx).fmt(f) } diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 0130f2ce517b..7270f170780a 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -552,20 +552,18 @@ impl FromClean for GenericBound { } pub(crate) fn from_trait_bound_modifier( - modifier: rustc_hir::TraitBoundModifier, + modifiers: rustc_hir::TraitBoundModifiers, ) -> TraitBoundModifier { - use rustc_hir::TraitBoundModifier::*; - match modifier { - None => TraitBoundModifier::None, - Maybe => TraitBoundModifier::Maybe, - MaybeConst => TraitBoundModifier::MaybeConst, - // FIXME(const_trait_impl): Create rjt::TBM::Const and map to it once always-const bounds - // are less experimental. - Const => TraitBoundModifier::None, - // FIXME(negative-bounds): This bound should be rendered negative, but - // since that's experimental, maybe let's not add it to the rustdoc json - // API just now... - Negative => TraitBoundModifier::None, + use rustc_hir as hir; + let hir::TraitBoundModifiers { constness, polarity } = modifiers; + match (constness, polarity) { + (hir::BoundConstness::Never, hir::BoundPolarity::Positive) => TraitBoundModifier::None, + (hir::BoundConstness::Never, hir::BoundPolarity::Maybe(_)) => TraitBoundModifier::Maybe, + (hir::BoundConstness::Maybe(_), hir::BoundPolarity::Positive) => { + TraitBoundModifier::MaybeConst + } + // FIXME: Fill out the rest of this matrix. + _ => TraitBoundModifier::None, } } diff --git a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs index 00f832372248..65fdc93e0ed9 100644 --- a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs +++ b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs @@ -3,7 +3,7 @@ use clippy_utils::source::snippet; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_hir::def_id::DefId; use rustc_hir::{ - AssocItemConstraint, GenericArg, GenericBound, GenericBounds, PredicateOrigin, TraitBoundModifier, TyKind, + AssocItemConstraint, GenericArg, GenericBound, GenericBounds, PredicateOrigin, TraitBoundModifiers, TyKind, WherePredicate, }; use rustc_hir_analysis::lower_ty; @@ -234,7 +234,7 @@ fn collect_supertrait_bounds<'tcx>(cx: &LateContext<'tcx>, bounds: GenericBounds .iter() .filter_map(|bound| { if let GenericBound::Trait(poly_trait) = bound - && let TraitBoundModifier::None = poly_trait.modifiers + && let TraitBoundModifiers::NONE = poly_trait.modifiers && let [.., path] = poly_trait.trait_ref.path.segments && poly_trait.bound_generic_params.is_empty() && let Some(trait_def_id) = path.res.opt_def_id() @@ -300,7 +300,7 @@ fn check<'tcx>(cx: &LateContext<'tcx>, bounds: GenericBounds<'tcx>) { // simply comparing trait `DefId`s won't be enough. We also need to compare the generics. for (index, bound) in bounds.iter().enumerate() { if let GenericBound::Trait(poly_trait) = bound - && let TraitBoundModifier::None = poly_trait.modifiers + && let TraitBoundModifiers::NONE = poly_trait.modifiers && let [.., path] = poly_trait.trait_ref.path.segments && let implied_args = path.args.map_or([].as_slice(), |a| a.args) && let implied_constraints = path.args.map_or([].as_slice(), |a| a.constraints) diff --git a/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs b/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs index 68c9af07465d..9a1c397b5b23 100644 --- a/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs +++ b/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_errors::Applicability; use rustc_hir::def_id::{DefId, DefIdMap}; -use rustc_hir::{GenericBound, Generics, PolyTraitRef, TraitBoundModifier, WherePredicate}; +use rustc_hir::{GenericBound, Generics, PolyTraitRef, TraitBoundModifiers, BoundPolarity, WherePredicate}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{ClauseKind, PredicatePolarity}; use rustc_session::declare_lint_pass; @@ -118,13 +118,13 @@ impl LateLintPass<'_> for NeedlessMaybeSized { let maybe_sized_params: DefIdMap<_> = type_param_bounds(generics) .filter(|bound| { bound.trait_bound.trait_ref.trait_def_id() == Some(sized_trait) - && bound.trait_bound.modifiers == TraitBoundModifier::Maybe + && matches!(bound.trait_bound.modifiers.polarity, BoundPolarity::Maybe(_)) }) .map(|bound| (bound.param, bound)) .collect(); for bound in type_param_bounds(generics) { - if bound.trait_bound.modifiers == TraitBoundModifier::None + if bound.trait_bound.modifiers == TraitBoundModifiers::NONE && let Some(sized_bound) = maybe_sized_params.get(&bound.param) && let Some(path) = path_to_sized_bound(cx, bound.trait_bound) { diff --git a/src/tools/clippy/clippy_lints/src/trait_bounds.rs b/src/tools/clippy/clippy_lints/src/trait_bounds.rs index 7f528b9d17b8..3da4bf67558d 100644 --- a/src/tools/clippy/clippy_lints/src/trait_bounds.rs +++ b/src/tools/clippy/clippy_lints/src/trait_bounds.rs @@ -11,7 +11,7 @@ use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{ GenericBound, Generics, Item, ItemKind, LangItem, Node, Path, PathSegment, PredicateOrigin, QPath, - TraitBoundModifier, TraitItem, TraitRef, Ty, TyKind, WherePredicate, + TraitBoundModifiers, TraitItem, TraitRef, Ty, TyKind, WherePredicate, BoundPolarity, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; @@ -233,7 +233,7 @@ impl TraitBounds { fn cannot_combine_maybe_bound(&self, cx: &LateContext<'_>, bound: &GenericBound<'_>) -> bool { if !self.msrv.meets(msrvs::MAYBE_BOUND_IN_WHERE) && let GenericBound::Trait(tr) = bound - && let TraitBoundModifier::Maybe = tr.modifiers + && let BoundPolarity::Maybe(_) = tr.modifiers.polarity { cx.tcx.lang_items().get(LangItem::Sized) == tr.trait_ref.path.res.opt_def_id() } else { @@ -374,12 +374,12 @@ fn check_trait_bound_duplication<'tcx>(cx: &LateContext<'tcx>, generics: &'_ Gen struct ComparableTraitRef<'a, 'tcx> { cx: &'a LateContext<'tcx>, trait_ref: &'tcx TraitRef<'tcx>, - modifier: TraitBoundModifier, + modifiers: TraitBoundModifiers, } impl PartialEq for ComparableTraitRef<'_, '_> { fn eq(&self, other: &Self) -> bool { - self.modifier == other.modifier + SpanlessEq::new(self.cx).eq_modifiers(self.modifiers, other.modifiers) && SpanlessEq::new(self.cx) .paths_by_resolution() .eq_path(self.trait_ref.path, other.trait_ref.path) @@ -390,8 +390,8 @@ impl Hash for ComparableTraitRef<'_, '_> { fn hash(&self, state: &mut H) { let mut s = SpanlessHash::new(self.cx).paths_by_resolution(); s.hash_path(self.trait_ref.path); + s.hash_modifiers(self.modifiers); state.write_u64(s.finish()); - self.modifier.hash(state); } } @@ -400,7 +400,7 @@ fn get_trait_info_from_bound<'a>(bound: &'a GenericBound<'_>) -> Option<(Res, &' let trait_path = t.trait_ref.path; let trait_span = { let path_span = trait_path.span; - if let TraitBoundModifier::Maybe = t.modifiers { + if let BoundPolarity::Maybe(_) = t.modifiers.polarity { path_span.with_lo(path_span.lo() - BytePos(1)) // include the `?` } else { path_span @@ -427,7 +427,7 @@ fn rollup_traits<'cx, 'tcx>( ComparableTraitRef { cx, trait_ref: &t.trait_ref, - modifier: t.modifiers, + modifiers: t.modifiers, }, t.span, )) diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index 27c57808ecea..181d414cbbde 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -9,7 +9,8 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::{ ArrayLen, AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, Closure, ConstArg, ConstArgKind, Expr, ExprField, ExprKind, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime, - LifetimeName, Pat, PatField, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, Ty, TyKind, + LifetimeName, Pat, PatField, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitBoundModifiers, Ty, + TyKind, }; use rustc_lexer::{TokenKind, tokenize}; use rustc_lint::LateContext; @@ -126,6 +127,11 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool { self.inter_expr().eq_path_segments(left, right) } + + pub fn eq_modifiers(&mut self, left: TraitBoundModifiers, right: TraitBoundModifiers) -> bool { + std::mem::discriminant(&left.constness) == std::mem::discriminant(&right.constness) + && std::mem::discriminant(&left.polarity) == std::mem::discriminant(&right.polarity) + } } pub struct HirEqInterExpr<'a, 'b, 'tcx> { @@ -1143,6 +1149,12 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { } } + pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) { + let TraitBoundModifiers { constness, polarity } = modifiers; + std::mem::discriminant(&polarity).hash(&mut self.s); + std::mem::discriminant(&constness).hash(&mut self.s); + } + pub fn hash_stmt(&mut self, b: &Stmt<'_>) { std::mem::discriminant(&b.kind).hash(&mut self.s); diff --git a/tests/ui/stats/hir-stats.stderr b/tests/ui/stats/hir-stats.stderr index 3a2d4df3bee6..bd0c8cbc3b12 100644 --- a/tests/ui/stats/hir-stats.stderr +++ b/tests/ui/stats/hir-stats.stderr @@ -141,10 +141,10 @@ hir-stats FnDecl 120 ( 1.3%) 3 40 hir-stats Attribute 128 ( 1.4%) 4 32 hir-stats GenericArgs 144 ( 1.6%) 3 48 hir-stats Variant 144 ( 1.6%) 2 72 -hir-stats GenericBound 192 ( 2.1%) 4 48 -hir-stats - Trait 192 ( 2.1%) 4 hir-stats WherePredicate 192 ( 2.1%) 3 64 hir-stats - BoundPredicate 192 ( 2.1%) 3 +hir-stats GenericBound 256 ( 2.8%) 4 64 +hir-stats - Trait 256 ( 2.8%) 4 hir-stats Block 288 ( 3.2%) 6 48 hir-stats GenericParam 360 ( 4.0%) 5 72 hir-stats Pat 360 ( 4.0%) 5 72 @@ -155,15 +155,15 @@ hir-stats Generics 560 ( 6.2%) 10 56 hir-stats Ty 720 ( 8.0%) 15 48 hir-stats - Ref 48 ( 0.5%) 1 hir-stats - Ptr 48 ( 0.5%) 1 -hir-stats - Path 624 ( 7.0%) 13 -hir-stats Expr 768 ( 8.6%) 12 64 +hir-stats - Path 624 ( 6.9%) 13 +hir-stats Expr 768 ( 8.5%) 12 64 hir-stats - Path 64 ( 0.7%) 1 hir-stats - Match 64 ( 0.7%) 1 hir-stats - Struct 64 ( 0.7%) 1 hir-stats - InlineAsm 64 ( 0.7%) 1 hir-stats - Lit 128 ( 1.4%) 2 hir-stats - Block 384 ( 4.3%) 6 -hir-stats Item 968 (10.8%) 11 88 +hir-stats Item 968 (10.7%) 11 88 hir-stats - Enum 88 ( 1.0%) 1 hir-stats - Trait 88 ( 1.0%) 1 hir-stats - Impl 88 ( 1.0%) 1 @@ -171,8 +171,8 @@ hir-stats - ExternCrate 88 ( 1.0%) 1 hir-stats - ForeignMod 88 ( 1.0%) 1 hir-stats - Fn 176 ( 2.0%) 2 hir-stats - Use 352 ( 3.9%) 4 -hir-stats Path 1_240 (13.8%) 31 40 -hir-stats PathSegment 1_920 (21.4%) 40 48 +hir-stats Path 1_240 (13.7%) 31 40 +hir-stats PathSegment 1_920 (21.3%) 40 48 hir-stats ---------------------------------------------------------------- -hir-stats Total 8_960 +hir-stats Total 9_024 hir-stats From 0b52ec3d7e9135562569c5ee51ad1ad475ca1797 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 22 Oct 2024 19:57:58 +0000 Subject: [PATCH 133/366] Simplify confusing ResolvedArg constructors --- .../src/collect/resolve_bound_vars.rs | 103 ++++++++---------- 1 file changed, 46 insertions(+), 57 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index cb7f0901c7e4..c5d64ddb99b7 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -33,18 +33,12 @@ use crate::errors; #[extension(trait RegionExt)] impl ResolvedArg { - fn early(param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg) { - debug!("ResolvedArg::early: def_id={:?}", param.def_id); - (param.def_id, ResolvedArg::EarlyBound(param.def_id)) + fn early(param: &GenericParam<'_>) -> ResolvedArg { + ResolvedArg::EarlyBound(param.def_id) } - fn late(idx: u32, param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg) { - let depth = ty::INNERMOST; - debug!( - "ResolvedArg::late: idx={:?}, param={:?} depth={:?} def_id={:?}", - idx, param, depth, param.def_id, - ); - (param.def_id, ResolvedArg::LateBound(depth, idx, param.def_id)) + fn late(idx: u32, param: &GenericParam<'_>) -> ResolvedArg { + ResolvedArg::LateBound(ty::INNERMOST, idx, param.def_id) } fn id(&self) -> Option { @@ -282,24 +276,18 @@ fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBou fn late_arg_as_bound_arg<'tcx>( tcx: TyCtxt<'tcx>, - arg: &ResolvedArg, param: &GenericParam<'tcx>, ) -> ty::BoundVariableKind { - match arg { - ResolvedArg::LateBound(_, _, def_id) => { - let def_id = def_id.to_def_id(); - let name = tcx.item_name(def_id); - match param.kind { - GenericParamKind::Lifetime { .. } => { - ty::BoundVariableKind::Region(ty::BrNamed(def_id, name)) - } - GenericParamKind::Type { .. } => { - ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id, name)) - } - GenericParamKind::Const { .. } => ty::BoundVariableKind::Const, - } + let def_id = param.def_id.to_def_id(); + let name = tcx.item_name(def_id); + match param.kind { + GenericParamKind::Lifetime { .. } => { + ty::BoundVariableKind::Region(ty::BrNamed(def_id, name)) } - _ => bug!("{:?} is not a late argument", arg), + GenericParamKind::Type { .. } => { + ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id, name)) + } + GenericParamKind::Const { .. } => ty::BoundVariableKind::Const, } } @@ -360,10 +348,9 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { let mut bound_vars: FxIndexMap = FxIndexMap::default(); let binders_iter = trait_ref.bound_generic_params.iter().enumerate().map(|(late_bound_idx, param)| { - let pair = ResolvedArg::late(initial_bound_vars + late_bound_idx as u32, param); - let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); - bound_vars.insert(pair.0, pair.1); - r + let arg = ResolvedArg::late(initial_bound_vars + late_bound_idx as u32, param); + bound_vars.insert(param.def_id, arg); + late_arg_as_bound_arg(self.tcx, param) }); binders.extend(binders_iter); @@ -458,9 +445,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { .iter() .enumerate() .map(|(late_bound_idx, param)| { - let pair = ResolvedArg::late(late_bound_idx as u32, param); - let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); - (pair, r) + ( + (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)), + late_arg_as_bound_arg(self.tcx, param), + ) }) .unzip(); @@ -492,8 +480,8 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { let mut bound_vars = FxIndexMap::default(); debug!(?opaque.generics.params); for param in opaque.generics.params { - let (def_id, reg) = ResolvedArg::early(param); - bound_vars.insert(def_id, reg); + let arg = ResolvedArg::early(param); + bound_vars.insert(param.def_id, arg); } let hir_id = self.tcx.local_def_id_to_hir_id(opaque.def_id); @@ -618,9 +606,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { .iter() .enumerate() .map(|(late_bound_idx, param)| { - let pair = ResolvedArg::late(late_bound_idx as u32, param); - let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); - (pair, r) + ( + (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)), + late_arg_as_bound_arg(self.tcx, param), + ) }) .unzip(); @@ -870,9 +859,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { .iter() .enumerate() .map(|(late_bound_idx, param)| { - let pair = ResolvedArg::late(late_bound_idx as u32, param); - let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); - (pair, r) + ( + (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)), + late_arg_as_bound_arg(self.tcx, param), + ) }) .unzip(); @@ -1052,19 +1042,21 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { let bound_vars: FxIndexMap = generics .params .iter() - .map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - if self.tcx.is_late_bound(param.hir_id) { - let late_bound_idx = named_late_bound_vars; - named_late_bound_vars += 1; - ResolvedArg::late(late_bound_idx, param) - } else { + .map(|param| { + (param.def_id, match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.tcx.is_late_bound(param.hir_id) { + let late_bound_idx = named_late_bound_vars; + named_late_bound_vars += 1; + ResolvedArg::late(late_bound_idx, param) + } else { + ResolvedArg::early(param) + } + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { ResolvedArg::early(param) } - } - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - ResolvedArg::early(param) - } + }) }) .collect(); @@ -1075,11 +1067,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { matches!(param.kind, GenericParamKind::Lifetime { .. }) && self.tcx.is_late_bound(param.hir_id) }) - .enumerate() - .map(|(late_bound_idx, param)| { - let pair = ResolvedArg::late(late_bound_idx as u32, param); - late_arg_as_bound_arg(self.tcx, &pair.1, param) - }) + .map(|param| late_arg_as_bound_arg(self.tcx, param)) .collect(); self.record_late_bound_vars(hir_id, binders); let scope = Scope::Binder { @@ -1096,7 +1084,8 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { where F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>), { - let bound_vars = generics.params.iter().map(ResolvedArg::early).collect(); + let bound_vars = + generics.params.iter().map(|param| (param.def_id, ResolvedArg::early(param))).collect(); self.record_late_bound_vars(hir_id, vec![]); let scope = Scope::Binder { hir_id, From 1b7a91ed719ebc1f0615365a551f55ded1e9beed Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 22 Oct 2024 19:58:15 +0000 Subject: [PATCH 134/366] Deduplicate handling of early-bound params in RTN --- .../src/collect/resolve_bound_vars.rs | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index c5d64ddb99b7..0e9623ecb73b 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -291,6 +291,21 @@ fn late_arg_as_bound_arg<'tcx>( } } +/// Turn a [`ty::GenericParamDef`] into a bound arg. Generally, this should only +/// be used when turning early-bound vars into late-bound vars when lowering +/// return type notation. +fn generic_param_def_as_bound_arg(param: &ty::GenericParamDef) -> ty::BoundVariableKind { + match param.kind { + ty::GenericParamDefKind::Lifetime => { + ty::BoundVariableKind::Region(ty::BoundRegionKind::BrNamed(param.def_id, param.name)) + } + ty::GenericParamDefKind::Type { .. } => { + ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(param.def_id, param.name)) + } + ty::GenericParamDefKind::Const { .. } => ty::BoundVariableKind::Const, + } +} + impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref. fn poly_trait_ref_binder_info(&mut self) -> (Vec, BinderScopeType) { @@ -1628,17 +1643,13 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { constraint.ident, ty::AssocKind::Fn, ) { - bound_vars.extend(self.tcx.generics_of(assoc_fn.def_id).own_params.iter().map( - |param| match param.kind { - ty::GenericParamDefKind::Lifetime => ty::BoundVariableKind::Region( - ty::BoundRegionKind::BrNamed(param.def_id, param.name), - ), - ty::GenericParamDefKind::Type { .. } => ty::BoundVariableKind::Ty( - ty::BoundTyKind::Param(param.def_id, param.name), - ), - ty::GenericParamDefKind::Const { .. } => ty::BoundVariableKind::Const, - }, - )); + bound_vars.extend( + self.tcx + .generics_of(assoc_fn.def_id) + .own_params + .iter() + .map(|param| generic_param_def_as_bound_arg(param)), + ); bound_vars.extend( self.tcx.fn_sig(assoc_fn.def_id).instantiate_identity().bound_vars(), ); @@ -1957,17 +1968,13 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { // Append the early-bound vars on the function, and then the late-bound ones. // We actually turn type parameters into higher-ranked types here, but we // deny them later in HIR lowering. - bound_vars.extend(self.tcx.generics_of(item_def_id).own_params.iter().map(|param| { - match param.kind { - ty::GenericParamDefKind::Lifetime => ty::BoundVariableKind::Region( - ty::BoundRegionKind::BrNamed(param.def_id, param.name), - ), - ty::GenericParamDefKind::Type { .. } => { - ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(param.def_id, param.name)) - } - ty::GenericParamDefKind::Const { .. } => ty::BoundVariableKind::Const, - } - })); + bound_vars.extend( + self.tcx + .generics_of(item_def_id) + .own_params + .iter() + .map(|param| generic_param_def_as_bound_arg(param)), + ); bound_vars.extend(self.tcx.fn_sig(item_def_id).instantiate_identity().bound_vars()); // SUBTLE: Stash the old bound vars onto the *item segment* before appending From 196fdf144f638e2ce901c5f44c9d404bba8d1ed3 Mon Sep 17 00:00:00 2001 From: lcnr Date: Tue, 22 Oct 2024 23:07:51 +0200 Subject: [PATCH 135/366] do not relate `Abi` and `Safety` and update some macros while we're at it --- compiler/rustc_middle/src/ty/relate.rs | 22 ---- .../rustc_middle/src/ty/structural_impls.rs | 7 +- compiler/rustc_type_ir/src/error.rs | 4 +- compiler/rustc_type_ir/src/inherent.rs | 4 +- compiler/rustc_type_ir/src/relate.rs | 15 ++- compiler/rustc_type_ir/src/ty_kind.rs | 4 + compiler/rustc_type_ir/src/ty_kind/closure.rs | 4 + compiler/rustc_type_ir_macros/src/lib.rs | 114 +++++++++++------- 8 files changed, 99 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 4c7bcb1bf2e8..504a3c8a6d83 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -1,7 +1,5 @@ use std::iter; -use rustc_hir as hir; -use rustc_target::spec::abi; pub use rustc_type_ir::relate::*; use crate::ty::error::{ExpectedFound, TypeError}; @@ -121,26 +119,6 @@ impl<'tcx> Relate> for &'tcx ty::List Relate> for hir::Safety { - fn relate>>( - _relation: &mut R, - a: hir::Safety, - b: hir::Safety, - ) -> RelateResult<'tcx, hir::Safety> { - if a != b { Err(TypeError::SafetyMismatch(ExpectedFound::new(true, a, b))) } else { Ok(a) } - } -} - -impl<'tcx> Relate> for abi::Abi { - fn relate>>( - _relation: &mut R, - a: abi::Abi, - b: abi::Abi, - ) -> RelateResult<'tcx, abi::Abi> { - if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(ExpectedFound::new(true, a, b))) } - } -} - impl<'tcx> Relate> for ty::GenericArgsRef<'tcx> { fn relate>>( relation: &mut R, diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index cd9ff9b60d85..4872d8c89eb8 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -264,8 +264,6 @@ TrivialTypeTraversalImpls! { // interners). TrivialTypeTraversalAndLiftImpls! { ::rustc_hir::def_id::DefId, - ::rustc_hir::Safety, - ::rustc_target::spec::abi::Abi, crate::ty::ClosureKind, crate::ty::ParamConst, crate::ty::ParamTy, @@ -276,6 +274,11 @@ TrivialTypeTraversalAndLiftImpls! { rustc_target::abi::Size, } +TrivialLiftImpls! { + ::rustc_hir::Safety, + ::rustc_target::spec::abi::Abi, +} + /////////////////////////////////////////////////////////////////////////// // Lift implementations diff --git a/compiler/rustc_type_ir/src/error.rs b/compiler/rustc_type_ir/src/error.rs index 8a6d37b7d23f..725019457210 100644 --- a/compiler/rustc_type_ir/src/error.rs +++ b/compiler/rustc_type_ir/src/error.rs @@ -29,8 +29,8 @@ pub enum TypeError { Mismatch, ConstnessMismatch(ExpectedFound), PolarityMismatch(ExpectedFound), - SafetyMismatch(ExpectedFound), - AbiMismatch(ExpectedFound), + SafetyMismatch(#[type_visitable(ignore)] ExpectedFound), + AbiMismatch(#[type_visitable(ignore)] ExpectedFound), Mutability, ArgumentMutability(usize), TupleSize(ExpectedFound), diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index f7875bb51527..02ec29a7f3d5 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -208,14 +208,14 @@ pub trait Tys>: fn output(self) -> I::Ty; } -pub trait Abi>: Copy + Debug + Hash + Eq + Relate { +pub trait Abi>: Copy + Debug + Hash + Eq { fn rust() -> Self; /// Whether this ABI is `extern "Rust"`. fn is_rust(self) -> bool; } -pub trait Safety>: Copy + Debug + Hash + Eq + Relate { +pub trait Safety>: Copy + Debug + Hash + Eq { fn safe() -> Self; fn is_safe(self) -> bool; diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index a0b93064694e..ccb8e9fcf7ce 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -174,12 +174,17 @@ impl Relate for ty::FnSig { ExpectedFound::new(true, a, b) })); } - let safety = relation.relate(a.safety, b.safety)?; - let abi = relation.relate(a.abi, b.abi)?; + + if a.safety != b.safety { + return Err(TypeError::SafetyMismatch(ExpectedFound::new(true, a.safety, b.safety))); + } + + if a.abi != b.abi { + return Err(TypeError::AbiMismatch(ExpectedFound::new(true, a.abi, b.abi))); + }; let a_inputs = a.inputs(); let b_inputs = b.inputs(); - if a_inputs.len() != b_inputs.len() { return Err(TypeError::ArgCount); } @@ -212,8 +217,8 @@ impl Relate for ty::FnSig { Ok(ty::FnSig { inputs_and_output: cx.mk_type_list_from_iter(inputs_and_output)?, c_variadic: a.c_variadic, - safety, - abi, + safety: a.safety, + abi: a.abi, }) } } diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index b7f6ef4ffbb9..499e6d3dd37d 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -861,7 +861,11 @@ pub struct TypeAndMut { pub struct FnSig { pub inputs_and_output: I::Tys, pub c_variadic: bool, + #[type_visitable(ignore)] + #[type_foldable(identity)] pub safety: I::Safety, + #[type_visitable(ignore)] + #[type_foldable(identity)] pub abi: I::Abi, } diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index 09a43b179551..10b164eae027 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -372,8 +372,12 @@ pub struct CoroutineClosureSignature { /// Always false pub c_variadic: bool, /// Always `Normal` (safe) + #[type_visitable(ignore)] + #[type_foldable(identity)] pub safety: I::Safety, /// Always `RustCall` + #[type_visitable(ignore)] + #[type_foldable(identity)] pub abi: I::Abi, } diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index 1a0a2479f6f0..aaf69e2648d5 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -1,18 +1,73 @@ -use quote::quote; -use syn::parse_quote; +use quote::{ToTokens, quote}; use syn::visit_mut::VisitMut; +use syn::{Attribute, parse_quote}; use synstructure::decl_derive; decl_derive!( - [TypeFoldable_Generic] => type_foldable_derive + [TypeVisitable_Generic, attributes(type_visitable)] => type_visitable_derive ); decl_derive!( - [TypeVisitable_Generic] => type_visitable_derive + [TypeFoldable_Generic, attributes(type_foldable)] => type_foldable_derive ); decl_derive!( [Lift_Generic] => lift_derive ); +fn has_ignore_attr(attrs: &[Attribute], name: &'static str, meta: &'static str) -> bool { + let mut ignored = false; + attrs.iter().for_each(|attr| { + if !attr.path().is_ident(name) { + return; + } + let _ = attr.parse_nested_meta(|nested| { + if nested.path.is_ident(meta) { + ignored = true; + } + Ok(()) + }); + }); + + ignored +} + +fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { + if let syn::Data::Union(_) = s.ast().data { + panic!("cannot derive on union") + } + + if !s.ast().generics.type_params().any(|ty| ty.ident == "I") { + s.add_impl_generic(parse_quote! { I }); + } + + s.filter(|bi| !has_ignore_attr(&bi.ast().attrs, "type_visitable", "ignore")); + + s.add_where_predicate(parse_quote! { I: Interner }); + s.add_bounds(synstructure::AddBounds::Fields); + let body_visit = s.each(|bind| { + quote! { + match ::rustc_ast_ir::visit::VisitorResult::branch( + ::rustc_type_ir::visit::TypeVisitable::visit_with(#bind, __visitor) + ) { + ::core::ops::ControlFlow::Continue(()) => {}, + ::core::ops::ControlFlow::Break(r) => { + return ::rustc_ast_ir::visit::VisitorResult::from_residual(r); + }, + } + } + }); + s.bind_with(|_| synstructure::BindStyle::Move); + + s.bound_impl(quote!(::rustc_type_ir::visit::TypeVisitable), quote! { + fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor>( + &self, + __visitor: &mut __V + ) -> __V::Result { + match *self { #body_visit } + <__V::Result as ::rustc_ast_ir::visit::VisitorResult>::output() + } + }) +} + fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { if let syn::Data::Union(_) = s.ast().data { panic!("cannot derive on union") @@ -29,12 +84,23 @@ fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke let bindings = vi.bindings(); vi.construct(|_, index| { let bind = &bindings[index]; - quote! { - ::rustc_type_ir::fold::TypeFoldable::try_fold_with(#bind, __folder)? + + // retain value of fields with #[type_foldable(identity)] + if has_ignore_attr(&bind.ast().attrs, "type_foldable", "identity") { + bind.to_token_stream() + } else { + quote! { + ::rustc_type_ir::fold::TypeFoldable::try_fold_with(#bind, __folder)? + } } }) }); + // We filter fields which get ignored and don't require them to implement + // `TypeFoldable`. We do so after generating `body_fold` as we still need + // to generate code for them. + s.filter(|bi| !has_ignore_attr(&bi.ast().attrs, "type_foldable", "identity")); + s.add_bounds(synstructure::AddBounds::Fields); s.bound_impl(quote!(::rustc_type_ir::fold::TypeFoldable), quote! { fn try_fold_with<__F: ::rustc_type_ir::fold::FallibleTypeFolder>( self, @@ -113,39 +179,3 @@ fn lift(mut ty: syn::Type) -> syn::Type { ty } - -fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { - if let syn::Data::Union(_) = s.ast().data { - panic!("cannot derive on union") - } - - if !s.ast().generics.type_params().any(|ty| ty.ident == "I") { - s.add_impl_generic(parse_quote! { I }); - } - - s.add_where_predicate(parse_quote! { I: Interner }); - s.add_bounds(synstructure::AddBounds::Fields); - let body_visit = s.each(|bind| { - quote! { - match ::rustc_ast_ir::visit::VisitorResult::branch( - ::rustc_type_ir::visit::TypeVisitable::visit_with(#bind, __visitor) - ) { - ::core::ops::ControlFlow::Continue(()) => {}, - ::core::ops::ControlFlow::Break(r) => { - return ::rustc_ast_ir::visit::VisitorResult::from_residual(r); - }, - } - } - }); - s.bind_with(|_| synstructure::BindStyle::Move); - - s.bound_impl(quote!(::rustc_type_ir::visit::TypeVisitable), quote! { - fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor>( - &self, - __visitor: &mut __V - ) -> __V::Result { - match *self { #body_visit } - <__V::Result as ::rustc_ast_ir::visit::VisitorResult>::output() - } - }) -} From 00266eeaa5957f0dde0b17f2823fd4b4ea6996c2 Mon Sep 17 00:00:00 2001 From: lcnr Date: Wed, 23 Oct 2024 00:52:37 +0200 Subject: [PATCH 136/366] remove `PredicatePolarity` and `BoundConstness` relate impls Also removes `TypeError::ConstnessMismatch`. It is unused. --- compiler/rustc_middle/src/ty/error.rs | 3 --- compiler/rustc_type_ir/src/error.rs | 9 +++---- compiler/rustc_type_ir/src/relate.rs | 39 +++++---------------------- 3 files changed, 11 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index b02eff3bfd6a..c49824bb418c 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -35,9 +35,6 @@ impl<'tcx> TypeError<'tcx> { TypeError::CyclicTy(_) => "cyclic type of infinite size".into(), TypeError::CyclicConst(_) => "encountered a self-referencing constant".into(), TypeError::Mismatch => "types differ".into(), - TypeError::ConstnessMismatch(values) => { - format!("expected {} bound, found {} bound", values.expected, values.found).into() - } TypeError::PolarityMismatch(values) => { format!("expected {} polarity, found {} polarity", values.expected, values.found) .into() diff --git a/compiler/rustc_type_ir/src/error.rs b/compiler/rustc_type_ir/src/error.rs index 725019457210..cdff77f742d0 100644 --- a/compiler/rustc_type_ir/src/error.rs +++ b/compiler/rustc_type_ir/src/error.rs @@ -27,8 +27,7 @@ impl ExpectedFound { #[cfg_attr(feature = "nightly", rustc_pass_by_value)] pub enum TypeError { Mismatch, - ConstnessMismatch(ExpectedFound), - PolarityMismatch(ExpectedFound), + PolarityMismatch(#[type_visitable(ignore)] ExpectedFound), SafetyMismatch(#[type_visitable(ignore)] ExpectedFound), AbiMismatch(#[type_visitable(ignore)] ExpectedFound), Mutability, @@ -73,9 +72,9 @@ impl TypeError { pub fn must_include_note(self) -> bool { use self::TypeError::*; match self { - CyclicTy(_) | CyclicConst(_) | SafetyMismatch(_) | ConstnessMismatch(_) - | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_) - | ArgumentSorts(..) | Sorts(_) | VariadicMismatch(_) | TargetFeatureCast(_) => false, + CyclicTy(_) | CyclicConst(_) | SafetyMismatch(_) | PolarityMismatch(_) | Mismatch + | AbiMismatch(_) | FixedArraySize(_) | ArgumentSorts(..) | Sorts(_) + | VariadicMismatch(_) | TargetFeatureCast(_) => false, Mutability | ArgumentMutability(_) diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index ccb8e9fcf7ce..ad17911830b3 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -223,20 +223,6 @@ impl Relate for ty::FnSig { } } -impl Relate for ty::BoundConstness { - fn relate>( - _relation: &mut R, - a: ty::BoundConstness, - b: ty::BoundConstness, - ) -> RelateResult { - if a != b { - Err(TypeError::ConstnessMismatch(ExpectedFound::new(true, a, b))) - } else { - Ok(a) - } - } -} - impl Relate for ty::AliasTy { fn relate>( relation: &mut R, @@ -664,29 +650,18 @@ impl> Relate for ty::Binder { } } -impl Relate for ty::PredicatePolarity { - fn relate>( - _relation: &mut R, - a: ty::PredicatePolarity, - b: ty::PredicatePolarity, - ) -> RelateResult { - if a != b { - Err(TypeError::PolarityMismatch(ExpectedFound::new(true, a, b))) - } else { - Ok(a) - } - } -} - impl Relate for ty::TraitPredicate { fn relate>( relation: &mut R, a: ty::TraitPredicate, b: ty::TraitPredicate, ) -> RelateResult> { - Ok(ty::TraitPredicate { - trait_ref: relation.relate(a.trait_ref, b.trait_ref)?, - polarity: relation.relate(a.polarity, b.polarity)?, - }) + let trait_ref = relation.relate(a.trait_ref, b.trait_ref)?; + if a.polarity != b.polarity { + return Err(TypeError::PolarityMismatch(ExpectedFound::new( + true, a.polarity, b.polarity, + ))); + } + Ok(ty::TraitPredicate { trait_ref, polarity: a.polarity }) } } From 8ca39104f1af6871ccc6119ddfda37aa76f628fb Mon Sep 17 00:00:00 2001 From: Henry Jiang Date: Tue, 22 Oct 2024 20:18:11 -0400 Subject: [PATCH 137/366] AIX use /dev/urandom for impl --- library/std/src/random.rs | 2 +- library/std/src/sys/random/mod.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/library/std/src/random.rs b/library/std/src/random.rs index cdb88c795bfd..45f51dd37b04 100644 --- a/library/std/src/random.rs +++ b/library/std/src/random.rs @@ -38,7 +38,7 @@ use crate::sys::random as sys; /// Vita | `arc4random_buf` /// Hermit | `read_entropy` /// Horizon | `getrandom` shim -/// Hurd, L4Re, QNX | `/dev/urandom` +/// AIX, Hurd, L4Re, QNX | `/dev/urandom` /// Redox | `/scheme/rand` /// RTEMS | [`arc4random_buf`](https://docs.rtems.org/branches/master/bsp-howto/getentropy.html) /// SGX | [`rdrand`](https://en.wikipedia.org/wiki/RDRAND) diff --git a/library/std/src/sys/random/mod.rs b/library/std/src/sys/random/mod.rs index edc2cacdfd87..f42351deb92c 100644 --- a/library/std/src/sys/random/mod.rs +++ b/library/std/src/sys/random/mod.rs @@ -40,6 +40,7 @@ cfg_if::cfg_if! { mod horizon; pub use horizon::fill_bytes; } else if #[cfg(any( + target_os = "aix", target_os = "hurd", target_os = "l4re", target_os = "nto", From 03df13b70ded5c95bfd5dad82e1bbe169f4a78f1 Mon Sep 17 00:00:00 2001 From: Asuna Date: Wed, 16 Oct 2024 23:46:39 +0200 Subject: [PATCH 138/366] Introduce `adjust_for_rust_abi` in `rustc_target` --- compiler/rustc_target/src/callconv/mod.rs | 117 +++++++++++++++++- compiler/rustc_target/src/callconv/x86.rs | 37 +++++- compiler/rustc_ty_utils/src/abi.rs | 138 ++-------------------- 3 files changed, 159 insertions(+), 133 deletions(-) diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 5d120a68059a..0d2a0e8f5517 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -1,11 +1,14 @@ -use std::fmt; use std::str::FromStr; +use std::{fmt, iter}; pub use rustc_abi::{Reg, RegKind}; use rustc_macros::HashStable_Generic; use rustc_span::Symbol; -use crate::abi::{self, Abi, Align, HasDataLayout, Size, TyAbiInterface, TyAndLayout}; +use crate::abi::{ + self, Abi, AddressSpace, Align, HasDataLayout, Pointer, Size, TyAbiInterface, TyAndLayout, +}; +use crate::spec::abi::Abi as SpecAbi; use crate::spec::{self, HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, WasmCAbi}; mod aarch64; @@ -720,6 +723,116 @@ impl<'a, Ty> FnAbi<'a, Ty> { Ok(()) } + + pub fn adjust_for_rust_abi(&mut self, cx: &C, abi: SpecAbi) + where + Ty: TyAbiInterface<'a, C> + Copy, + C: HasDataLayout + HasTargetSpec, + { + let spec = cx.target_spec(); + match &spec.arch[..] { + "x86" => x86::compute_rust_abi_info(cx, self, abi), + _ => {} + }; + + for (arg_idx, arg) in self + .args + .iter_mut() + .enumerate() + .map(|(idx, arg)| (Some(idx), arg)) + .chain(iter::once((None, &mut self.ret))) + { + if arg.is_ignore() { + continue; + } + + if arg_idx.is_none() && arg.layout.size > Pointer(AddressSpace::DATA).size(cx) * 2 { + // Return values larger than 2 registers using a return area + // pointer. LLVM and Cranelift disagree about how to return + // values that don't fit in the registers designated for return + // values. LLVM will force the entire return value to be passed + // by return area pointer, while Cranelift will look at each IR level + // return value independently and decide to pass it in a + // register or not, which would result in the return value + // being passed partially in registers and partially through a + // return area pointer. + // + // While Cranelift may need to be fixed as the LLVM behavior is + // generally more correct with respect to the surface language, + // forcing this behavior in rustc itself makes it easier for + // other backends to conform to the Rust ABI and for the C ABI + // rustc already handles this behavior anyway. + // + // In addition LLVM's decision to pass the return value in + // registers or using a return area pointer depends on how + // exactly the return type is lowered to an LLVM IR type. For + // example `Option` can be lowered as `{ i128, i128 }` + // in which case the x86_64 backend would use a return area + // pointer, or it could be passed as `{ i32, i128 }` in which + // case the x86_64 backend would pass it in registers by taking + // advantage of an LLVM ABI extension that allows using 3 + // registers for the x86_64 sysv call conv rather than the + // officially specified 2 registers. + // + // FIXME: Technically we should look at the amount of available + // return registers rather than guessing that there are 2 + // registers for return values. In practice only a couple of + // architectures have less than 2 return registers. None of + // which supported by Cranelift. + // + // NOTE: This adjustment is only necessary for the Rust ABI as + // for other ABI's the calling convention implementations in + // rustc_target already ensure any return value which doesn't + // fit in the available amount of return registers is passed in + // the right way for the current target. + arg.make_indirect(); + continue; + } + + match arg.layout.abi { + Abi::Aggregate { .. } => {} + + // This is a fun case! The gist of what this is doing is + // that we want callers and callees to always agree on the + // ABI of how they pass SIMD arguments. If we were to *not* + // make these arguments indirect then they'd be immediates + // in LLVM, which means that they'd used whatever the + // appropriate ABI is for the callee and the caller. That + // means, for example, if the caller doesn't have AVX + // enabled but the callee does, then passing an AVX argument + // across this boundary would cause corrupt data to show up. + // + // This problem is fixed by unconditionally passing SIMD + // arguments through memory between callers and callees + // which should get them all to agree on ABI regardless of + // target feature sets. Some more information about this + // issue can be found in #44367. + // + // Note that the intrinsic ABI is exempt here as + // that's how we connect up to LLVM and it's unstable + // anyway, we control all calls to it in libstd. + Abi::Vector { .. } if abi != SpecAbi::RustIntrinsic && spec.simd_types_indirect => { + arg.make_indirect(); + continue; + } + + _ => continue, + } + // Compute `Aggregate` ABI. + + let is_indirect_not_on_stack = + matches!(arg.mode, PassMode::Indirect { on_stack: false, .. }); + assert!(is_indirect_not_on_stack); + + let size = arg.layout.size; + if !arg.layout.is_unsized() && size <= Pointer(AddressSpace::DATA).size(cx) { + // We want to pass small aggregates as immediates, but using + // an LLVM aggregate type for this leads to bad optimizations, + // so we pick an appropriately sized integer type instead. + arg.cast_to(Reg { kind: RegKind::Integer, size }); + } + } + } } impl FromStr for Conv { diff --git a/compiler/rustc_target/src/callconv/x86.rs b/compiler/rustc_target/src/callconv/x86.rs index 40c3e7a891a0..e907beecb381 100644 --- a/compiler/rustc_target/src/callconv/x86.rs +++ b/compiler/rustc_target/src/callconv/x86.rs @@ -1,6 +1,9 @@ use crate::abi::call::{ArgAttribute, FnAbi, PassMode, Reg, RegKind}; -use crate::abi::{Abi, Align, HasDataLayout, TyAbiInterface, TyAndLayout}; +use crate::abi::{ + Abi, AddressSpace, Align, Float, HasDataLayout, Pointer, TyAbiInterface, TyAndLayout, +}; use crate::spec::HasTargetSpec; +use crate::spec::abi::Abi as SpecAbi; #[derive(PartialEq)] pub(crate) enum Flavor { @@ -207,3 +210,35 @@ pub(crate) fn fill_inregs<'a, Ty, C>( } } } + +pub(crate) fn compute_rust_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, abi: SpecAbi) +where + Ty: TyAbiInterface<'a, C> + Copy, + C: HasDataLayout + HasTargetSpec, +{ + // Avoid returning floats in x87 registers on x86 as loading and storing from x87 + // registers will quiet signalling NaNs. Also avoid using SSE registers since they + // are not always available (depending on target features). + if !fn_abi.ret.is_ignore() + // Intrinsics themselves are not actual "real" functions, so theres no need to change their ABIs. + && abi != SpecAbi::RustIntrinsic + { + let has_float = match fn_abi.ret.layout.abi { + Abi::Scalar(s) => matches!(s.primitive(), Float(_)), + Abi::ScalarPair(s1, s2) => { + matches!(s1.primitive(), Float(_)) || matches!(s2.primitive(), Float(_)) + } + _ => false, // anyway not passed via registers on x86 + }; + if has_float { + if fn_abi.ret.layout.size <= Pointer(AddressSpace::DATA).size(cx) { + // Same size or smaller than pointer, return in a register. + fn_abi.ret.cast_to(Reg { kind: RegKind::Integer, size: fn_abi.ret.layout.size }); + } else { + // Larger than a pointer, return indirectly. + fn_abi.ret.make_indirect(); + } + return; + } + } +} diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 09b9ecb3486e..48149a08de88 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -1,7 +1,7 @@ use std::iter; -use rustc_abi::Primitive::{Float, Pointer}; -use rustc_abi::{Abi, AddressSpace, PointerKind, Scalar, Size}; +use rustc_abi::Primitive::Pointer; +use rustc_abi::{Abi, PointerKind, Scalar, Size}; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::bug; @@ -13,8 +13,7 @@ use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt}; use rustc_session::config::OptLevel; use rustc_span::def_id::DefId; use rustc_target::abi::call::{ - ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, Conv, FnAbi, PassMode, Reg, RegKind, - RiscvInterruptKind, + ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, Conv, FnAbi, PassMode, RiscvInterruptKind, }; use rustc_target::spec::abi::Abi as SpecAbi; use tracing::debug; @@ -678,6 +677,8 @@ fn fn_abi_adjust_for_abi<'tcx>( let tcx = cx.tcx(); if abi == SpecAbi::Rust || abi == SpecAbi::RustCall || abi == SpecAbi::RustIntrinsic { + fn_abi.adjust_for_rust_abi(cx, abi); + // Look up the deduced parameter attributes for this function, if we have its def ID and // we're optimizing in non-incremental mode. We'll tag its parameters with those attributes // as appropriate. @@ -688,125 +689,9 @@ fn fn_abi_adjust_for_abi<'tcx>( &[] }; - let fixup = |arg: &mut ArgAbi<'tcx, Ty<'tcx>>, arg_idx: Option| { + for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() { if arg.is_ignore() { - return; - } - - // Avoid returning floats in x87 registers on x86 as loading and storing from x87 - // registers will quiet signalling NaNs. Also avoid using SSE registers since they - // are not always available (depending on target features). - if tcx.sess.target.arch == "x86" - && arg_idx.is_none() - // Intrinsics themselves are not actual "real" functions, so theres no need to - // change their ABIs. - && abi != SpecAbi::RustIntrinsic - { - let has_float = match arg.layout.abi { - Abi::Scalar(s) => matches!(s.primitive(), Float(_)), - Abi::ScalarPair(s1, s2) => { - matches!(s1.primitive(), Float(_)) || matches!(s2.primitive(), Float(_)) - } - _ => false, // anyway not passed via registers on x86 - }; - if has_float { - if arg.layout.size <= Pointer(AddressSpace::DATA).size(cx) { - // Same size or smaller than pointer, return in a register. - arg.cast_to(Reg { kind: RegKind::Integer, size: arg.layout.size }); - } else { - // Larger than a pointer, return indirectly. - arg.make_indirect(); - } - return; - } - } - - if arg_idx.is_none() && arg.layout.size > Pointer(AddressSpace::DATA).size(cx) * 2 { - // Return values larger than 2 registers using a return area - // pointer. LLVM and Cranelift disagree about how to return - // values that don't fit in the registers designated for return - // values. LLVM will force the entire return value to be passed - // by return area pointer, while Cranelift will look at each IR level - // return value independently and decide to pass it in a - // register or not, which would result in the return value - // being passed partially in registers and partially through a - // return area pointer. - // - // While Cranelift may need to be fixed as the LLVM behavior is - // generally more correct with respect to the surface language, - // forcing this behavior in rustc itself makes it easier for - // other backends to conform to the Rust ABI and for the C ABI - // rustc already handles this behavior anyway. - // - // In addition LLVM's decision to pass the return value in - // registers or using a return area pointer depends on how - // exactly the return type is lowered to an LLVM IR type. For - // example `Option` can be lowered as `{ i128, i128 }` - // in which case the x86_64 backend would use a return area - // pointer, or it could be passed as `{ i32, i128 }` in which - // case the x86_64 backend would pass it in registers by taking - // advantage of an LLVM ABI extension that allows using 3 - // registers for the x86_64 sysv call conv rather than the - // officially specified 2 registers. - // - // FIXME: Technically we should look at the amount of available - // return registers rather than guessing that there are 2 - // registers for return values. In practice only a couple of - // architectures have less than 2 return registers. None of - // which supported by Cranelift. - // - // NOTE: This adjustment is only necessary for the Rust ABI as - // for other ABI's the calling convention implementations in - // rustc_target already ensure any return value which doesn't - // fit in the available amount of return registers is passed in - // the right way for the current target. - arg.make_indirect(); - return; - } - - match arg.layout.abi { - Abi::Aggregate { .. } => {} - - // This is a fun case! The gist of what this is doing is - // that we want callers and callees to always agree on the - // ABI of how they pass SIMD arguments. If we were to *not* - // make these arguments indirect then they'd be immediates - // in LLVM, which means that they'd used whatever the - // appropriate ABI is for the callee and the caller. That - // means, for example, if the caller doesn't have AVX - // enabled but the callee does, then passing an AVX argument - // across this boundary would cause corrupt data to show up. - // - // This problem is fixed by unconditionally passing SIMD - // arguments through memory between callers and callees - // which should get them all to agree on ABI regardless of - // target feature sets. Some more information about this - // issue can be found in #44367. - // - // Note that the intrinsic ABI is exempt here as - // that's how we connect up to LLVM and it's unstable - // anyway, we control all calls to it in libstd. - Abi::Vector { .. } - if abi != SpecAbi::RustIntrinsic && tcx.sess.target.simd_types_indirect => - { - arg.make_indirect(); - return; - } - - _ => return, - } - // Compute `Aggregate` ABI. - - let is_indirect_not_on_stack = - matches!(arg.mode, PassMode::Indirect { on_stack: false, .. }); - assert!(is_indirect_not_on_stack, "{:?}", arg); - - let size = arg.layout.size; - if !arg.layout.is_unsized() && size <= Pointer(AddressSpace::DATA).size(cx) { - // We want to pass small aggregates as immediates, but using - // an LLVM aggregate type for this leads to bad optimizations, - // so we pick an appropriately sized integer type instead. - arg.cast_to(Reg { kind: RegKind::Integer, size }); + continue; } // If we deduced that this parameter was read-only, add that to the attribute list now. @@ -814,9 +699,7 @@ fn fn_abi_adjust_for_abi<'tcx>( // The `readonly` parameter only applies to pointers, so we can only do this if the // argument was passed indirectly. (If the argument is passed directly, it's an SSA // value, so it's implicitly immutable.) - if let (Some(arg_idx), &mut PassMode::Indirect { ref mut attrs, .. }) = - (arg_idx, &mut arg.mode) - { + if let &mut PassMode::Indirect { ref mut attrs, .. } = &mut arg.mode { // The `deduced_param_attrs` list could be empty if this is a type of function // we can't deduce any parameters for, so make sure the argument index is in // bounds. @@ -827,11 +710,6 @@ fn fn_abi_adjust_for_abi<'tcx>( } } } - }; - - fixup(&mut fn_abi.ret, None); - for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() { - fixup(arg, Some(arg_idx)); } } else { fn_abi From 6b6552462031422f41d6b39303f892ca9a4a7b5f Mon Sep 17 00:00:00 2001 From: Asuna Date: Sun, 20 Oct 2024 02:36:36 +0200 Subject: [PATCH 139/366] Set `signext` or `zeroext` for integer arguments on RISC-V --- compiler/rustc_target/src/callconv/mod.rs | 1 + compiler/rustc_target/src/callconv/riscv.rs | 27 ++++++ tests/assembly/rust-abi-arg-attr.rs | 96 +++++++++++++++++++ tests/codegen/checked_ilog.rs | 2 +- tests/codegen/checked_math.rs | 12 +-- tests/codegen/comparison-operators-newtype.rs | 8 +- tests/codegen/fewer-names.rs | 4 +- tests/codegen/function-arguments.rs | 8 +- tests/codegen/intrinsics/three_way_compare.rs | 6 +- tests/codegen/mir-aggregate-no-alloca.rs | 14 +-- tests/codegen/range-attribute.rs | 4 +- .../rust-abi-arch-specific-adjustment.rs | 93 ++++++++++++++++++ tests/codegen/transmute-scalar.rs | 2 +- tests/codegen/union-abi.rs | 2 +- tests/codegen/var-names.rs | 2 +- 15 files changed, 248 insertions(+), 33 deletions(-) create mode 100644 tests/assembly/rust-abi-arg-attr.rs create mode 100644 tests/codegen/rust-abi-arch-specific-adjustment.rs diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 0d2a0e8f5517..811ef4e3069c 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -732,6 +732,7 @@ impl<'a, Ty> FnAbi<'a, Ty> { let spec = cx.target_spec(); match &spec.arch[..] { "x86" => x86::compute_rust_abi_info(cx, self, abi), + "riscv32" | "riscv64" => riscv::compute_rust_abi_info(cx, self, abi), _ => {} }; diff --git a/compiler/rustc_target/src/callconv/riscv.rs b/compiler/rustc_target/src/callconv/riscv.rs index be6bc701b497..f96169e6a618 100644 --- a/compiler/rustc_target/src/callconv/riscv.rs +++ b/compiler/rustc_target/src/callconv/riscv.rs @@ -7,6 +7,7 @@ use crate::abi::call::{ArgAbi, ArgExtension, CastTarget, FnAbi, PassMode, Reg, RegKind, Uniform}; use crate::abi::{self, Abi, FieldsShape, HasDataLayout, Size, TyAbiInterface, TyAndLayout}; use crate::spec::HasTargetSpec; +use crate::spec::abi::Abi as SpecAbi; #[derive(Copy, Clone)] enum RegPassKind { @@ -365,3 +366,29 @@ where ); } } + +pub(crate) fn compute_rust_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, abi: SpecAbi) +where + Ty: TyAbiInterface<'a, C> + Copy, + C: HasDataLayout + HasTargetSpec, +{ + if abi == SpecAbi::RustIntrinsic { + return; + } + + let xlen = cx.data_layout().pointer_size.bits(); + + for arg in fn_abi.args.iter_mut() { + if arg.is_ignore() { + continue; + } + + // LLVM integers types do not differentiate between signed or unsigned integers. + // Some RISC-V instructions do not have a `.w` suffix version, they use all the + // XLEN bits. By explicitly setting the `signext` or `zeroext` attribute + // according to signedness to avoid unnecessary integer extending instructions. + // + // See https://github.com/rust-lang/rust/issues/114508 for details. + extend_integer_width(arg, xlen); + } +} diff --git a/tests/assembly/rust-abi-arg-attr.rs b/tests/assembly/rust-abi-arg-attr.rs new file mode 100644 index 000000000000..2226aa8fa5ad --- /dev/null +++ b/tests/assembly/rust-abi-arg-attr.rs @@ -0,0 +1,96 @@ +//@ assembly-output: emit-asm +//@ revisions: riscv64 riscv64-zbb +//@ compile-flags: -C opt-level=3 +//@ [riscv64] compile-flags: --target riscv64gc-unknown-linux-gnu +//@ [riscv64] needs-llvm-components: riscv +//@ [riscv64-zbb] compile-flags: --target riscv64gc-unknown-linux-gnu +//@ [riscv64-zbb] compile-flags: -C target-feature=+zbb +//@ [riscv64-zbb] needs-llvm-components: riscv + +#![feature(no_core, lang_items, intrinsics, rustc_attrs)] +#![crate_type = "lib"] +#![no_std] +#![no_core] + +// FIXME: Migrate these code after PR #130693 is landed. +// vvvvv core + +#[lang = "sized"] +trait Sized {} + +#[lang = "copy"] +trait Copy {} + +impl Copy for i8 {} +impl Copy for u32 {} +impl Copy for i32 {} + +#[lang = "neg"] +trait Neg { + type Output; + + fn neg(self) -> Self::Output; +} + +impl Neg for i8 { + type Output = i8; + + fn neg(self) -> Self::Output { + -self + } +} + +#[lang = "Ordering"] +#[repr(i8)] +enum Ordering { + Less = -1, + Equal = 0, + Greater = 1, +} + +extern "rust-intrinsic" { + #[rustc_safe_intrinsic] + fn three_way_compare(lhs: T, rhs: T) -> Ordering; +} + +// ^^^^^ core + +// Reimplementation of function `{integer}::max`. +macro_rules! max { + ($a:expr, $b:expr) => { + match three_way_compare($a, $b) { + Ordering::Less | Ordering::Equal => $b, + Ordering::Greater => $a, + } + }; +} + +#[no_mangle] +// CHECK-LABEL: issue_114508_u32: +pub fn issue_114508_u32(a: u32, b: u32) -> u32 { + // CHECK-NEXT: .cfi_startproc + + // riscv64-NEXT: bltu a1, a0, .[[RET:.+]] + // riscv64-NEXT: mv a0, a1 + // riscv64-NEXT: .[[RET]]: + + // riscv64-zbb-NEXT: maxu a0, a0, a1 + + // CHECK-NEXT: ret + max!(a, b) +} + +#[no_mangle] +// CHECK-LABEL: issue_114508_i32: +pub fn issue_114508_i32(a: i32, b: i32) -> i32 { + // CHECK-NEXT: .cfi_startproc + + // riscv64-NEXT: blt a1, a0, .[[RET:.+]] + // riscv64-NEXT: mv a0, a1 + // riscv64-NEXT: .[[RET]]: + + // riscv64-zbb-NEXT: max a0, a0, a1 + + // CHECK-NEXT: ret + max!(a, b) +} diff --git a/tests/codegen/checked_ilog.rs b/tests/codegen/checked_ilog.rs index 8f3c07119fee..d7dfc7c29e7d 100644 --- a/tests/codegen/checked_ilog.rs +++ b/tests/codegen/checked_ilog.rs @@ -5,7 +5,7 @@ // Ensure that when val < base, we do not divide or multiply. // CHECK-LABEL: @checked_ilog -// CHECK-SAME: (i16 noundef %val, i16 noundef %base) +// CHECK-SAME: (i16{{.*}} %val, i16{{.*}} %base) #[no_mangle] pub fn checked_ilog(val: u16, base: u16) -> Option { // CHECK-NOT: udiv diff --git a/tests/codegen/checked_math.rs b/tests/codegen/checked_math.rs index 75df5866d6ea..63f5c3d34f7a 100644 --- a/tests/codegen/checked_math.rs +++ b/tests/codegen/checked_math.rs @@ -8,7 +8,7 @@ // Thanks to poison semantics, this doesn't even need branches. // CHECK-LABEL: @checked_sub_unsigned -// CHECK-SAME: (i16 noundef %a, i16 noundef %b) +// CHECK-SAME: (i16{{.*}} %a, i16{{.*}} %b) #[no_mangle] pub fn checked_sub_unsigned(a: u16, b: u16) -> Option { // CHECK-DAG: %[[IS_SOME:.+]] = icmp uge i16 %a, %b @@ -26,7 +26,7 @@ pub fn checked_sub_unsigned(a: u16, b: u16) -> Option { // looking for no-wrap flags, we just need there to not be any masking. // CHECK-LABEL: @checked_shl_unsigned -// CHECK-SAME: (i32 noundef %a, i32 noundef %b) +// CHECK-SAME: (i32{{.*}} %a, i32{{.*}} %b) #[no_mangle] pub fn checked_shl_unsigned(a: u32, b: u32) -> Option { // CHECK-DAG: %[[IS_SOME:.+]] = icmp ult i32 %b, 32 @@ -41,7 +41,7 @@ pub fn checked_shl_unsigned(a: u32, b: u32) -> Option { } // CHECK-LABEL: @checked_shr_unsigned -// CHECK-SAME: (i32 noundef %a, i32 noundef %b) +// CHECK-SAME: (i32{{.*}} %a, i32{{.*}} %b) #[no_mangle] pub fn checked_shr_unsigned(a: u32, b: u32) -> Option { // CHECK-DAG: %[[IS_SOME:.+]] = icmp ult i32 %b, 32 @@ -56,7 +56,7 @@ pub fn checked_shr_unsigned(a: u32, b: u32) -> Option { } // CHECK-LABEL: @checked_shl_signed -// CHECK-SAME: (i32 noundef %a, i32 noundef %b) +// CHECK-SAME: (i32{{.*}} %a, i32{{.*}} %b) #[no_mangle] pub fn checked_shl_signed(a: i32, b: u32) -> Option { // CHECK-DAG: %[[IS_SOME:.+]] = icmp ult i32 %b, 32 @@ -71,7 +71,7 @@ pub fn checked_shl_signed(a: i32, b: u32) -> Option { } // CHECK-LABEL: @checked_shr_signed -// CHECK-SAME: (i32 noundef %a, i32 noundef %b) +// CHECK-SAME: (i32{{.*}} %a, i32{{.*}} %b) #[no_mangle] pub fn checked_shr_signed(a: i32, b: u32) -> Option { // CHECK-DAG: %[[IS_SOME:.+]] = icmp ult i32 %b, 32 @@ -86,7 +86,7 @@ pub fn checked_shr_signed(a: i32, b: u32) -> Option { } // CHECK-LABEL: @checked_add_one_unwrap_unsigned -// CHECK-SAME: (i32 noundef %x) +// CHECK-SAME: (i32{{.*}} %x) #[no_mangle] pub fn checked_add_one_unwrap_unsigned(x: u32) -> u32 { // CHECK: %[[IS_MAX:.+]] = icmp eq i32 %x, -1 diff --git a/tests/codegen/comparison-operators-newtype.rs b/tests/codegen/comparison-operators-newtype.rs index d336c4e6ed3d..acce0cb59467 100644 --- a/tests/codegen/comparison-operators-newtype.rs +++ b/tests/codegen/comparison-operators-newtype.rs @@ -12,7 +12,7 @@ use std::cmp::Ordering; pub struct Foo(u16); // CHECK-LABEL: @check_lt -// CHECK-SAME: (i16 noundef %[[A:.+]], i16 noundef %[[B:.+]]) +// CHECK-SAME: (i16{{.*}} %[[A:.+]], i16{{.*}} %[[B:.+]]) #[no_mangle] pub fn check_lt(a: Foo, b: Foo) -> bool { // CHECK: %[[R:.+]] = icmp ult i16 %[[A]], %[[B]] @@ -21,7 +21,7 @@ pub fn check_lt(a: Foo, b: Foo) -> bool { } // CHECK-LABEL: @check_le -// CHECK-SAME: (i16 noundef %[[A:.+]], i16 noundef %[[B:.+]]) +// CHECK-SAME: (i16{{.*}} %[[A:.+]], i16{{.*}} %[[B:.+]]) #[no_mangle] pub fn check_le(a: Foo, b: Foo) -> bool { // CHECK: %[[R:.+]] = icmp ule i16 %[[A]], %[[B]] @@ -30,7 +30,7 @@ pub fn check_le(a: Foo, b: Foo) -> bool { } // CHECK-LABEL: @check_gt -// CHECK-SAME: (i16 noundef %[[A:.+]], i16 noundef %[[B:.+]]) +// CHECK-SAME: (i16{{.*}} %[[A:.+]], i16{{.*}} %[[B:.+]]) #[no_mangle] pub fn check_gt(a: Foo, b: Foo) -> bool { // CHECK: %[[R:.+]] = icmp ugt i16 %[[A]], %[[B]] @@ -39,7 +39,7 @@ pub fn check_gt(a: Foo, b: Foo) -> bool { } // CHECK-LABEL: @check_ge -// CHECK-SAME: (i16 noundef %[[A:.+]], i16 noundef %[[B:.+]]) +// CHECK-SAME: (i16{{.*}} %[[A:.+]], i16{{.*}} %[[B:.+]]) #[no_mangle] pub fn check_ge(a: Foo, b: Foo) -> bool { // CHECK: %[[R:.+]] = icmp uge i16 %[[A]], %[[B]] diff --git a/tests/codegen/fewer-names.rs b/tests/codegen/fewer-names.rs index b14dd30482c5..a171629a076b 100644 --- a/tests/codegen/fewer-names.rs +++ b/tests/codegen/fewer-names.rs @@ -6,11 +6,11 @@ #[no_mangle] pub fn sum(x: u32, y: u32) -> u32 { - // YES-LABEL: define{{.*}}i32 @sum(i32 noundef %0, i32 noundef %1) + // YES-LABEL: define{{.*}}i32 @sum(i32{{.*}} %0, i32{{.*}} %1) // YES-NEXT: %3 = add i32 %1, %0 // YES-NEXT: ret i32 %3 - // NO-LABEL: define{{.*}}i32 @sum(i32 noundef %x, i32 noundef %y) + // NO-LABEL: define{{.*}}i32 @sum(i32{{.*}} %x, i32{{.*}} %y) // NO-NEXT: start: // NO-NEXT: %z = add i32 %y, %x // NO-NEXT: ret i32 %z diff --git a/tests/codegen/function-arguments.rs b/tests/codegen/function-arguments.rs index bf9f405192b6..7fa1d6598854 100644 --- a/tests/codegen/function-arguments.rs +++ b/tests/codegen/function-arguments.rs @@ -32,7 +32,7 @@ pub fn boolean(x: bool) -> bool { x } -// CHECK: i8 @maybeuninit_boolean(i8 %x) +// CHECK: i8 @maybeuninit_boolean(i8{{.*}} %x) #[no_mangle] pub fn maybeuninit_boolean(x: MaybeUninit) -> MaybeUninit { x @@ -44,19 +44,19 @@ pub fn enum_bool(x: MyBool) -> MyBool { x } -// CHECK: i8 @maybeuninit_enum_bool(i8 %x) +// CHECK: i8 @maybeuninit_enum_bool(i8{{.*}} %x) #[no_mangle] pub fn maybeuninit_enum_bool(x: MaybeUninit) -> MaybeUninit { x } -// CHECK: noundef{{( range\(i32 0, 1114112\))?}} i32 @char(i32 noundef{{( range\(i32 0, 1114112\))?}} %x) +// CHECK: noundef{{( range\(i32 0, 1114112\))?}} i32 @char(i32{{.*}}{{( range\(i32 0, 1114112\))?}} %x) #[no_mangle] pub fn char(x: char) -> char { x } -// CHECK: i32 @maybeuninit_char(i32 %x) +// CHECK: i32 @maybeuninit_char(i32{{.*}} %x) #[no_mangle] pub fn maybeuninit_char(x: MaybeUninit) -> MaybeUninit { x diff --git a/tests/codegen/intrinsics/three_way_compare.rs b/tests/codegen/intrinsics/three_way_compare.rs index f3b631abc227..9a476abe8914 100644 --- a/tests/codegen/intrinsics/three_way_compare.rs +++ b/tests/codegen/intrinsics/three_way_compare.rs @@ -10,8 +10,7 @@ use std::intrinsics::three_way_compare; #[no_mangle] // CHECK-LABEL: @signed_cmp -// DEBUG-SAME: (i16 %a, i16 %b) -// OPTIM-SAME: (i16 noundef %a, i16 noundef %b) +// CHECK-SAME: (i16{{.*}} %a, i16{{.*}} %b) pub fn signed_cmp(a: i16, b: i16) -> std::cmp::Ordering { // DEBUG: %[[GT:.+]] = icmp sgt i16 %a, %b // DEBUG: %[[ZGT:.+]] = zext i1 %[[GT]] to i8 @@ -29,8 +28,7 @@ pub fn signed_cmp(a: i16, b: i16) -> std::cmp::Ordering { #[no_mangle] // CHECK-LABEL: @unsigned_cmp -// DEBUG-SAME: (i16 %a, i16 %b) -// OPTIM-SAME: (i16 noundef %a, i16 noundef %b) +// CHECK-SAME: (i16{{.*}} %a, i16{{.*}} %b) pub fn unsigned_cmp(a: u16, b: u16) -> std::cmp::Ordering { // DEBUG: %[[GT:.+]] = icmp ugt i16 %a, %b // DEBUG: %[[ZGT:.+]] = zext i1 %[[GT]] to i8 diff --git a/tests/codegen/mir-aggregate-no-alloca.rs b/tests/codegen/mir-aggregate-no-alloca.rs index 04ffb0755382..37b024a55b37 100644 --- a/tests/codegen/mir-aggregate-no-alloca.rs +++ b/tests/codegen/mir-aggregate-no-alloca.rs @@ -9,7 +9,7 @@ #[repr(transparent)] pub struct Transparent32(u32); -// CHECK: i32 @make_transparent(i32 noundef %x) +// CHECK: i32 @make_transparent(i32{{.*}} %x) #[no_mangle] pub fn make_transparent(x: u32) -> Transparent32 { // CHECK-NOT: alloca @@ -18,7 +18,7 @@ pub fn make_transparent(x: u32) -> Transparent32 { a } -// CHECK: i32 @make_closure(i32 noundef %x) +// CHECK: i32 @make_closure(i32{{.*}} %x) #[no_mangle] pub fn make_closure(x: i32) -> impl Fn(i32) -> i32 { // CHECK-NOT: alloca @@ -40,7 +40,7 @@ pub fn make_transparent_pair(x: (u16, u16)) -> TransparentPair { a } -// CHECK-LABEL: { i32, i32 } @make_2_tuple(i32 noundef %x) +// CHECK-LABEL: { i32, i32 } @make_2_tuple(i32{{.*}} %x) #[no_mangle] pub fn make_2_tuple(x: u32) -> (u32, u32) { // CHECK-NOT: alloca @@ -59,7 +59,7 @@ pub fn make_cell_of_bool(b: bool) -> std::cell::Cell { std::cell::Cell::new(b) } -// CHECK-LABEL: { i8, i16 } @make_cell_of_bool_and_short(i1 noundef zeroext %b, i16 noundef %s) +// CHECK-LABEL: { i8, i16 } @make_cell_of_bool_and_short(i1 noundef zeroext %b, i16{{.*}} %s) #[no_mangle] pub fn make_cell_of_bool_and_short(b: bool, s: u16) -> std::cell::Cell<(bool, u16)> { // CHECK-NOT: alloca @@ -92,7 +92,7 @@ pub fn make_struct_0() -> Struct0 { pub struct Struct1(i32); -// CHECK-LABEL: i32 @make_struct_1(i32 noundef %a) +// CHECK-LABEL: i32 @make_struct_1(i32{{.*}} %a) #[no_mangle] pub fn make_struct_1(a: i32) -> Struct1 { // CHECK: ret i32 %a @@ -104,7 +104,7 @@ pub struct Struct2Asc(i16, i64); // bit32-LABEL: void @make_struct_2_asc({{.*}} sret({{[^,]*}}) {{.*}} %s, // bit64-LABEL: { i64, i16 } @make_struct_2_asc( -// CHECK-SAME: i16 noundef %a, i64 noundef %b) +// CHECK-SAME: i16{{.*}} %a, i64 noundef %b) #[no_mangle] pub fn make_struct_2_asc(a: i16, b: i64) -> Struct2Asc { // CHECK-NOT: alloca @@ -122,7 +122,7 @@ pub struct Struct2Desc(i64, i16); // bit32-LABEL: void @make_struct_2_desc({{.*}} sret({{[^,]*}}) {{.*}} %s, // bit64-LABEL: { i64, i16 } @make_struct_2_desc( -// CHECK-SAME: i64 noundef %a, i16 noundef %b) +// CHECK-SAME: i64 noundef %a, i16{{.*}} %b) #[no_mangle] pub fn make_struct_2_desc(a: i64, b: i16) -> Struct2Desc { // CHECK-NOT: alloca diff --git a/tests/codegen/range-attribute.rs b/tests/codegen/range-attribute.rs index 8972fc76ca28..a44ec1026b16 100644 --- a/tests/codegen/range-attribute.rs +++ b/tests/codegen/range-attribute.rs @@ -24,7 +24,7 @@ pub fn nonzero_int(x: NonZero) -> NonZero { x } -// CHECK: noundef range(i8 0, 3) i8 @optional_bool(i8 noundef range(i8 0, 3) %x) +// CHECK: noundef range(i8 0, 3) i8 @optional_bool(i8{{.*}} range(i8 0, 3) %x) #[no_mangle] pub fn optional_bool(x: Option) -> Option { x @@ -36,7 +36,7 @@ pub enum Enum0 { C, } -// CHECK: noundef range(i8 0, 4) i8 @enum0_value(i8 noundef range(i8 0, 4) %x) +// CHECK: noundef range(i8 0, 4) i8 @enum0_value(i8{{.*}} range(i8 0, 4) %x) #[no_mangle] pub fn enum0_value(x: Enum0) -> Enum0 { x diff --git a/tests/codegen/rust-abi-arch-specific-adjustment.rs b/tests/codegen/rust-abi-arch-specific-adjustment.rs new file mode 100644 index 000000000000..87a7cd8ae263 --- /dev/null +++ b/tests/codegen/rust-abi-arch-specific-adjustment.rs @@ -0,0 +1,93 @@ +//@ compile-flags: -O -C no-prepopulate-passes +//@ revisions: riscv64 + +//@[riscv64] only-riscv64 +//@[riscv64] compile-flags: --target riscv64gc-unknown-linux-gnu +//@[riscv64] needs-llvm-components: riscv + +#![crate_type = "lib"] + +#[no_mangle] +// riscv64: define noundef i8 @arg_attr_u8(i8 noundef zeroext %x) +pub fn arg_attr_u8(x: u8) -> u8 { + x +} + +#[no_mangle] +// riscv64: define noundef i16 @arg_attr_u16(i16 noundef zeroext %x) +pub fn arg_attr_u16(x: u16) -> u16 { + x +} + +#[no_mangle] +// riscv64: define noundef i32 @arg_attr_u32(i32 noundef signext %x) +pub fn arg_attr_u32(x: u32) -> u32 { + x +} + +#[no_mangle] +// riscv64: define noundef i64 @arg_attr_u64(i64 noundef %x) +pub fn arg_attr_u64(x: u64) -> u64 { + x +} + +#[no_mangle] +// riscv64: define noundef i128 @arg_attr_u128(i128 noundef %x) +pub fn arg_attr_u128(x: u128) -> u128 { + x +} + +#[no_mangle] +// riscv64: define noundef i8 @arg_attr_i8(i8 noundef signext %x) +pub fn arg_attr_i8(x: i8) -> i8 { + x +} + +#[no_mangle] +// riscv64: define noundef i16 @arg_attr_i16(i16 noundef signext %x) +pub fn arg_attr_i16(x: i16) -> i16 { + x +} + +#[no_mangle] +// riscv64: define noundef i32 @arg_attr_i32(i32 noundef signext %x) +pub fn arg_attr_i32(x: i32) -> i32 { + x +} + +#[no_mangle] +// riscv64: define noundef i64 @arg_attr_i64(i64 noundef %x) +pub fn arg_attr_i64(x: i64) -> i64 { + x +} + +#[no_mangle] +// riscv64: define noundef i128 @arg_attr_i128(i128 noundef %x) +pub fn arg_attr_i128(x: i128) -> i128 { + x +} + +#[no_mangle] +// riscv64: define noundef zeroext i1 @arg_attr_bool(i1 noundef zeroext %x) +pub fn arg_attr_bool(x: bool) -> bool { + x +} + +#[no_mangle] +// ignore-tidy-linelength +// riscv64: define noundef{{( range\(i32 0, 1114112\))?}} i32 @arg_attr_char(i32 noundef signext{{( range\(i32 0, 1114112\))?}} %x) +pub fn arg_attr_char(x: char) -> char { + x +} + +#[no_mangle] +// riscv64: define noundef float @arg_attr_f32(float noundef %x) +pub fn arg_attr_f32(x: f32) -> f32 { + x +} + +#[no_mangle] +// riscv64: define noundef double @arg_attr_f64(double noundef %x) +pub fn arg_attr_f64(x: f64) -> f64 { + x +} diff --git a/tests/codegen/transmute-scalar.rs b/tests/codegen/transmute-scalar.rs index caaa70962d5b..43da7c1781ef 100644 --- a/tests/codegen/transmute-scalar.rs +++ b/tests/codegen/transmute-scalar.rs @@ -25,7 +25,7 @@ pub fn bool_to_byte(b: bool) -> u8 { unsafe { std::mem::transmute(b) } } -// CHECK-LABEL: define{{.*}}zeroext i1 @byte_to_bool(i8 %byte) +// CHECK-LABEL: define{{.*}}zeroext i1 @byte_to_bool(i8{{.*}} %byte) // CHECK: %_0 = trunc i8 %byte to i1 // CHECK-NEXT: ret i1 %_0 #[no_mangle] diff --git a/tests/codegen/union-abi.rs b/tests/codegen/union-abi.rs index b3c67a59730d..2f14682dfa57 100644 --- a/tests/codegen/union-abi.rs +++ b/tests/codegen/union-abi.rs @@ -131,7 +131,7 @@ pub fn test_CUnionU128(_: CUnionU128) { pub union UnionBool { b: bool, } -// CHECK: define {{(dso_local )?}}noundef zeroext i1 @test_UnionBool(i8 %b) +// CHECK: define {{(dso_local )?}}noundef zeroext i1 @test_UnionBool(i8{{.*}} %b) #[no_mangle] pub fn test_UnionBool(b: UnionBool) -> bool { unsafe { b.b } diff --git a/tests/codegen/var-names.rs b/tests/codegen/var-names.rs index fd163a55551b..4ea5b3b436d8 100644 --- a/tests/codegen/var-names.rs +++ b/tests/codegen/var-names.rs @@ -2,7 +2,7 @@ #![crate_type = "lib"] -// CHECK-LABEL: define{{.*}}i32 @test(i32 noundef %a, i32 noundef %b) +// CHECK-LABEL: define{{.*}}i32 @test(i32{{.*}} %a, i32{{.*}} %b) #[no_mangle] pub fn test(a: u32, b: u32) -> u32 { let c = a + b; From 57bffe1d59cb6caa39c6ae5f5620c0cb371eea72 Mon Sep 17 00:00:00 2001 From: Asuna Date: Sun, 20 Oct 2024 23:17:04 +0200 Subject: [PATCH 140/366] Set `signext` or `zeroext` for integer arguments on LoongArch64 --- .../rustc_target/src/callconv/loongarch.rs | 28 +++++++++++ compiler/rustc_target/src/callconv/mod.rs | 1 + tests/assembly/rust-abi-arg-attr.rs | 14 +++++- .../rust-abi-arch-specific-adjustment.rs | 48 +++++++++++++------ .../cfi/emit-type-checks-attr-no-sanitize.rs | 2 +- .../codegen/sanitizer/cfi/emit-type-checks.rs | 2 +- 6 files changed, 77 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_target/src/callconv/loongarch.rs b/compiler/rustc_target/src/callconv/loongarch.rs index 4a21935623b9..ffec76370d02 100644 --- a/compiler/rustc_target/src/callconv/loongarch.rs +++ b/compiler/rustc_target/src/callconv/loongarch.rs @@ -1,6 +1,7 @@ use crate::abi::call::{ArgAbi, ArgExtension, CastTarget, FnAbi, PassMode, Reg, RegKind, Uniform}; use crate::abi::{self, Abi, FieldsShape, HasDataLayout, Size, TyAbiInterface, TyAndLayout}; use crate::spec::HasTargetSpec; +use crate::spec::abi::Abi as SpecAbi; #[derive(Copy, Clone)] enum RegPassKind { @@ -359,3 +360,30 @@ where ); } } + +pub(crate) fn compute_rust_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, abi: SpecAbi) +where + Ty: TyAbiInterface<'a, C> + Copy, + C: HasDataLayout + HasTargetSpec, +{ + if abi == SpecAbi::RustIntrinsic { + return; + } + + let grlen = cx.data_layout().pointer_size.bits(); + + for arg in fn_abi.args.iter_mut() { + if arg.is_ignore() { + continue; + } + + // LLVM integers types do not differentiate between signed or unsigned integers. + // Some LoongArch instructions do not have a `.w` suffix version, they use all the + // GRLEN bits. By explicitly setting the `signext` or `zeroext` attribute + // according to signedness to avoid unnecessary integer extending instructions. + // + // This is similar to the RISC-V case, see + // https://github.com/rust-lang/rust/issues/114508 for details. + extend_integer_width(arg, grlen); + } +} diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 811ef4e3069c..25b001b57e8a 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -733,6 +733,7 @@ impl<'a, Ty> FnAbi<'a, Ty> { match &spec.arch[..] { "x86" => x86::compute_rust_abi_info(cx, self, abi), "riscv32" | "riscv64" => riscv::compute_rust_abi_info(cx, self, abi), + "loongarch64" => loongarch::compute_rust_abi_info(cx, self, abi), _ => {} }; diff --git a/tests/assembly/rust-abi-arg-attr.rs b/tests/assembly/rust-abi-arg-attr.rs index 2226aa8fa5ad..2a113eed4ba4 100644 --- a/tests/assembly/rust-abi-arg-attr.rs +++ b/tests/assembly/rust-abi-arg-attr.rs @@ -1,11 +1,13 @@ //@ assembly-output: emit-asm -//@ revisions: riscv64 riscv64-zbb +//@ revisions: riscv64 riscv64-zbb loongarch64 //@ compile-flags: -C opt-level=3 //@ [riscv64] compile-flags: --target riscv64gc-unknown-linux-gnu //@ [riscv64] needs-llvm-components: riscv //@ [riscv64-zbb] compile-flags: --target riscv64gc-unknown-linux-gnu //@ [riscv64-zbb] compile-flags: -C target-feature=+zbb //@ [riscv64-zbb] needs-llvm-components: riscv +//@ [loongarch64] compile-flags: --target loongarch64-unknown-linux-gnu +//@ [loongarch64] needs-llvm-components: loongarch #![feature(no_core, lang_items, intrinsics, rustc_attrs)] #![crate_type = "lib"] @@ -76,6 +78,11 @@ pub fn issue_114508_u32(a: u32, b: u32) -> u32 { // riscv64-zbb-NEXT: maxu a0, a0, a1 + // loongarch64-NEXT: sltu $a2, $a1, $a0 + // loongarch64-NEXT: masknez $a1, $a1, $a2 + // loongarch64-NEXT: maskeqz $a0, $a0, $a2 + // loongarch64-NEXT: or $a0, $a0, $a1 + // CHECK-NEXT: ret max!(a, b) } @@ -91,6 +98,11 @@ pub fn issue_114508_i32(a: i32, b: i32) -> i32 { // riscv64-zbb-NEXT: max a0, a0, a1 + // loongarch64-NEXT: slt $a2, $a1, $a0 + // loongarch64-NEXT: masknez $a1, $a1, $a2 + // loongarch64-NEXT: maskeqz $a0, $a0, $a2 + // loongarch64-NEXT: or $a0, $a0, $a1 + // CHECK-NEXT: ret max!(a, b) } diff --git a/tests/codegen/rust-abi-arch-specific-adjustment.rs b/tests/codegen/rust-abi-arch-specific-adjustment.rs index 87a7cd8ae263..9da10f662b0e 100644 --- a/tests/codegen/rust-abi-arch-specific-adjustment.rs +++ b/tests/codegen/rust-abi-arch-specific-adjustment.rs @@ -1,93 +1,111 @@ //@ compile-flags: -O -C no-prepopulate-passes -//@ revisions: riscv64 +//@ revisions: riscv64 loongarch64 //@[riscv64] only-riscv64 //@[riscv64] compile-flags: --target riscv64gc-unknown-linux-gnu //@[riscv64] needs-llvm-components: riscv +//@[loongarch64] only-loongarch64 +//@[loongarch64] compile-flags: --target loongarch64-unknown-linux-gnu +//@[loongarch64] needs-llvm-components: loongarch + #![crate_type = "lib"] #[no_mangle] -// riscv64: define noundef i8 @arg_attr_u8(i8 noundef zeroext %x) +// riscv64: define noundef i8 @arg_attr_u8(i8 noundef zeroext %x) +// loongarch64: define noundef i8 @arg_attr_u8(i8 noundef zeroext %x) pub fn arg_attr_u8(x: u8) -> u8 { x } #[no_mangle] -// riscv64: define noundef i16 @arg_attr_u16(i16 noundef zeroext %x) +// riscv64: define noundef i16 @arg_attr_u16(i16 noundef zeroext %x) +// loongarch64: define noundef i16 @arg_attr_u16(i16 noundef zeroext %x) pub fn arg_attr_u16(x: u16) -> u16 { x } #[no_mangle] -// riscv64: define noundef i32 @arg_attr_u32(i32 noundef signext %x) +// riscv64: define noundef i32 @arg_attr_u32(i32 noundef signext %x) +// loongarch64: define noundef i32 @arg_attr_u32(i32 noundef signext %x) pub fn arg_attr_u32(x: u32) -> u32 { x } #[no_mangle] -// riscv64: define noundef i64 @arg_attr_u64(i64 noundef %x) +// riscv64: define noundef i64 @arg_attr_u64(i64 noundef %x) +// loongarch64: define noundef i64 @arg_attr_u64(i64 noundef %x) pub fn arg_attr_u64(x: u64) -> u64 { x } #[no_mangle] -// riscv64: define noundef i128 @arg_attr_u128(i128 noundef %x) +// riscv64: define noundef i128 @arg_attr_u128(i128 noundef %x) +// loongarch64: define noundef i128 @arg_attr_u128(i128 noundef %x) pub fn arg_attr_u128(x: u128) -> u128 { x } #[no_mangle] -// riscv64: define noundef i8 @arg_attr_i8(i8 noundef signext %x) +// riscv64: define noundef i8 @arg_attr_i8(i8 noundef signext %x) +// loongarch64: define noundef i8 @arg_attr_i8(i8 noundef signext %x) pub fn arg_attr_i8(x: i8) -> i8 { x } #[no_mangle] -// riscv64: define noundef i16 @arg_attr_i16(i16 noundef signext %x) +// riscv64: define noundef i16 @arg_attr_i16(i16 noundef signext %x) +// loongarch64: define noundef i16 @arg_attr_i16(i16 noundef signext %x) pub fn arg_attr_i16(x: i16) -> i16 { x } #[no_mangle] -// riscv64: define noundef i32 @arg_attr_i32(i32 noundef signext %x) +// riscv64: define noundef i32 @arg_attr_i32(i32 noundef signext %x) +// loongarch64: define noundef i32 @arg_attr_i32(i32 noundef signext %x) pub fn arg_attr_i32(x: i32) -> i32 { x } #[no_mangle] -// riscv64: define noundef i64 @arg_attr_i64(i64 noundef %x) +// riscv64: define noundef i64 @arg_attr_i64(i64 noundef %x) +// loongarch64: define noundef i64 @arg_attr_i64(i64 noundef %x) pub fn arg_attr_i64(x: i64) -> i64 { x } #[no_mangle] -// riscv64: define noundef i128 @arg_attr_i128(i128 noundef %x) +// riscv64: define noundef i128 @arg_attr_i128(i128 noundef %x) +// loongarch64: define noundef i128 @arg_attr_i128(i128 noundef %x) pub fn arg_attr_i128(x: i128) -> i128 { x } #[no_mangle] -// riscv64: define noundef zeroext i1 @arg_attr_bool(i1 noundef zeroext %x) +// riscv64: define noundef zeroext i1 @arg_attr_bool(i1 noundef zeroext %x) +// loongarch64: define noundef zeroext i1 @arg_attr_bool(i1 noundef zeroext %x) pub fn arg_attr_bool(x: bool) -> bool { x } #[no_mangle] // ignore-tidy-linelength -// riscv64: define noundef{{( range\(i32 0, 1114112\))?}} i32 @arg_attr_char(i32 noundef signext{{( range\(i32 0, 1114112\))?}} %x) +// riscv64: define noundef{{( range\(i32 0, 1114112\))?}} i32 @arg_attr_char(i32 noundef signext{{( range\(i32 0, 1114112\))?}} %x) +// loongarch64: define noundef{{( range\(i32 0, 1114112\))?}} i32 @arg_attr_char(i32 noundef signext{{( range\(i32 0, 1114112\))?}} %x) pub fn arg_attr_char(x: char) -> char { x } #[no_mangle] -// riscv64: define noundef float @arg_attr_f32(float noundef %x) +// riscv64: define noundef float @arg_attr_f32(float noundef %x) +// loongarch64: define noundef float @arg_attr_f32(float noundef %x) pub fn arg_attr_f32(x: f32) -> f32 { x } #[no_mangle] -// riscv64: define noundef double @arg_attr_f64(double noundef %x) +// riscv64: define noundef double @arg_attr_f64(double noundef %x) +// loongarch64: define noundef double @arg_attr_f64(double noundef %x) pub fn arg_attr_f64(x: f64) -> f64 { x } diff --git a/tests/codegen/sanitizer/cfi/emit-type-checks-attr-no-sanitize.rs b/tests/codegen/sanitizer/cfi/emit-type-checks-attr-no-sanitize.rs index 259967e89181..71ccdc8ca624 100644 --- a/tests/codegen/sanitizer/cfi/emit-type-checks-attr-no-sanitize.rs +++ b/tests/codegen/sanitizer/cfi/emit-type-checks-attr-no-sanitize.rs @@ -12,7 +12,7 @@ pub fn foo(f: fn(i32) -> i32, arg: i32) -> i32 { // CHECK: Function Attrs: {{.*}} // CHECK-LABEL: define{{.*}}foo{{.*}}!type !{{[0-9]+}} !type !{{[0-9]+}} !type !{{[0-9]+}} !type !{{[0-9]+}} // CHECK: start: - // CHECK-NEXT: {{%.+}} = call i32 %f(i32 %arg) + // CHECK-NEXT: {{%.+}} = call i32 %f(i32{{.*}} %arg) // CHECK-NEXT: ret i32 {{%.+}} f(arg) } diff --git a/tests/codegen/sanitizer/cfi/emit-type-checks.rs b/tests/codegen/sanitizer/cfi/emit-type-checks.rs index 37edbefee56a..ebc66a015df6 100644 --- a/tests/codegen/sanitizer/cfi/emit-type-checks.rs +++ b/tests/codegen/sanitizer/cfi/emit-type-checks.rs @@ -11,7 +11,7 @@ pub fn foo(f: fn(i32) -> i32, arg: i32) -> i32 { // CHECK: [[TT:%.+]] = call i1 @llvm.type.test(ptr {{%f|%0}}, metadata !"{{[[:print:]]+}}") // CHECK-NEXT: br i1 [[TT]], label %type_test.pass, label %type_test.fail // CHECK: type_test.pass: - // CHECK-NEXT: {{%.+}} = call i32 %f(i32 %arg) + // CHECK-NEXT: {{%.+}} = call i32 %f(i32{{.*}} %arg) // CHECK: type_test.fail: // CHECK-NEXT: call void @llvm.trap() // CHECK-NEXT: unreachable From 47d6667454f89516f86ebebd272cfc01282e4d66 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Wed, 23 Oct 2024 08:56:54 +0300 Subject: [PATCH 141/366] do not remove `.cargo` directroy Signed-off-by: onur-ozkan --- src/bootstrap/bootstrap.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 04909cd79214..d7ae0299dd69 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -1092,9 +1092,6 @@ class RustBuild(object): if not os.path.exists(cargo_dir): eprint('ERROR: vendoring required, but .cargo/config does not exist.') raise Exception("{} not found".format(cargo_dir)) - else: - if os.path.exists(cargo_dir): - shutil.rmtree(cargo_dir) def parse_args(args): """Parse the command line arguments that the python script needs.""" From e14d6d8314f792bc8a5cf77a6144cbd57b80a717 Mon Sep 17 00:00:00 2001 From: Graydon Hoare Date: Thu, 10 Oct 2024 00:05:16 -0700 Subject: [PATCH 142/366] Add wasm32v1-none target (compiler-team/#791) --- compiler/rustc_target/src/spec/mod.rs | 1 + .../src/spec/targets/wasm32v1_none.rs | 88 +++++++++++++++++++ tests/assembly/targets/targets-elf.rs | 3 + 3 files changed, 92 insertions(+) create mode 100644 compiler/rustc_target/src/spec/targets/wasm32v1_none.rs diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 5ca2a339f72c..f4cbe47e0f35 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1803,6 +1803,7 @@ supported_targets! { ("wasm32-unknown-emscripten", wasm32_unknown_emscripten), ("wasm32-unknown-unknown", wasm32_unknown_unknown), + ("wasm32v1-none", wasm32v1_none), ("wasm32-wasi", wasm32_wasi), ("wasm32-wasip1", wasm32_wasip1), ("wasm32-wasip2", wasm32_wasip2), diff --git a/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs b/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs new file mode 100644 index 000000000000..be6f7eae287d --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs @@ -0,0 +1,88 @@ +//! A "bare wasm" target representing a WebAssembly output that makes zero +//! assumptions about its environment, similar to wasm32-unknown-unknown, but +//! that also specifies an _upper_ bound on the set of wasm proposals that are +//! supported. +//! +//! It is implemented as a variant on LLVM's wasm32-unknown-unknown target, with +//! the additional flags `-Ctarget-cpu=mvp` and `-Ctarget-feature=+mutable-globals`. +//! +//! This target exists to resolve a tension in Rustc's choice of WebAssembly +//! proposals to support. Since most WebAssembly users are in fact _on the web_ +//! and web browsers are frequently updated with support for the latest +//! features, it is reasonable for Rustc to generate wasm code that exploits new +//! WebAssembly proposals as they gain browser support. At least by default. And +//! this is what the wasm32-unknown-unknown target does, which means that the +//! _exact_ WebAssembly features that Rustc generates will change over time. +//! +//! But a different set of users -- smaller but nonetheless worth supporting -- +//! are using WebAssembly in implementations that either don't get updated very +//! often, or need to prioritize stability, implementation simplicity or +//! security over feature support. This target is for them, and it promises that +//! the wasm code it generates will not go beyond the proposals/features of the +//! W3C WebAssembly core 1.0 spec, which (as far as I can tell) is approximately +//! "the wasm MVP plus mutable globals". Mutable globals was proposed in 2018 +//! and made it in. +//! +//! See https://www.w3.org/TR/wasm-core-1/ +//! +//! Notably this feature-set _excludes_: +//! +//! - sign-extension operators +//! - non-trapping / saturating float-to-int conversions +//! - multi-value +//! - reference types +//! - bulk memory operations +//! - SIMD +//! +//! These are all listed as additions in the core 2.0 spec. Also they were all +//! proposed after 2020, and core 1.0 shipped in 2019. It also excludes even +//! later proposals such as: +//! +//! - exception handling +//! - tail calls +//! - extended consts +//! - function references +//! - multi-memory +//! - component model +//! - gc +//! - threads +//! - relaxed SIMD +//! - custom annotations +//! - branch hinting +//! + +use crate::spec::{Cc, LinkerFlavor, Target, base}; + +pub(crate) fn target() -> Target { + let mut options = base::wasm::options(); + options.os = "none".into(); + + options.cpu = "mvp".into(); + options.features = "+mutable-globals".into(); + + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ + // For now this target just never has an entry symbol no matter the output + // type, so unconditionally pass this. + "--no-entry", + ]); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ + // Make sure clang uses LLD as its linker and is configured appropriately + // otherwise + "--target=wasm32-unknown-unknown", + "-Wl,--no-entry", + ]); + + Target { + llvm_target: "wasm32-unknown-unknown".into(), + metadata: crate::spec::TargetMetadata { + description: Some("WebAssembly".into()), + tier: Some(2), + host_tools: Some(false), + std: Some(false), + }, + pointer_width: 32, + data_layout: "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20".into(), + arch: "wasm32".into(), + options, + } +} diff --git a/tests/assembly/targets/targets-elf.rs b/tests/assembly/targets/targets-elf.rs index f26d06a0ecb8..1857633a8bfa 100644 --- a/tests/assembly/targets/targets-elf.rs +++ b/tests/assembly/targets/targets-elf.rs @@ -522,6 +522,9 @@ //@ revisions: wasm32_unknown_unknown //@ [wasm32_unknown_unknown] compile-flags: --target wasm32-unknown-unknown //@ [wasm32_unknown_unknown] needs-llvm-components: webassembly +//@ revisions: wasm32v1_none +//@ [wasm32v1_none] compile-flags: --target wasm32v1-none +//@ [wasm32v1_none] needs-llvm-components: webassembly //@ revisions: wasm32_wasi //@ [wasm32_wasi] compile-flags: --target wasm32-wasi //@ [wasm32_wasi] needs-llvm-components: webassembly From 212d516ab0e06b6227ce6c0a6d23960f047537bd Mon Sep 17 00:00:00 2001 From: Graydon Hoare Date: Wed, 16 Oct 2024 16:48:53 -0700 Subject: [PATCH 143/366] Address review comments on wasm32v1-none target --- .../src/spec/targets/wasm32v1_none.rs | 63 +++------- .../host-x86_64/dist-various-2/Dockerfile | 1 + src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 1 + .../src/platform-support/wasm32v1-none.md | 109 ++++++++++++++++++ src/tools/build-manifest/src/main.rs | 1 + 6 files changed, 126 insertions(+), 50 deletions(-) create mode 100644 src/doc/rustc/src/platform-support/wasm32v1-none.md diff --git a/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs b/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs index be6f7eae287d..bf35ae009c6e 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs @@ -1,55 +1,16 @@ -//! A "bare wasm" target representing a WebAssembly output that makes zero -//! assumptions about its environment, similar to wasm32-unknown-unknown, but -//! that also specifies an _upper_ bound on the set of wasm proposals that are -//! supported. +//! A "bare wasm" target representing a WebAssembly output that does not import +//! anything from its environment and also specifies an _upper_ bound on the set +//! of WebAssembly proposals that are supported. //! -//! It is implemented as a variant on LLVM's wasm32-unknown-unknown target, with -//! the additional flags `-Ctarget-cpu=mvp` and `-Ctarget-feature=+mutable-globals`. -//! -//! This target exists to resolve a tension in Rustc's choice of WebAssembly -//! proposals to support. Since most WebAssembly users are in fact _on the web_ -//! and web browsers are frequently updated with support for the latest -//! features, it is reasonable for Rustc to generate wasm code that exploits new -//! WebAssembly proposals as they gain browser support. At least by default. And -//! this is what the wasm32-unknown-unknown target does, which means that the -//! _exact_ WebAssembly features that Rustc generates will change over time. -//! -//! But a different set of users -- smaller but nonetheless worth supporting -- -//! are using WebAssembly in implementations that either don't get updated very -//! often, or need to prioritize stability, implementation simplicity or -//! security over feature support. This target is for them, and it promises that -//! the wasm code it generates will not go beyond the proposals/features of the -//! W3C WebAssembly core 1.0 spec, which (as far as I can tell) is approximately -//! "the wasm MVP plus mutable globals". Mutable globals was proposed in 2018 -//! and made it in. -//! -//! See https://www.w3.org/TR/wasm-core-1/ -//! -//! Notably this feature-set _excludes_: -//! -//! - sign-extension operators -//! - non-trapping / saturating float-to-int conversions -//! - multi-value -//! - reference types -//! - bulk memory operations -//! - SIMD -//! -//! These are all listed as additions in the core 2.0 spec. Also they were all -//! proposed after 2020, and core 1.0 shipped in 2019. It also excludes even -//! later proposals such as: -//! -//! - exception handling -//! - tail calls -//! - extended consts -//! - function references -//! - multi-memory -//! - component model -//! - gc -//! - threads -//! - relaxed SIMD -//! - custom annotations -//! - branch hinting +//! It's equivalent to the `wasm32-unknown-unknown` target with the additional +//! flags `-Ctarget-cpu=mvp` and `-Ctarget-feature=+mutable-globals`. This +//! enables just the features specified in //! +//! This is a _separate target_ because using `wasm32-unknown-unknown` with +//! those target flags doesn't automatically rebuild libcore / liballoc with +//! them, and in order to get those libraries rebuilt you need to use the +//! nightly Rust feature `-Zbuild-std`. This target is for people who want to +//! use stable Rust, and target a stable set pf WebAssembly features. use crate::spec::{Cc, LinkerFlavor, Target, base}; @@ -57,6 +18,8 @@ pub(crate) fn target() -> Target { let mut options = base::wasm::options(); options.os = "none".into(); + // WebAssembly 1.0 shipped in 2019 and included exactly one proposal + // after the initial "MVP" feature set: "mutable-globals". options.cpu = "mvp".into(); options.features = "+mutable-globals".into(); diff --git a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile index 410f0f92e60b..8aabfaafbabb 100644 --- a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile @@ -118,6 +118,7 @@ ENV TARGETS=$TARGETS,wasm32-wasi ENV TARGETS=$TARGETS,wasm32-wasip1 ENV TARGETS=$TARGETS,wasm32-wasip1-threads ENV TARGETS=$TARGETS,wasm32-wasip2 +ENV TARGETS=$TARGETS,wasm32v1-none ENV TARGETS=$TARGETS,sparcv9-sun-solaris ENV TARGETS=$TARGETS,x86_64-pc-solaris ENV TARGETS=$TARGETS,x86_64-unknown-linux-gnux32 diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 795908b32c0b..e05d9a40f00e 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -86,6 +86,7 @@ - [wasm32-wasip2](platform-support/wasm32-wasip2.md) - [wasm32-unknown-emscripten](platform-support/wasm32-unknown-emscripten.md) - [wasm32-unknown-unknown](platform-support/wasm32-unknown-unknown.md) + - [wasm32v1-none](platform-support/wasm32v1-none.md) - [wasm64-unknown-unknown](platform-support/wasm64-unknown-unknown.md) - [\*-win7-windows-msvc](platform-support/win7-windows-msvc.md) - [x86_64-fortanix-unknown-sgx](platform-support/x86_64-fortanix-unknown-sgx.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index e9c73ef1c2d8..5da03d26eb41 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -195,6 +195,7 @@ target | std | notes `wasm32-wasi` | ✓ | WebAssembly with WASI (undergoing a [rename to `wasm32-wasip1`][wasi-rename]) [`wasm32-wasip1`](platform-support/wasm32-wasip1.md) | ✓ | WebAssembly with WASI [`wasm32-wasip1-threads`](platform-support/wasm32-wasip1-threads.md) | ✓ | WebAssembly with WASI Preview 1 and threads +[`wasm32v1-none`](platform-support/wasm32v1-none.md) | * | WebAssembly limited to 1.0 features and no imports [`x86_64-apple-ios`](platform-support/apple-ios.md) | ✓ | 64-bit x86 iOS [`x86_64-apple-ios-macabi`](platform-support/apple-ios-macabi.md) | ✓ | Mac Catalyst on x86_64 [`x86_64-fortanix-unknown-sgx`](platform-support/x86_64-fortanix-unknown-sgx.md) | ✓ | [Fortanix ABI] for 64-bit Intel SGX diff --git a/src/doc/rustc/src/platform-support/wasm32v1-none.md b/src/doc/rustc/src/platform-support/wasm32v1-none.md new file mode 100644 index 000000000000..666f5e780d14 --- /dev/null +++ b/src/doc/rustc/src/platform-support/wasm32v1-none.md @@ -0,0 +1,109 @@ +# `wasm32v1-none` + +**Tier: 2** + +The `wasm32v1-none` target is a WebAssembly compilation target that: + +- Imports nothing from its host environment +- Enables no proposals / features past the [W3C WebAssembly Core 1.0 spec] + +[W3C WebAssembly Core 1.0 spec]: https://www.w3.org/TR/wasm-core-1/ + +The target is very similar to [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md) and similarly uses LLVM's `wasm32-unknown-unknown` backend target. It contains only three minor differences: + +* Setting the `target-cpu` to `mvp` rather than the default `generic`. Requesting `mvp` disables _all_ WebAssembly proposals / LLVM target feature flags. +* Enabling the [Import/Export of Mutable Globals] proposal (i.e. the `+mutable-globals` LLVM target feature flag) +* Not compiling the `std` library at all, rather than compiling it with stubs. + +[Import/Export of Mutable Globals]: https://github.com/WebAssembly/mutable-global + +## Target maintainers + +- Alex Crichton, https://github.com/alexcrichton +- Graydon Hoare, https://github.com/graydon + +## Requirements + +This target is cross-compiled. It does not support `std`, only `core` and `alloc`. Since it imports nothing from its environment, any `std` parts that use OS facilities would be stubbed out with functions-that-fail anyways, and the experience of working with the stub `std` in the `wasm32-unknown-unknown` target was deemed not something worth repeating here. + +Everything else about this target's requirements, building, usage and testing is the same as what's described in the [`wasm32-unknown-unknown` document](./wasm32-unknown-unknown.md), just using the target string `wasm32v1-none` in place of `wasm32-unknown-unknown`. + +## Conditionally compiling code + +It's recommended to conditionally compile code for this target with: + +```text +#[cfg(all(target_family = "wasm", target_os = "none"))] +``` + +Note that there is no way to tell via `#[cfg]` whether code will be running on +the web or not. + +## Enabled WebAssembly features + +As noted above, _no WebAssembly proposals past 1.0_ are enabled on this target by default. Indeed, the entire point of this target is to have a way to compile for a stable "no post-1.0 proposals" subset of WebAssembly _on stable Rust_. + +The [W3C WebAssembly Core 1.0 spec] was adopted as a W3C recommendation in December 2019, and includes exactly one "post-MVP" proposal: the [Import/Export of Mutable Globals] proposal. + +All subsequent proposals are _disabled_ on this target by default, though they can be individually enabled by passing LLVM target-feature flags. + +For reference sake, the set of proposals that LLVM supports at the time of writing, that this target _does not enable by default_, are listed here along with their LLVM target-feature flags: + +* Post-1.0 proposals (integrated into the WebAssembly core 2.0 spec): + * [Bulk memory] - `+bulk-memory` + * [Sign-extending operations] - `+sign-ext` + * [Non-trapping fp-to-int operations] - `+nontrapping-fptoint` + * [Multi-value] - `+multivalue` + * [Reference Types] - `+reference-types` + * [Fixed-width SIMD] - `+simd128` +* Post-2.0 proposals: + * [Threads] (supported by atomics) - `+atomics` + * [Exception handling] - `+exception-handling` + * [Extended Constant Expressions] - `+extended-const` + * [Half Precision] - `+half-precision` + * [Multiple memories]- `+multimemory` + * [Relaxed SIMD] - `+relaxed-simd` + * [Tail call] - `+tail-call` + +[Bulk memory]: https://github.com/WebAssembly/spec/blob/main/proposals/bulk-memory-operations/Overview.md +[Sign-extending operations]: https://github.com/WebAssembly/spec/blob/main/proposals/sign-extension-ops/Overview.md +[Non-trapping fp-to-int operations]: https://github.com/WebAssembly/spec/blob/main/proposals/nontrapping-float-to-int-conversion/Overview.md +[Multi-value]: https://github.com/WebAssembly/spec/blob/main/proposals/multi-value/Overview.md +[Reference Types]: https://github.com/WebAssembly/spec/blob/main/proposals/reference-types/Overview.md +[Fixed-width SIMD]: https://github.com/WebAssembly/spec/blob/main/proposals/simd/SIMD.md +[Threads]: https://github.com/webassembly/threads +[Exception handling]: https://github.com/WebAssembly/exception-handling +[Extended Constant Expressions]: https://github.com/WebAssembly/extended-const +[Half Precision]: https://github.com/WebAssembly/half-precision +[Multiple memories]: https://github.com/WebAssembly/multi-memory +[Relaxed SIMD]: https://github.com/WebAssembly/relaxed-simd +[Tail call]: https://github.com/WebAssembly/tail-call + +Additional proposals in the future are, of course, also not enabled by default. + +## Rationale relative to wasm32-unknown-unknown + +As noted in the [`wasm32-unknown-unknown` document](./wasm32-unknown-unknown.md), it is possible to compile with `-target wasm32-unknown-unknown` and disable all WebAssembly proposals "by hand", by passing `-Ctarget-cpu=mvp`. Furthermore one can enable proposals one by one by passing LLVM target feature flags, such as `-Ctarget-feature=+mutable-globals`. + +Is it therefore reasonable to wonder what the difference is between building with this: + +```sh +$ rustc -target wasm32-unknown-unknown -Ctarget-cpu=mvp -Ctarget-feature=+mutable-globals +``` + +and building with this: + +```sh +$ rustc -target wasm32v1-none +``` + +The difference is in how the `core` and `alloc` crates are compiled for distribution with the toolchain, and whether it works on _stable_ Rust toolchains or requires _nightly_ ones. Again referring back to the [`wasm32-unknown-unknown` document](./wasm32-unknown-unknown.md), note that to disable all post-MVP proposals on that target one _actually_ has to compile with this: + +```sh +$ export RUSTFLAGS="-Ctarget-cpu=mvp -Ctarget-feature=+mutable-globals" +$ cargo +nightly build -Zbuild-std=panic_abort,std -target wasm32-unknown-unknown +``` + +Which not only rebuilds `std`, `core` and `alloc` (which is somewhat costly and annoying) but more importantly requires the use of nightly Rust toolchains (for the `-Zbuild-std` flag). This is very undesirable for the target audience, which consists of people targeting WebAssembly implementations that prioritize stability, simplicity and/or security over feature support. + +This `wasm32v1-none` target exists as an alternative option that works on stable Rust toolchains, without rebuilding the stdlib. diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index 62e1695cbe36..925cbfe09a45 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -161,6 +161,7 @@ static TARGETS: &[&str] = &[ "wasm32-wasip1", "wasm32-wasip1-threads", "wasm32-wasip2", + "wasm32v1-none", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-apple-ios-macabi", From 3ba87498fa3349d63f622593ea7d722105059978 Mon Sep 17 00:00:00 2001 From: Graydon Hoare Date: Wed, 16 Oct 2024 18:56:43 -0700 Subject: [PATCH 144/366] Fix rustc_target test: wasmNN-none should support dynamic linking --- compiler/rustc_target/src/spec/tests/tests_impl.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/tests/tests_impl.rs b/compiler/rustc_target/src/spec/tests/tests_impl.rs index 7ed21954fba0..cc5931be860b 100644 --- a/compiler/rustc_target/src/spec/tests/tests_impl.rs +++ b/compiler/rustc_target/src/spec/tests/tests_impl.rs @@ -121,7 +121,13 @@ impl Target { // Check dynamic linking stuff // BPF: when targeting user space vms (like rbpf), those can load dynamic libraries. // hexagon: when targeting QuRT, that OS can load dynamic libraries. - if self.os == "none" && (self.arch != "bpf" && self.arch != "hexagon") { + // wasm{32,64}: dynamic linking is inherent in the definition of the VM. + if self.os == "none" + && (self.arch != "bpf" + && self.arch != "hexagon" + && self.arch != "wasm32" + && self.arch != "wasm64") + { assert!(!self.dynamic_linking); } if self.only_cdylib From b0f02823fab05e9274131bbcaf9fe87366271888 Mon Sep 17 00:00:00 2001 From: Graydon Hoare Date: Tue, 22 Oct 2024 23:04:20 -0700 Subject: [PATCH 145/366] More review comments on wasm32v1-none target --- .../wasm32-unknown-unknown.md | 24 +++++++++++++------ .../src/platform-support/wasm32v1-none.md | 8 +++---- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md b/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md index 48a8df0c4a86..73264aba8580 100644 --- a/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md +++ b/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md @@ -132,10 +132,20 @@ As of the time of this writing the proposals that are enabled by default (the If you're compiling WebAssembly code for an engine that does not support a feature in LLVM's default feature set then the feature must be disabled at -compile time. Note, though, that enabled features may be used in the standard -library or precompiled libraries shipped via rustup. This means that not only -does your own code need to be compiled with the correct set of flags but the -Rust standard library additionally must be recompiled. +compile time. There are two approaches to choose from: + + - If you are targeting a feature set no smaller than the W3C WebAssembly Core + 1.0 recommendation -- which is equivalent to the WebAssembly MVP plus the + `mutable-globals` feature -- and you are building `no_std`, then you can + simply use the [`wasm32v1-none` target](./wasm32v1-none.md) instead of + `wasm32-unknown-unknown`, which uses only those minimal features and + includes a core and alloc library built with only those minimal features. + + - Otherwise -- if you need std, or if you need to target the ultra-minimal + "MVP" feature set, excluding `mutable-globals` -- you will need to manually + specify `-Ctarget-cpu=mvp` and also rebuild the stdlib using that target to + ensure no features are used in the stdlib. This in turn requires use of a + nightly compiler. Compiling all code for the initial release of WebAssembly looks like: @@ -150,9 +160,9 @@ then used to recompile the standard library in addition to your own code. This will produce a binary that uses only the original WebAssembly features by default and no proposals since its inception. -To enable individual features it can be done with `-Ctarget-feature=+foo`. -Available features for Rust code itself are documented in the [reference] and -can also be found through: +To enable individual features on either this target or `wasm32v1-none`, pass +arguments of the form `-Ctarget-feature=+foo`. Available features for Rust code +itself are documented in the [reference] and can also be found through: ```sh $ rustc -Ctarget-feature=help --target wasm32-unknown-unknown diff --git a/src/doc/rustc/src/platform-support/wasm32v1-none.md b/src/doc/rustc/src/platform-support/wasm32v1-none.md index 666f5e780d14..46f89c201130 100644 --- a/src/doc/rustc/src/platform-support/wasm32v1-none.md +++ b/src/doc/rustc/src/platform-support/wasm32v1-none.md @@ -83,25 +83,25 @@ Additional proposals in the future are, of course, also not enabled by default. ## Rationale relative to wasm32-unknown-unknown -As noted in the [`wasm32-unknown-unknown` document](./wasm32-unknown-unknown.md), it is possible to compile with `-target wasm32-unknown-unknown` and disable all WebAssembly proposals "by hand", by passing `-Ctarget-cpu=mvp`. Furthermore one can enable proposals one by one by passing LLVM target feature flags, such as `-Ctarget-feature=+mutable-globals`. +As noted in the [`wasm32-unknown-unknown` document](./wasm32-unknown-unknown.md), it is possible to compile with `--target wasm32-unknown-unknown` and disable all WebAssembly proposals "by hand", by passing `-Ctarget-cpu=mvp`. Furthermore one can enable proposals one by one by passing LLVM target feature flags, such as `-Ctarget-feature=+mutable-globals`. Is it therefore reasonable to wonder what the difference is between building with this: ```sh -$ rustc -target wasm32-unknown-unknown -Ctarget-cpu=mvp -Ctarget-feature=+mutable-globals +$ rustc --target wasm32-unknown-unknown -Ctarget-cpu=mvp -Ctarget-feature=+mutable-globals ``` and building with this: ```sh -$ rustc -target wasm32v1-none +$ rustc --target wasm32v1-none ``` The difference is in how the `core` and `alloc` crates are compiled for distribution with the toolchain, and whether it works on _stable_ Rust toolchains or requires _nightly_ ones. Again referring back to the [`wasm32-unknown-unknown` document](./wasm32-unknown-unknown.md), note that to disable all post-MVP proposals on that target one _actually_ has to compile with this: ```sh $ export RUSTFLAGS="-Ctarget-cpu=mvp -Ctarget-feature=+mutable-globals" -$ cargo +nightly build -Zbuild-std=panic_abort,std -target wasm32-unknown-unknown +$ cargo +nightly build -Zbuild-std=panic_abort,std --target wasm32-unknown-unknown ``` Which not only rebuilds `std`, `core` and `alloc` (which is somewhat costly and annoying) but more importantly requires the use of nightly Rust toolchains (for the `-Zbuild-std` flag). This is very undesirable for the target audience, which consists of people targeting WebAssembly implementations that prioritize stability, simplicity and/or security over feature support. From cb816ad4f0c2ec8ac8cb74fdcc8b078d7357e012 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 09:30:36 +0200 Subject: [PATCH 146/366] Add text edit to adjustment hints --- .../crates/ide/src/inlay_hints/adjustment.rs | 52 +++++++++++++++---- .../ide/src/inlay_hints/binding_mode.rs | 11 +--- 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs index ab44d8c3b500..8f239f6029b7 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs @@ -3,6 +3,8 @@ //! let _: u32 = /* */ loop {}; //! let _: &u32 = /* &* */ &mut 0; //! ``` +use std::ops::Not; + use either::Either; use hir::{ Adjust, Adjustment, AutoBorrow, HirDisplay, Mutability, OverloadedDeref, PointerCast, Safety, @@ -15,6 +17,7 @@ use syntax::{ ast::{self, make, AstNode}, ted, }; +use text_edit::TextEditBuilder; use crate::{ AdjustmentHints, AdjustmentHintsMode, InlayHint, InlayHintLabel, InlayHintLabelPart, @@ -51,13 +54,13 @@ pub(super) fn hints( let adjustments = sema.expr_adjustments(desc_expr).filter(|it| !it.is_empty())?; if let ast::Expr::BlockExpr(_) | ast::Expr::IfExpr(_) | ast::Expr::MatchExpr(_) = desc_expr { - if let [Adjustment { kind: Adjust::Deref(_), source, .. }, Adjustment { kind: Adjust::Borrow(_), source: _, target }] = - &*adjustments - { - // Don't show unnecessary reborrows for these, they will just repeat the inner ones again - if source == target { - return None; - } + // Don't show unnecessary reborrows for these, they will just repeat the inner ones again + if matches!( + &*adjustments, + [Adjustment { kind: Adjust::Deref(_), source, .. }, Adjustment { kind: Adjust::Borrow(_), target, .. }] + if source == target + ) { + return None; } } @@ -170,12 +173,39 @@ pub(super) fn hints( if needs_outer_parens || (!postfix && needs_inner_parens) { post.label.append_str(")"); } - if !pre.label.parts.is_empty() { - acc.push(pre); + + let mut pre = pre.label.parts.is_empty().not().then_some(pre); + let mut post = post.label.parts.is_empty().not().then_some(post); + if pre.is_none() && post.is_none() { + return None; } - if !post.label.parts.is_empty() { - acc.push(post); + let edit = { + let mut b = TextEditBuilder::default(); + if let Some(pre) = &pre { + b.insert( + pre.range.start(), + pre.label.parts.iter().map(|part| &*part.text).collect::(), + ); + } + if let Some(post) = &post { + b.insert( + post.range.end(), + post.label.parts.iter().map(|part| &*part.text).collect::(), + ); + } + b.finish() + }; + match (&mut pre, &mut post) { + (Some(pre), Some(post)) => { + pre.text_edit = Some(edit.clone()); + post.text_edit = Some(edit); + } + (Some(pre), None) => pre.text_edit = Some(edit), + (None, Some(post)) => post.text_edit = Some(edit), + (None, None) => (), } + acc.extend(pre); + acc.extend(post); Some(()) } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs index beba2ad748cf..db36a06cbe86 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs @@ -23,16 +23,7 @@ pub(super) fn hints( return None; } - let outer_paren_pat = pat - .syntax() - .ancestors() - .skip(1) - .map_while(ast::Pat::cast) - .map_while(|pat| match pat { - ast::Pat::ParenPat(pat) => Some(pat), - _ => None, - }) - .last(); + let outer_paren_pat = pat.syntax().ancestors().skip(1).map_while(ast::ParenPat::cast).last(); let range = outer_paren_pat.as_ref().map_or_else( || match pat { // for ident patterns that @ bind a name, render the un-ref patterns in front of the inner pattern From c92f76d7d7fe819b3f6ba26c6224acd74194b2ea Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 09:52:03 +0200 Subject: [PATCH 147/366] Add text edit to binding mode hints --- .../crates/ide/src/inlay_hints.rs | 13 ---- .../ide/src/inlay_hints/binding_mode.rs | 61 ++++++++++++------- 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index fcf262877dd1..b6e46c32028e 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -410,19 +410,6 @@ impl InlayHint { } } - fn opening_paren_before(kind: InlayKind, range: TextRange) -> InlayHint { - InlayHint { - range, - kind, - label: InlayHintLabel::from("("), - text_edit: None, - position: InlayHintPosition::Before, - pad_left: false, - pad_right: false, - resolve_parent: None, - } - } - pub fn needs_resolve(&self) -> Option { self.resolve_parent.filter(|_| self.text_edit.is_some() || self.label.needs_resolve()) } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs index db36a06cbe86..e38450b73f9d 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/binding_mode.rs @@ -9,6 +9,7 @@ use ide_db::famous_defs::FamousDefs; use span::EditionedFileId; use syntax::ast::{self, AstNode}; +use text_edit::TextEditBuilder; use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind}; @@ -61,33 +62,30 @@ pub(super) fn hints( hint.label.append_str(r); }); hint.pad_right = was_mut_last; - if !hint.label.parts.is_empty() { - acc.push(hint); - } + let acc_base = acc.len(); match pat { ast::Pat::IdentPat(pat) if pat.ref_token().is_none() && pat.mut_token().is_none() => { let bm = sema.binding_mode_of_pat(pat)?; let bm = match bm { - hir::BindingMode::Move => return None, - hir::BindingMode::Ref(Mutability::Mut) => "ref mut", - hir::BindingMode::Ref(Mutability::Shared) => "ref", + hir::BindingMode::Move => None, + hir::BindingMode::Ref(Mutability::Mut) => Some("ref mut"), + hir::BindingMode::Ref(Mutability::Shared) => Some("ref"), }; - acc.push(InlayHint { - range: pat.syntax().text_range(), - kind: InlayKind::BindingMode, - label: bm.into(), - text_edit: None, - position: InlayHintPosition::Before, - pad_left: false, - pad_right: true, - resolve_parent: Some(pat.syntax().text_range()), - }); + if let Some(bm) = bm { + acc.push(InlayHint { + range: pat.syntax().text_range(), + kind: InlayKind::BindingMode, + label: bm.into(), + text_edit: None, + position: InlayHintPosition::Before, + pad_left: false, + pad_right: true, + resolve_parent: Some(pat.syntax().text_range()), + }); + } } ast::Pat::OrPat(pat) if !pattern_adjustments.is_empty() && outer_paren_pat.is_none() => { - acc.push(InlayHint::opening_paren_before( - InlayKind::BindingMode, - pat.syntax().text_range(), - )); + hint.label.append_str("("); acc.push(InlayHint::closing_paren_after( InlayKind::BindingMode, pat.syntax().text_range(), @@ -95,6 +93,24 @@ pub(super) fn hints( } _ => (), } + if !hint.label.parts.is_empty() { + acc.push(hint); + } + + if let hints @ [_, ..] = &mut acc[acc_base..] { + let mut edit = TextEditBuilder::default(); + for h in &mut *hints { + edit.insert( + match h.position { + InlayHintPosition::Before => h.range.start(), + InlayHintPosition::After => h.range.end(), + }, + h.label.parts.iter().map(|p| &*p.text).collect(), + ); + } + let edit = edit.finish(); + hints.iter_mut().for_each(|h| h.text_edit = Some(edit.clone())); + } Some(()) } @@ -145,11 +161,10 @@ fn __( } match &(0,) { (x,) | (x,) => (), - //^^^^^^^^^^^& + //^^^^^^^^^^^) + //^^^^^^^^^^^&( //^ ref //^ ref - //^^^^^^^^^^^( - //^^^^^^^^^^^) ((x,) | (x,)) => (), //^^^^^^^^^^^^^& //^ ref From 49322a176f984849b5953c5a42fb9d0c246a5b16 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 09:57:00 +0200 Subject: [PATCH 148/366] Add text edit to discriminant hints --- .../crates/ide/src/inlay_hints/discriminant.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/discriminant.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/discriminant.rs index 35b62878329f..40d7367dba38 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/discriminant.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/discriminant.rs @@ -8,6 +8,7 @@ use hir::Semantics; use ide_db::{famous_defs::FamousDefs, RootDatabase}; use span::EditionedFileId; use syntax::ast::{self, AstNode, HasName}; +use text_edit::TextEdit; use crate::{ DiscriminantHints, InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind, @@ -65,11 +66,11 @@ fn variant_hints( let eq_ = if eq_token.is_none() { " =" } else { "" }; let label = InlayHintLabel::simple( match d { - Ok(x) => { - if x >= 10 { - format!("{eq_} {x} ({x:#X})") + Ok(val) => { + if val >= 10 { + format!("{eq_} {val} ({val:#X})") } else { - format!("{eq_} {x}") + format!("{eq_} {val}") } } Err(_) => format!("{eq_} ?"), @@ -87,7 +88,7 @@ fn variant_hints( }, kind: InlayKind::Discriminant, label, - text_edit: None, + text_edit: d.ok().map(|val| TextEdit::insert(range.start(), format!("{eq_} {val}"))), position: InlayHintPosition::After, pad_left: false, pad_right: false, From 41fc1fbaabee63a7db556b2f998e79fd862cbd57 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 09:58:20 +0200 Subject: [PATCH 149/366] Add text edit to implicit 'static hints --- .../crates/ide/src/inlay_hints/implicit_static.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs index 8d422478cbfc..f15d19047c9c 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs @@ -9,6 +9,7 @@ use syntax::{ ast::{self, AstNode}, SyntaxKind, }; +use text_edit::TextEdit; use crate::{InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind, LifetimeElisionHints}; @@ -38,7 +39,7 @@ pub(super) fn hints( range: t.text_range(), kind: InlayKind::Lifetime, label: "'static".into(), - text_edit: None, + text_edit: Some(TextEdit::insert(t.text_range().start(), "'static ".into())), position: InlayHintPosition::After, pad_left: false, pad_right: true, From 77a7164ec99c5ba195f107b221d37a55667f3a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20du=20Garreau?= Date: Tue, 22 Oct 2024 17:09:10 +0200 Subject: [PATCH 150/366] Specialize `read_exact` and `read_buf_exact` for `VecDeque` --- library/std/src/io/impls.rs | 46 +++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/library/std/src/io/impls.rs b/library/std/src/io/impls.rs index 85023540a816..b952c85addf6 100644 --- a/library/std/src/io/impls.rs +++ b/library/std/src/io/impls.rs @@ -453,6 +453,29 @@ impl Read for VecDeque { Ok(n) } + fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { + let (front, back) = self.as_slices(); + + // Use only the front buffer if it is big enough to fill `buf`, else use + // the back buffer too. + match buf.split_at_mut_checked(front.len()) { + None => buf.copy_from_slice(&front[..buf.len()]), + Some((buf_front, buf_back)) => match back.split_at_checked(buf_back.len()) { + Some((back, _)) => { + buf_front.copy_from_slice(front); + buf_back.copy_from_slice(back); + } + None => { + self.clear(); + return Err(io::Error::READ_EXACT_EOF); + } + }, + } + + self.drain(..buf.len()); + Ok(()) + } + #[inline] fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> { let (ref mut front, _) = self.as_slices(); @@ -462,6 +485,29 @@ impl Read for VecDeque { Ok(()) } + fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> { + let len = cursor.capacity(); + let (front, back) = self.as_slices(); + + match front.split_at_checked(cursor.capacity()) { + Some((front, _)) => cursor.append(front), + None => { + cursor.append(front); + match back.split_at_checked(cursor.capacity()) { + Some((back, _)) => cursor.append(back), + None => { + cursor.append(back); + self.clear(); + return Err(io::Error::READ_EXACT_EOF); + } + } + } + } + + self.drain(..len); + Ok(()) + } + #[inline] fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { // The total len is known upfront so we can reserve it in a single call. From ad3991d30382676f987a38243b3097d880b9033a Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 9 Oct 2024 09:01:57 +0200 Subject: [PATCH 151/366] nightly feature tracking: get rid of the per-feature bool fields --- compiler/rustc_ast_lowering/src/asm.rs | 6 +- compiler/rustc_ast_lowering/src/expr.rs | 8 +- compiler/rustc_ast_lowering/src/item.rs | 4 +- compiler/rustc_ast_lowering/src/lib.rs | 12 +- compiler/rustc_ast_lowering/src/path.rs | 4 +- .../rustc_ast_passes/src/ast_validation.rs | 22 +-- compiler/rustc_ast_passes/src/feature_gate.rs | 18 +-- compiler/rustc_attr/src/builtin.rs | 10 +- compiler/rustc_borrowck/src/type_check/mod.rs | 2 +- compiler/rustc_builtin_macros/src/assert.rs | 2 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 10 +- .../rustc_codegen_ssa/src/target_features.rs | 42 +++--- .../src/check_consts/check.rs | 4 +- .../rustc_const_eval/src/check_consts/mod.rs | 2 +- .../src/check_consts/post_drop_elaboration.rs | 2 +- compiler/rustc_expand/src/config.rs | 8 +- compiler/rustc_expand/src/expand.rs | 4 +- compiler/rustc_expand/src/mbe/quoted.rs | 4 +- compiler/rustc_feature/src/builtin_attrs.rs | 4 +- compiler/rustc_feature/src/unstable.rs | 138 +++++++----------- compiler/rustc_hir_analysis/src/bounds.rs | 2 +- .../rustc_hir_analysis/src/check/check.rs | 4 +- .../rustc_hir_analysis/src/check/region.rs | 8 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 10 +- .../src/coherence/inherent_impls.rs | 4 +- .../rustc_hir_analysis/src/coherence/mod.rs | 6 +- compiler/rustc_hir_analysis/src/collect.rs | 4 +- .../src/collect/generics_of.rs | 2 +- .../src/collect/predicates_of.rs | 4 +- .../src/collect/resolve_bound_vars.rs | 4 +- .../rustc_hir_analysis/src/collect/type_of.rs | 4 +- .../src/hir_ty_lowering/bounds.rs | 2 +- .../src/hir_ty_lowering/errors.rs | 4 +- .../src/hir_ty_lowering/mod.rs | 2 +- .../rustc_hir_analysis/src/impl_wf_check.rs | 2 +- compiler/rustc_hir_analysis/src/lib.rs | 6 +- .../rustc_hir_analysis/src/outlives/mod.rs | 2 +- compiler/rustc_hir_typeck/src/cast.rs | 2 +- compiler/rustc_hir_typeck/src/coercion.rs | 14 +- compiler/rustc_hir_typeck/src/expr.rs | 10 +- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 2 +- .../rustc_hir_typeck/src/gather_locals.rs | 4 +- compiler/rustc_hir_typeck/src/lib.rs | 2 +- .../rustc_hir_typeck/src/method/confirm.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 10 +- compiler/rustc_hir_typeck/src/pat.rs | 16 +- compiler/rustc_hir_typeck/src/upvar.rs | 2 +- compiler/rustc_hir_typeck/src/writeback.rs | 2 +- .../rustc_incremental/src/assert_dep_graph.rs | 2 +- .../src/persist/dirty_clean.rs | 2 +- compiler/rustc_lint/src/async_fn_in_trait.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 6 +- compiler/rustc_lint/src/if_let_rescope.rs | 2 +- .../rustc_lint/src/impl_trait_overcaptures.rs | 4 +- .../rustc_lint/src/tail_expr_drop_order.rs | 2 +- .../rustc_metadata/src/dependency_format.rs | 2 +- compiler/rustc_metadata/src/native_libs.rs | 6 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 6 +- .../rustc_middle/src/mir/interpret/queries.rs | 2 +- .../src/traits/specialization_graph.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 6 +- compiler/rustc_middle/src/ty/layout.rs | 2 +- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- compiler/rustc_middle/src/ty/sty.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 8 +- .../src/build/expr/as_operand.rs | 2 +- .../rustc_mir_build/src/build/matches/test.rs | 2 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 2 +- .../src/thir/pattern/check_match.rs | 2 +- compiler/rustc_mir_transform/src/coroutine.rs | 2 +- compiler/rustc_mir_transform/src/gvn.rs | 2 +- compiler/rustc_passes/src/abi_test.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 4 +- compiler/rustc_passes/src/check_const.rs | 2 +- compiler/rustc_passes/src/layout_test.rs | 2 +- compiler/rustc_passes/src/lib_features.rs | 2 +- compiler/rustc_passes/src/stability.rs | 10 +- compiler/rustc_pattern_analysis/src/rustc.rs | 6 +- .../src/ich/impls_syntax.rs | 2 +- compiler/rustc_resolve/src/ident.rs | 4 +- compiler/rustc_resolve/src/late.rs | 10 +- .../rustc_resolve/src/late/diagnostics.rs | 6 +- compiler/rustc_resolve/src/macros.rs | 4 +- compiler/rustc_symbol_mangling/src/test.rs | 2 +- .../traits/fulfillment_errors.rs | 2 +- .../src/error_reporting/traits/suggestions.rs | 6 +- .../src/traits/const_evaluatable.rs | 2 +- .../src/traits/dyn_compatibility.rs | 4 +- .../src/traits/fulfill.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 2 +- .../src/traits/normalize.rs | 2 +- .../src/traits/project.rs | 2 +- .../src/traits/select/candidate_assembly.rs | 4 +- .../src/traits/select/confirmation.rs | 4 +- .../src/traits/select/mod.rs | 4 +- .../src/traits/specialize/mod.rs | 2 +- .../src/traits/structural_normalize.rs | 2 +- .../rustc_trait_selection/src/traits/wf.rs | 2 +- compiler/rustc_ty_utils/src/assoc.rs | 2 +- compiler/rustc_ty_utils/src/consts.rs | 2 +- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/clean/types.rs | 4 +- .../passes/check_doc_test_visibility.rs | 2 +- .../passes/collect_intra_doc_links.rs | 2 +- .../clippy/clippy_lints/src/empty_enum.rs | 2 +- .../src/matches/match_same_arms.rs | 2 +- .../src/matches/redundant_guards.rs | 2 +- 108 files changed, 299 insertions(+), 331 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 88cdb2ec3639..6585a7de2459 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -49,7 +49,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { | asm::InlineAsmArch::RiscV64 | asm::InlineAsmArch::LoongArch64 ); - if !is_stable && !self.tcx.features().asm_experimental_arch { + if !is_stable && !self.tcx.features().asm_experimental_arch() { feature_err( &self.tcx.sess, sym::asm_experimental_arch, @@ -65,7 +65,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { { self.dcx().emit_err(AttSyntaxOnlyX86 { span: sp }); } - if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind { + if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind() { feature_err( &self.tcx.sess, sym::asm_unwind, @@ -237,7 +237,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } InlineAsmOperand::Label { block } => { - if !self.tcx.features().asm_goto { + if !self.tcx.features().asm_goto() { feature_err( sess, sym::asm_goto, diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index ae1e1b3f8a21..a1a16d0ca263 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -575,7 +575,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } else { // Either `body.is_none()` or `is_never_pattern` here. if !is_never_pattern { - if self.tcx.features().never_patterns { + if self.tcx.features().never_patterns() { // If the feature is off we already emitted the error after parsing. let suggestion = span.shrink_to_hi(); self.dcx().emit_err(MatchArmWithNoBody { span, suggestion }); @@ -717,7 +717,7 @@ impl<'hir> LoweringContext<'_, 'hir> { outer_hir_id: HirId, inner_hir_id: HirId, ) { - if self.tcx.features().async_fn_track_caller + if self.tcx.features().async_fn_track_caller() && let Some(attrs) = self.attrs.get(&outer_hir_id.local_id) && attrs.into_iter().any(|attr| attr.has_name(sym::track_caller)) { @@ -1572,7 +1572,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ); } Some(hir::CoroutineKind::Coroutine(_)) => { - if !self.tcx.features().coroutines { + if !self.tcx.features().coroutines() { rustc_session::parse::feature_err( &self.tcx.sess, sym::coroutines, @@ -1584,7 +1584,7 @@ impl<'hir> LoweringContext<'_, 'hir> { false } None => { - if !self.tcx.features().coroutines { + if !self.tcx.features().coroutines() { rustc_session::parse::feature_err( &self.tcx.sess, sym::coroutines, diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 7416a1e39eb5..c43106c6e5f6 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1512,7 +1512,7 @@ impl<'hir> LoweringContext<'_, 'hir> { continue; } let is_param = *is_param.get_or_insert_with(compute_is_param); - if !is_param && !self.tcx.features().more_maybe_bounds { + if !is_param && !self.tcx.features().more_maybe_bounds() { self.tcx .sess .create_feature_err( @@ -1530,7 +1530,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let host_param_parts = if let Const::Yes(span) = constness // if this comes from implementing a `const` trait, we must force constness to be appended // to the impl item, no matter whether effects is enabled. - && (self.tcx.features().effects || force_append_constness) + && (self.tcx.features().effects() || force_append_constness) { let span = self.lower_span(span); let param_node_id = self.next_node_id(); diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 28523bcb3bf7..7cd0cd1ebcdc 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -193,7 +193,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { impl_trait_defs: Vec::new(), impl_trait_bounds: Vec::new(), allow_try_trait: [sym::try_trait_v2, sym::yeet_desugar_details].into(), - allow_gen_future: if tcx.features().async_fn_track_caller { + allow_gen_future: if tcx.features().async_fn_track_caller() { [sym::gen_future, sym::closure_track_caller].into() } else { [sym::gen_future].into() @@ -1035,7 +1035,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { span: data.inputs_span, }) }; - if !self.tcx.features().return_type_notation + if !self.tcx.features().return_type_notation() && self.tcx.sess.is_nightly_build() { add_feature_diagnostics( @@ -1160,7 +1160,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(lt)), ast::GenericArg::Type(ty) => { match &ty.kind { - TyKind::Infer if self.tcx.features().generic_arg_infer => { + TyKind::Infer if self.tcx.features().generic_arg_infer() => { return GenericArg::Infer(hir::InferArg { hir_id: self.lower_node_id(ty.id), span: self.lower_span(ty.span), @@ -1500,7 +1500,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // is enabled. We don't check the span of the edition, since this is done // on a per-opaque basis to account for nested opaques. let always_capture_in_scope = match origin { - _ if self.tcx.features().lifetime_capture_rules_2024 => true, + _ if self.tcx.features().lifetime_capture_rules_2024() => true, hir::OpaqueTyOrigin::TyAlias { .. } => true, hir::OpaqueTyOrigin::FnReturn { in_trait_or_impl, .. } => in_trait_or_impl.is_some(), hir::OpaqueTyOrigin::AsyncFn { .. } => { @@ -1519,7 +1519,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Feature gate for RPITIT + use<..> match origin { rustc_hir::OpaqueTyOrigin::FnReturn { in_trait_or_impl: Some(_), .. } => { - if !self.tcx.features().precise_capturing_in_traits + if !self.tcx.features().precise_capturing_in_traits() && let Some(span) = bounds.iter().find_map(|bound| match *bound { ast::GenericBound::Use(_, span) => Some(span), _ => None, @@ -2270,7 +2270,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen<'hir> { match c.value.kind { ExprKind::Underscore => { - if self.tcx.features().generic_arg_infer { + if self.tcx.features().generic_arg_infer() { hir::ArrayLen::Infer(hir::InferArg { hir_id: self.lower_node_id(c.id), span: self.lower_span(c.value.span), diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index e60488fdc8c7..258655de486f 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -268,7 +268,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { span: data.inputs_span, }) }; - if !self.tcx.features().return_type_notation + if !self.tcx.features().return_type_notation() && self.tcx.sess.is_nightly_build() { add_feature_diagnostics( @@ -496,7 +496,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // // disallowed --^^^^^^^^^^ allowed --^^^^^^^^^^ // ``` FnRetTy::Ty(ty) if matches!(itctx, ImplTraitContext::OpaqueTy { .. }) => { - if self.tcx.features().impl_trait_in_fn_trait_return { + if self.tcx.features().impl_trait_in_fn_trait_return() { self.lower_ty(ty, itctx) } else { self.lower_ty( diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 20a4f2120dcd..bf6ebfb160bc 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -295,7 +295,8 @@ impl<'a> AstValidator<'a> { return; }; - let make_impl_const_sugg = if self.features.const_trait_impl + let const_trait_impl = self.features.const_trait_impl(); + let make_impl_const_sugg = if const_trait_impl && let TraitOrTraitImpl::TraitImpl { constness: Const::No, polarity: ImplPolarity::Positive, @@ -308,13 +309,12 @@ impl<'a> AstValidator<'a> { None }; - let make_trait_const_sugg = if self.features.const_trait_impl - && let TraitOrTraitImpl::Trait { span, constness: None } = parent - { - Some(span.shrink_to_lo()) - } else { - None - }; + let make_trait_const_sugg = + if const_trait_impl && let TraitOrTraitImpl::Trait { span, constness: None } = parent { + Some(span.shrink_to_lo()) + } else { + None + }; let parent_constness = parent.constness(); self.dcx().emit_err(errors::TraitFnConst { @@ -1145,7 +1145,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } self.check_type_no_bounds(bounds, "this context"); - if self.features.lazy_type_alias { + if self.features.lazy_type_alias() { if let Err(err) = self.check_type_alias_where_clause_location(ty_alias) { self.dcx().emit_err(err); } @@ -1286,7 +1286,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { GenericBound::Trait(trait_ref) => { match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) { (BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_)) - if !self.features.more_maybe_bounds => + if !self.features.more_maybe_bounds() => { self.sess .create_feature_err( @@ -1299,7 +1299,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { .emit(); } (BoundKind::TraitObject, BoundConstness::Never, BoundPolarity::Maybe(_)) - if !self.features.more_maybe_bounds => + if !self.features.more_maybe_bounds() => { self.sess .create_feature_err( diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 94fcfabc32ca..348a602fd59d 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -15,13 +15,13 @@ use crate::errors; /// The common case. macro_rules! gate { ($visitor:expr, $feature:ident, $span:expr, $explain:expr) => {{ - if !$visitor.features.$feature && !$span.allows_unstable(sym::$feature) { + if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) { #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable feature_err(&$visitor.sess, sym::$feature, $span, $explain).emit(); } }}; ($visitor:expr, $feature:ident, $span:expr, $explain:expr, $help:expr) => {{ - if !$visitor.features.$feature && !$span.allows_unstable(sym::$feature) { + if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) { // FIXME: make this translatable #[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::untranslatable_diagnostic)] @@ -43,7 +43,7 @@ macro_rules! gate_alt { /// The case involving a multispan. macro_rules! gate_multi { ($visitor:expr, $feature:ident, $spans:expr, $explain:expr) => {{ - if !$visitor.features.$feature { + if !$visitor.features.$feature() { let spans: Vec<_> = $spans.filter(|span| !span.allows_unstable(sym::$feature)).collect(); if !spans.is_empty() { @@ -56,7 +56,7 @@ macro_rules! gate_multi { /// The legacy case. macro_rules! gate_legacy { ($visitor:expr, $feature:ident, $span:expr, $explain:expr) => {{ - if !$visitor.features.$feature && !$span.allows_unstable(sym::$feature) { + if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) { feature_warn(&$visitor.sess, sym::$feature, $span, $explain); } }}; @@ -150,7 +150,7 @@ impl<'a> PostExpansionVisitor<'a> { // FIXME(non_lifetime_binders): Const bound params are pretty broken. // Let's keep users from using this feature accidentally. - if self.features.non_lifetime_binders { + if self.features.non_lifetime_binders() { let const_param_spans: Vec<_> = params .iter() .filter_map(|param| match param.kind { @@ -210,7 +210,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } // Emit errors for non-staged-api crates. - if !self.features.staged_api { + if !self.features.staged_api() { if attr.has_name(sym::unstable) || attr.has_name(sym::stable) || attr.has_name(sym::rustc_const_unstable) @@ -470,7 +470,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { // Limit `min_specialization` to only specializing functions. gate_alt!( &self, - self.features.specialization || (is_fn && self.features.min_specialization), + self.features.specialization() || (is_fn && self.features.min_specialization()), sym::specialization, i.span, "specialization is unstable" @@ -548,7 +548,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { gate_all!(return_type_notation, "return type notation is experimental"); gate_all!(pin_ergonomics, "pinned reference syntax is experimental"); - if !visitor.features.never_patterns { + if !visitor.features.never_patterns() { if let Some(spans) = spans.get(&sym::never_patterns) { for &span in spans { if span.allows_unstable(sym::never_patterns) { @@ -572,7 +572,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { } } - if !visitor.features.negative_bounds { + if !visitor.features.negative_bounds() { for &span in spans.get(&sym::negative_bounds).iter().copied().flatten() { sess.dcx().emit_err(errors::NegativeBoundUnsupported { span }); } diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index bbb174976844..e412417a9e95 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -622,7 +622,7 @@ pub fn eval_condition( &(( if *b { kw::True } else { kw::False }, sym::cfg_boolean_literals, - |features: &Features| features.cfg_boolean_literals, + |features: &Features| features.cfg_boolean_literals(), )), cfg.span(), sess, @@ -711,7 +711,7 @@ pub fn eval_condition( } sym::target => { if let Some(features) = features - && !features.cfg_target_compact + && !features.cfg_target_compact() { feature_err( sess, @@ -831,7 +831,7 @@ pub fn find_deprecation( attrs: &[Attribute], ) -> Option<(Deprecation, Span)> { let mut depr: Option<(Deprecation, Span)> = None; - let is_rustc = features.staged_api; + let is_rustc = features.staged_api(); 'outer: for attr in attrs { if !attr.has_name(sym::deprecated) { @@ -891,7 +891,7 @@ pub fn find_deprecation( } } sym::suggestion => { - if !features.deprecated_suggestion { + if !features.deprecated_suggestion() { sess.dcx().emit_err( session_diagnostics::DeprecatedItemSuggestion { span: mi.span, @@ -909,7 +909,7 @@ pub fn find_deprecation( sess.dcx().emit_err(session_diagnostics::UnknownMetaItem { span: meta.span(), item: pprust::path_to_string(&mi.path), - expected: if features.deprecated_suggestion { + expected: if features.deprecated_suggestion() { &["since", "note", "suggestion"] } else { &["since", "note"] diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 7b60a632c305..a544d88e8321 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -1035,7 +1035,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { fn unsized_feature_enabled(&self) -> bool { let features = self.tcx().features(); - features.unsized_locals || features.unsized_fn_params + features.unsized_locals() || features.unsized_fn_params() } /// Equate the inferred type and the annotated type for user type annotations diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index 714493509859..599b180f8793 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -69,7 +69,7 @@ pub(crate) fn expand_assert<'cx>( // If `generic_assert` is enabled, generates rich captured outputs // // FIXME(c410-f3r) See https://github.com/rust-lang/rust/issues/96949 - else if cx.ecfg.features.generic_assert { + else if cx.ecfg.features.generic_assert() { context::Context::new(cx, call_site_span).build(cond_expr, panic_path()) } // If `generic_assert` is not enabled, only outputs a literal "assertion failed: ..." diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index d536419ab3c2..a5bd3adbcddc 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -137,7 +137,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { let inner = attr.meta_item_list(); match inner.as_deref() { Some([item]) if item.has_name(sym::linker) => { - if !tcx.features().used_with_arg { + if !tcx.features().used_with_arg() { feature_err( &tcx.sess, sym::used_with_arg, @@ -149,7 +149,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER; } Some([item]) if item.has_name(sym::compiler) => { - if !tcx.features().used_with_arg { + if !tcx.features().used_with_arg() { feature_err( &tcx.sess, sym::used_with_arg, @@ -213,7 +213,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { .emit(); } if is_closure - && !tcx.features().closure_track_caller + && !tcx.features().closure_track_caller() && !attr.span.allows_unstable(sym::closure_track_caller) { feature_err( @@ -268,7 +268,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // // This exception needs to be kept in sync with allowing // `#[target_feature]` on `main` and `start`. - } else if !tcx.features().target_feature_11 { + } else if !tcx.features().target_feature_11() { feature_err( &tcx.sess, sym::target_feature_11, @@ -584,7 +584,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // its parent function, which effectively inherits the features anyway. Boxing this closure // would result in this closure being compiled without the inherited target features, but this // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute. - if tcx.features().target_feature_11 + if tcx.features().target_feature_11() && tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always { diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index dfe8fd616e4a..d99307106092 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -63,27 +63,27 @@ pub(crate) fn from_target_feature( // Only allow features whose feature gates have been enabled. let allowed = match feature_gate.as_ref().copied() { - Some(sym::arm_target_feature) => rust_features.arm_target_feature, - Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature, - Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature, - Some(sym::mips_target_feature) => rust_features.mips_target_feature, - Some(sym::riscv_target_feature) => rust_features.riscv_target_feature, - Some(sym::avx512_target_feature) => rust_features.avx512_target_feature, - Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature, - Some(sym::tbm_target_feature) => rust_features.tbm_target_feature, - Some(sym::wasm_target_feature) => rust_features.wasm_target_feature, - Some(sym::rtm_target_feature) => rust_features.rtm_target_feature, - Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature, - Some(sym::bpf_target_feature) => rust_features.bpf_target_feature, - Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature, - Some(sym::csky_target_feature) => rust_features.csky_target_feature, - Some(sym::loongarch_target_feature) => rust_features.loongarch_target_feature, - Some(sym::lahfsahf_target_feature) => rust_features.lahfsahf_target_feature, - Some(sym::prfchw_target_feature) => rust_features.prfchw_target_feature, - Some(sym::sha512_sm_x86) => rust_features.sha512_sm_x86, - Some(sym::x86_amx_intrinsics) => rust_features.x86_amx_intrinsics, - Some(sym::xop_target_feature) => rust_features.xop_target_feature, - Some(sym::s390x_target_feature) => rust_features.s390x_target_feature, + Some(sym::arm_target_feature) => rust_features.arm_target_feature(), + Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature(), + Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature(), + Some(sym::mips_target_feature) => rust_features.mips_target_feature(), + Some(sym::riscv_target_feature) => rust_features.riscv_target_feature(), + Some(sym::avx512_target_feature) => rust_features.avx512_target_feature(), + Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature(), + Some(sym::tbm_target_feature) => rust_features.tbm_target_feature(), + Some(sym::wasm_target_feature) => rust_features.wasm_target_feature(), + Some(sym::rtm_target_feature) => rust_features.rtm_target_feature(), + Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature(), + Some(sym::bpf_target_feature) => rust_features.bpf_target_feature(), + Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature(), + Some(sym::csky_target_feature) => rust_features.csky_target_feature(), + Some(sym::loongarch_target_feature) => rust_features.loongarch_target_feature(), + Some(sym::lahfsahf_target_feature) => rust_features.lahfsahf_target_feature(), + Some(sym::prfchw_target_feature) => rust_features.prfchw_target_feature(), + Some(sym::sha512_sm_x86) => rust_features.sha512_sm_x86(), + Some(sym::x86_amx_intrinsics) => rust_features.x86_amx_intrinsics(), + Some(sym::xop_target_feature) => rust_features.xop_target_feature(), + Some(sym::s390x_target_feature) => rust_features.s390x_target_feature(), Some(name) => bug!("unknown target feature gate {}", name), None => true, }; diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 73344508a9d8..288798bf0c27 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -611,7 +611,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // the trait into the concrete method, and uses that for const stability // checks. // FIXME(effects) we might consider moving const stability checks to typeck as well. - if tcx.features().effects { + if tcx.features().effects() { is_trait = true; if let Ok(Some(instance)) = @@ -631,7 +631,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { args: fn_args, span: *fn_span, call_source, - feature: Some(if tcx.features().const_trait_impl { + feature: Some(if tcx.features().const_trait_impl() { sym::effects } else { sym::const_trait_impl diff --git a/compiler/rustc_const_eval/src/check_consts/mod.rs b/compiler/rustc_const_eval/src/check_consts/mod.rs index 15ac4cedcc32..3720418d4f01 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -61,7 +61,7 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> { pub fn is_const_stable_const_fn(&self) -> bool { self.const_kind == Some(hir::ConstContext::ConstFn) - && self.tcx.features().staged_api + && self.tcx.features().staged_api() && is_const_stable_const_fn(self.tcx, self.def_id().to_def_id()) } diff --git a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs index f98234ce7f3c..d04d7b273f03 100644 --- a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs @@ -24,7 +24,7 @@ pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { ); } - ccx.tcx.features().const_precise_live_drops + ccx.tcx.features().const_precise_live_drops() } /// Look for live drops in a const context. diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index a6b7291ee8f4..7546c830a0b3 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -88,7 +88,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - // If the enabled feature is stable, record it. if let Some(f) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) { let since = Some(Symbol::intern(f.since)); - features.set_enabled_lang_feature(name, mi.span(), since, None); + features.set_enabled_lang_feature(name, mi.span(), since); continue; } @@ -103,7 +103,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - } // If the enabled feature is unstable, record it. - if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name) { + if UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name).is_some() { // When the ICE comes from core, alloc or std (approximation of the standard // library), there's a chance that the person hitting the ICE may be using // -Zbuild-std or similar with an untested target. The bug is probably in the @@ -114,7 +114,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - { sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed); } - features.set_enabled_lang_feature(name, mi.span(), None, Some(f)); + features.set_enabled_lang_feature(name, mi.span(), None); continue; } @@ -395,7 +395,7 @@ impl<'a> StripUnconfigured<'a> { /// If attributes are not allowed on expressions, emit an error for `attr` #[instrument(level = "trace", skip(self))] pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) { - if self.features.is_some_and(|features| !features.stmt_expr_attributes) + if self.features.is_some_and(|features| !features.stmt_expr_attributes()) && !attr.span.allows_unstable(sym::stmt_expr_attributes) { let mut err = feature_err( diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index a872b12e744c..5ffafcaa5426 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -867,7 +867,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { | Annotatable::FieldDef(..) | Annotatable::Variant(..) => panic!("unexpected annotatable"), }; - if self.cx.ecfg.features.proc_macro_hygiene { + if self.cx.ecfg.features.proc_macro_hygiene() { return; } feature_err( @@ -905,7 +905,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } } - if !self.cx.ecfg.features.proc_macro_hygiene { + if !self.cx.ecfg.features.proc_macro_hygiene() { annotatable.visit_with(&mut GateProcMacroInput { sess: &self.cx.sess }); } } diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index e518b27e419f..1345f06d5ac1 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -121,14 +121,14 @@ pub(super) fn parse( /// Asks for the `macro_metavar_expr` feature if it is not enabled fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &Session, span: Span) { - if !features.macro_metavar_expr { + if !features.macro_metavar_expr() { let msg = "meta-variable expressions are unstable"; feature_err(sess, sym::macro_metavar_expr, span, msg).emit(); } } fn maybe_emit_macro_metavar_expr_concat_feature(features: &Features, sess: &Session, span: Span) { - if !features.macro_metavar_expr_concat { + if !features.macro_metavar_expr_concat() { let msg = "the `concat` meta-variable expression is unstable"; feature_err(sess, sym::macro_metavar_expr_concat, span, msg).emit(); } diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 477760a45975..5ba4491e97f5 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -14,7 +14,7 @@ type GateFn = fn(&Features) -> bool; macro_rules! cfg_fn { ($field: ident) => { - (|features| features.$field) as GateFn + Features::$field as GateFn }; } @@ -1193,7 +1193,7 @@ pub static BUILTIN_ATTRIBUTE_MAP: LazyLock> pub fn is_stable_diagnostic_attribute(sym: Symbol, features: &Features) -> bool { match sym { sym::on_unimplemented => true, - sym::do_not_recommend => features.do_not_recommend, + sym::do_not_recommend => features.do_not_recommend(), _ => false, } } diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 0606f2914c34..93e91c0984c7 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -8,7 +8,6 @@ use super::{Feature, to_nonzero}; pub struct UnstableFeature { pub feature: Feature, - set_enabled: fn(&mut Features), } #[derive(PartialEq)] @@ -30,6 +29,53 @@ macro_rules! status_to_enum { }; } +/// A set of features to be used by later passes. +/// +/// There are two ways to check if a language feature `foo` is enabled: +/// - Directly with the `foo` method, e.g. `if tcx.features().foo() { ... }`. +/// - With the `enabled` method, e.g. `if tcx.features.enabled(sym::foo) { ... }`. +/// +/// The former is preferred. `enabled` should only be used when the feature symbol is not a +/// constant, e.g. a parameter, or when the feature is a library feature. +#[derive(Clone, Default, Debug)] +pub struct Features { + /// `#![feature]` attrs for language features, for error reporting. + enabled_lang_features: Vec<(Symbol, Span, Option)>, + /// `#![feature]` attrs for non-language (library) features. + enabled_lib_features: Vec<(Symbol, Span)>, + /// `enabled_lang_features` + `enabled_lib_features`. + enabled_features: FxHashSet, +} + +impl Features { + pub fn set_enabled_lang_feature(&mut self, name: Symbol, span: Span, since: Option) { + self.enabled_lang_features.push((name, span, since)); + self.enabled_features.insert(name); + } + + pub fn set_enabled_lib_feature(&mut self, name: Symbol, span: Span) { + self.enabled_lib_features.push((name, span)); + self.enabled_features.insert(name); + } + + pub fn enabled_lang_features(&self) -> &Vec<(Symbol, Span, Option)> { + &self.enabled_lang_features + } + + pub fn enabled_lib_features(&self) -> &Vec<(Symbol, Span)> { + &self.enabled_lib_features + } + + pub fn enabled_features(&self) -> &FxHashSet { + &self.enabled_features + } + + /// Is the given feature enabled (via `#[feature(...)]`)? + pub fn enabled(&self, feature: Symbol) -> bool { + self.enabled_features.contains(&feature) + } +} + macro_rules! declare_features { ($( $(#[doc = $doc:tt])* ($status:ident, $feature:ident, $ver:expr, $issue:expr), @@ -43,97 +89,15 @@ macro_rules! declare_features { since: $ver, issue: to_nonzero($issue), }, - // Sets this feature's corresponding bool within `features`. - set_enabled: |features| features.$feature = true, }),+ ]; - const NUM_FEATURES: usize = UNSTABLE_FEATURES.len(); - - /// A set of features to be used by later passes. - #[derive(Clone, Default, Debug)] - pub struct Features { - /// `#![feature]` attrs for language features, for error reporting. - enabled_lang_features: Vec<(Symbol, Span, Option)>, - /// `#![feature]` attrs for non-language (library) features. - enabled_lib_features: Vec<(Symbol, Span)>, - /// `enabled_lang_features` + `enabled_lib_features`. - enabled_features: FxHashSet, - /// State of individual features (unstable lang features only). - /// This is `true` if and only if the corresponding feature is listed in `enabled_lang_features`. - $( - $(#[doc = $doc])* - pub $feature: bool - ),+ - } - impl Features { - pub fn set_enabled_lang_feature( - &mut self, - name: Symbol, - span: Span, - since: Option, - feature: Option<&UnstableFeature>, - ) { - self.enabled_lang_features.push((name, span, since)); - self.enabled_features.insert(name); - if let Some(feature) = feature { - assert_eq!(feature.feature.name, name); - (feature.set_enabled)(self); - } else { - // Ensure we don't skip a `set_enabled` call. - debug_assert!(UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name).is_none()); + $( + pub fn $feature(&self) -> bool { + self.enabled_features.contains(&sym::$feature) } - } - - pub fn set_enabled_lib_feature(&mut self, name: Symbol, span: Span) { - self.enabled_lib_features.push((name, span)); - self.enabled_features.insert(name); - // Ensure we don't skip a `set_enabled` call. - debug_assert!(UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name).is_none()); - } - - /// This is intended for hashing the set of enabled language features. - /// - /// The expectation is that this produces much smaller code than other alternatives. - /// - /// Note that the total feature count is pretty small, so this is not a huge array. - #[inline] - pub fn all_lang_features(&self) -> [u8; NUM_FEATURES] { - [$(self.$feature as u8),+] - } - - pub fn enabled_lang_features(&self) -> &Vec<(Symbol, Span, Option)> { - &self.enabled_lang_features - } - - pub fn enabled_lib_features(&self) -> &Vec<(Symbol, Span)> { - &self.enabled_lib_features - } - - pub fn enabled_features(&self) -> &FxHashSet { - &self.enabled_features - } - - /// Is the given feature enabled (via `#[feature(...)]`)? - pub fn enabled(&self, feature: Symbol) -> bool { - let e = self.enabled_features.contains(&feature); - if cfg!(debug_assertions) { - // Ensure this matches `self.$feature`, if that exists. - let e2 = match feature { - $( sym::$feature => Some(self.$feature), )* - _ => None, - }; - if let Some(e2) = e2 { - assert_eq!( - e, e2, - "mismatch in feature state for `{feature}`: \ - `enabled_features` says {e} but `self.{feature}` says {e2}" - ); - } - } - e - } + )* /// Some features are known to be incomplete and using them is likely to have /// unanticipated results, such as compiler crashes. We warn the user about these diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index 9a2c38e51e2b..77df0cb7ef90 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -72,7 +72,7 @@ impl<'tcx> Bounds<'tcx> { // FIXME(effects): Lift this out of `push_trait_bound`, and move it somewhere else. // Perhaps moving this into `lower_poly_trait_ref`, just like we lower associated // type bounds. - if !tcx.features().effects { + if !tcx.features().effects() { return; } match predicate_filter { diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 2aeeb9450ce9..97f3f1c8ef27 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1166,7 +1166,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) return; } - if adt.is_union() && !tcx.features().transparent_unions { + if adt.is_union() && !tcx.features().transparent_unions() { feature_err( &tcx.sess, sym::transparent_unions, @@ -1301,7 +1301,7 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) { let repr_type_ty = def.repr().discr_type().to_ty(tcx); if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 { - if !tcx.features().repr128 { + if !tcx.features().repr128() { feature_err( &tcx.sess, sym::repr128, diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 1a5f46598128..312fb16c93aa 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -167,7 +167,7 @@ fn resolve_block<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, blk: &'tcx h } } if let Some(tail_expr) = blk.expr { - if visitor.tcx.features().shorter_tail_lifetimes + if visitor.tcx.features().shorter_tail_lifetimes() && blk.span.edition().at_least_rust_2024() { visitor.terminating_scopes.insert(tail_expr.hir_id.local_id); @@ -466,7 +466,8 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h hir::ExprKind::If(cond, then, Some(otherwise)) => { let expr_cx = visitor.cx; - let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope { + let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope() + { ScopeData::IfThenRescope } else { ScopeData::IfThen @@ -481,7 +482,8 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h hir::ExprKind::If(cond, then, None) => { let expr_cx = visitor.cx; - let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope { + let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope() + { ScopeData::IfThenRescope } else { ScopeData::IfThen diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index f788456d4e9e..3170c0ac9907 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -110,7 +110,7 @@ where let mut wfcx = WfCheckingCtxt { ocx, span, body_def_id, param_env }; - if !tcx.features().trivial_bounds { + if !tcx.features().trivial_bounds() { wfcx.check_false_global_bounds() } f(&mut wfcx)?; @@ -921,7 +921,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(), } => { let ty = tcx.type_of(param.def_id).instantiate_identity(); - if tcx.features().unsized_const_params { + if tcx.features().unsized_const_params() { enter_wf_checking_ctxt(tcx, hir_ty.span, param.def_id, |wfcx| { wfcx.register_bound( ObligationCause::new( @@ -935,7 +935,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(), ); Ok(()) }) - } else if tcx.features().adt_const_params { + } else if tcx.features().adt_const_params() { enter_wf_checking_ctxt(tcx, hir_ty.span, param.def_id, |wfcx| { wfcx.register_bound( ObligationCause::new( @@ -1698,9 +1698,9 @@ fn check_method_receiver<'tcx>( return Ok(()); } - let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers { + let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() { Some(ArbitrarySelfTypesLevel::WithPointers) - } else if tcx.features().arbitrary_self_types { + } else if tcx.features().arbitrary_self_types() { Some(ArbitrarySelfTypesLevel::Basic) } else { None diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index dfb3c088afb0..2afc2aec1baa 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -77,7 +77,7 @@ impl<'tcx> InherentCollect<'tcx> { return Ok(()); } - if self.tcx.features().rustc_attrs { + if self.tcx.features().rustc_attrs() { let items = self.tcx.associated_item_def_ids(impl_def_id); if !self.tcx.has_attr(ty_def_id, sym::rustc_has_incoherent_inherent_impls) { @@ -115,7 +115,7 @@ impl<'tcx> InherentCollect<'tcx> { ) -> Result<(), ErrorGuaranteed> { let items = self.tcx.associated_item_def_ids(impl_def_id); if !self.tcx.hir().rustc_coherence_is_core() { - if self.tcx.features().rustc_attrs { + if self.tcx.features().rustc_attrs() { for &impl_item in items { if !self.tcx.has_attr(impl_item, sym::rustc_allow_incoherent_impl) { let span = self.tcx.def_span(impl_def_id); diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index eea5a16ac6fd..3aad4bafeb5a 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -53,7 +53,7 @@ fn enforce_trait_manually_implementable( ) -> Result<(), ErrorGuaranteed> { let impl_header_span = tcx.def_span(impl_def_id); - if tcx.is_lang_item(trait_def_id, LangItem::Freeze) && !tcx.features().freeze_impls { + if tcx.is_lang_item(trait_def_id, LangItem::Freeze) && !tcx.features().freeze_impls() { feature_err( &tcx.sess, sym::freeze_impls, @@ -86,8 +86,8 @@ fn enforce_trait_manually_implementable( if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable = trait_def.specialization_kind { - if !tcx.features().specialization - && !tcx.features().min_specialization + if !tcx.features().specialization() + && !tcx.features().min_specialization() && !impl_header_span.allows_unstable(sym::specialization) && !impl_header_span.allows_unstable(sym::min_specialization) { diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index f63e2d40e390..acc21d0994bf 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1129,7 +1129,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { }; let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar); - if paren_sugar && !tcx.features().unboxed_closures { + if paren_sugar && !tcx.features().unboxed_closures() { tcx.dcx().emit_err(errors::ParenSugarAttribute { span: item.span }); } @@ -1696,7 +1696,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( // Feature gate SIMD types in FFI, since I am not sure that the // ABIs are handled at all correctly. -huonw - if abi != abi::Abi::RustIntrinsic && !tcx.features().simd_ffi { + if abi != abi::Abi::RustIntrinsic && !tcx.features().simd_ffi() { let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| { if ty.is_simd() { let snip = tcx diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 14b6b17ed18a..348b2260d260 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -109,7 +109,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { // We do not allow generic parameters in anon consts if we are inside // of a const parameter type, e.g. `struct Foo` is not allowed. None - } else if tcx.features().generic_const_exprs { + } else if tcx.features().generic_const_exprs() { let parent_node = tcx.parent_hir_node(hir_id); debug!(?parent_node); if let Node::Variant(Variant { disr_expr: Some(constant), .. }) = parent_node diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 9bd8c70dcfe7..097a1fbc3936 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -308,7 +308,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen } } - if tcx.features().generic_const_exprs { + if tcx.features().generic_const_exprs() { predicates.extend(const_evaluatable_predicates_of(tcx, def_id)); } @@ -524,7 +524,7 @@ pub(super) fn explicit_predicates_of<'tcx>( } } else { if matches!(def_kind, DefKind::AnonConst) - && tcx.features().generic_const_exprs + && tcx.features().generic_const_exprs() && let Some(defaulted_param_def_id) = tcx.hir().opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id)) { diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index cb7f0901c7e4..95e07244a6b3 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1161,7 +1161,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id) && param.is_elided_lifetime() && !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async() - && !self.tcx.features().anonymous_lifetime_in_impl_trait + && !self.tcx.features().anonymous_lifetime_in_impl_trait() { let mut diag: rustc_errors::Diag<'_> = rustc_session::parse::feature_err( &self.tcx.sess, @@ -2239,7 +2239,7 @@ fn deny_non_region_late_bound( format!("late-bound {what} parameter not allowed on {where_}"), ); - let guar = diag.emit_unless(!tcx.features().non_lifetime_binders || !first); + let guar = diag.emit_unless(!tcx.features().non_lifetime_binders() || !first); first = false; *arg = ResolvedArg::Error(guar); diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 470bcaeded16..84161ec76483 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -699,7 +699,7 @@ fn infer_placeholder_type<'tcx>( } fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) { - if !tcx.features().inherent_associated_types { + if !tcx.features().inherent_associated_types() { use rustc_session::parse::feature_err; use rustc_span::symbol::sym; feature_err( @@ -714,7 +714,7 @@ fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) { pub(crate) fn type_alias_is_lazy<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> bool { use hir::intravisit::Visitor; - if tcx.features().lazy_type_alias { + if tcx.features().lazy_type_alias() { return true; } struct HasTait; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index a8b2b9b7c0ac..2b0e1350108f 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -88,7 +88,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }; if seen_repeat { self.dcx().emit_err(err); - } else if !tcx.features().more_maybe_bounds { + } else if !tcx.features().more_maybe_bounds() { self.tcx().sess.create_feature_err(err, sym::more_maybe_bounds).emit(); }; } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index 01768c89cca8..dd0f250a8e28 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -63,7 +63,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { trait_segment: &'_ hir::PathSegment<'_>, is_impl: bool, ) { - if self.tcx().features().unboxed_closures { + if self.tcx().features().unboxed_closures() { return; } @@ -343,7 +343,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { && let Some(hir_ty) = constraint.ty() && let ty = self.lower_ty(hir_ty) && (ty.is_enum() || ty.references_error()) - && tcx.features().associated_const_equality + && tcx.features().associated_const_equality() { Some(errors::AssocKindMismatchWrapInBracesSugg { lo: hir_ty.span.shrink_to_lo(), diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index fe0cd572609f..a73a2f925cd3 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -1241,7 +1241,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // selection during HIR ty lowering instead of in the trait solver), IATs can lead to cycle // errors (#108491) which mask the feature-gate error, needlessly confusing users // who use IATs by accident (#113265). - if !tcx.features().inherent_associated_types { + if !tcx.features().inherent_associated_types() { return Ok(None); } diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index 7f183324f043..d9c70c3cee65 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -57,7 +57,7 @@ pub(crate) fn check_impl_wf( tcx: TyCtxt<'_>, impl_def_id: LocalDefId, ) -> Result<(), ErrorGuaranteed> { - let min_specialization = tcx.features().min_specialization; + let min_specialization = tcx.features().min_specialization(); let mut res = Ok(()); debug_assert_matches!(tcx.def_kind(impl_def_id), DefKind::Impl { .. }); res = res.and(enforce_impl_params_are_constrained(tcx, impl_def_id)); diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 71ee77f8f617..3ad35163191e 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -116,7 +116,7 @@ fn require_c_abi_if_c_variadic(tcx: TyCtxt<'_>, decl: &hir::FnDecl<'_>, abi: Abi return; } - let extended_abi_support = tcx.features().extended_varargs_abi_support; + let extended_abi_support = tcx.features().extended_varargs_abi_support(); let conventions = match (extended_abi_support, abi.supports_varargs()) { // User enabled additional ABI support for varargs and function ABI matches those ones. (true, true) => return, @@ -155,7 +155,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) { // FIXME(effects): remove once effects is implemented in old trait solver // or if the next solver is stabilized. - if tcx.features().effects && !tcx.next_trait_solver_globally() { + if tcx.features().effects() && !tcx.next_trait_solver_globally() { tcx.dcx().emit_err(errors::EffectsWithoutNextSolver); } @@ -172,7 +172,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) { let _ = tcx.ensure().crate_inherent_impls_overlap_check(()); }); - if tcx.features().rustc_attrs { + if tcx.features().rustc_attrs() { tcx.sess.time("outlives_dumping", || outlives::dump::inferred_outlives(tcx)); tcx.sess.time("variance_dumping", || variance::dump::variances(tcx)); collect::dump::opaque_hidden_types(tcx); diff --git a/compiler/rustc_hir_analysis/src/outlives/mod.rs b/compiler/rustc_hir_analysis/src/outlives/mod.rs index e3cdb1bf5f7d..c43917649de2 100644 --- a/compiler/rustc_hir_analysis/src/outlives/mod.rs +++ b/compiler/rustc_hir_analysis/src/outlives/mod.rs @@ -23,7 +23,7 @@ fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[(ty::Clau let crate_map = tcx.inferred_outlives_crate(()); crate_map.predicates.get(&item_def_id.to_def_id()).copied().unwrap_or(&[]) } - DefKind::AnonConst if tcx.features().generic_const_exprs => { + DefKind::AnonConst if tcx.features().generic_const_exprs() => { let id = tcx.local_def_id_to_hir_id(item_def_id); if tcx.hir().opt_const_param_default_param_def_id(id).is_some() { // In `generics_of` we set the generics' parent to be our parent's parent which means that diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 8fa6ab8503d0..f7306063c160 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -721,7 +721,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { use rustc_middle::ty::cast::IntTy::*; if self.cast_ty.is_dyn_star() { - if fcx.tcx.features().dyn_star { + if fcx.tcx.features().dyn_star() { span_bug!(self.span, "should be handled by `coerce`"); } else { // Report "casting is invalid" rather than "non-primitive cast" diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 406d668e7a5b..de80ccf790c1 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -223,11 +223,11 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { ty::Ref(r_b, _, mutbl_b) => { return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); } - ty::Dynamic(predicates, region, ty::DynStar) if self.tcx.features().dyn_star => { + ty::Dynamic(predicates, region, ty::DynStar) if self.tcx.features().dyn_star() => { return self.coerce_dyn_star(a, b, predicates, region); } ty::Adt(pin, _) - if self.tcx.features().pin_ergonomics + if self.tcx.features().pin_ergonomics() && self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => { return self.coerce_pin(a, b); @@ -698,7 +698,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { } if let Some((sub, sup)) = has_trait_upcasting_coercion - && !self.tcx().features().trait_upcasting + && !self.tcx().features().trait_upcasting() { // Renders better when we erase regions, since they're not really the point here. let (sub, sup) = self.tcx.erase_regions((sub, sup)); @@ -712,7 +712,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { err.emit(); } - if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { + if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion() { feature_err( &self.tcx.sess, sym::unsized_tuple_coercion, @@ -732,7 +732,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { predicates: &'tcx ty::List>, b_region: ty::Region<'tcx>, ) -> CoerceResult<'tcx> { - if !self.tcx.features().dyn_star { + if !self.tcx.features().dyn_star() { return Err(TypeError::Mismatch); } @@ -1695,7 +1695,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { blk_id, expression, ); - if !fcx.tcx.features().unsized_locals { + if !fcx.tcx.features().unsized_locals() { unsized_return = self.is_return_ty_definitely_unsized(fcx); } } @@ -1709,7 +1709,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { return_expr_id, expression, ); - if !fcx.tcx.features().unsized_locals { + if !fcx.tcx.features().unsized_locals() { unsized_return = self.is_return_ty_definitely_unsized(fcx); } } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index a1813782e293..da231acbb0f6 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -735,7 +735,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // be known if explicitly specified via turbofish). self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id)); } - if !tcx.features().unsized_fn_params { + if !tcx.features().unsized_fn_params() { // We want to remove some Sized bounds from std functions, // but don't want to expose the removal to stable Rust. // i.e., we don't want to allow @@ -1996,7 +1996,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(base_expr) = base_expr { // FIXME: We are currently creating two branches here in order to maintain // consistency. But they should be merged as much as possible. - let fru_tys = if self.tcx.features().type_changing_struct_update { + let fru_tys = if self.tcx.features().type_changing_struct_update() { if adt.is_struct() { // Make some fresh generic parameters for our ADT type. let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did()); @@ -3552,7 +3552,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (ident, _def_scope) = self.tcx.adjust_ident_and_get_scope(field, container_def.did(), block); - if !self.tcx.features().offset_of_enum { + if !self.tcx.features().offset_of_enum() { rustc_session::parse::feature_err( &self.tcx.sess, sym::offset_of_enum, @@ -3642,7 +3642,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { let field_ty = self.field_ty(expr.span, field, args); - if self.tcx.features().offset_of_slice { + if self.tcx.features().offset_of_slice() { self.require_type_has_static_alignment( field_ty, expr.span, @@ -3675,7 +3675,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && field.name == sym::integer(index) { if let Some(&field_ty) = tys.get(index) { - if self.tcx.features().offset_of_slice { + if self.tcx.features().offset_of_slice() { self.require_type_has_static_alignment( field_ty, expr.span, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 2bc84d1ac673..d2d311ef5654 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1486,7 +1486,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return ty::Const::new_error(self.tcx, guar); } } - } else if self.tcx.features().generic_const_exprs { + } else if self.tcx.features().generic_const_exprs() { ct.normalize_internal(self.tcx, self.param_env) } else { ct diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index e60bd1a312a1..4123feebb407 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -404,7 +404,7 @@ fn default_fallback(tcx: TyCtxt<'_>) -> DivergingFallbackBehavior { } // `feature(never_type_fallback)`: fallback to `!` or `()` trying to not break stuff - if tcx.features().never_type_fallback { + if tcx.features().never_type_fallback() { return DivergingFallbackBehavior::ContextDependent; } diff --git a/compiler/rustc_hir_typeck/src/gather_locals.rs b/compiler/rustc_hir_typeck/src/gather_locals.rs index 5ae8d2230f8f..f427b0b805eb 100644 --- a/compiler/rustc_hir_typeck/src/gather_locals.rs +++ b/compiler/rustc_hir_typeck/src/gather_locals.rs @@ -141,7 +141,7 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { let var_ty = self.assign(p.span, p.hir_id, None); if let Some((ty_span, hir_id)) = self.outermost_fn_param_pat { - if !self.fcx.tcx.features().unsized_fn_params { + if !self.fcx.tcx.features().unsized_fn_params() { self.fcx.require_type_is_sized( var_ty, ty_span, @@ -158,7 +158,7 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { ), ); } - } else if !self.fcx.tcx.features().unsized_locals { + } else if !self.fcx.tcx.features().unsized_locals() { self.fcx.require_type_is_sized( var_ty, p.span, diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 85ee0a5cf7da..85e11ff67450 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -161,7 +161,7 @@ fn typeck_with_fallback<'tcx>( let fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig); let fn_sig = fcx.normalize(body.value.span, fn_sig); - check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params); + check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params()); } else { let expected_type = infer_type_if_missing(&fcx, node); let expected_type = expected_type.unwrap_or_else(fallback); diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 1d7b3433fe5c..f4685725dd30 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -536,7 +536,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // FIXME(arbitrary_self_types): We probably should limit the // situations where this can occur by adding additional restrictions // to the feature, like the self type can't reference method args. - if self.tcx.features().arbitrary_self_types { + if self.tcx.features().arbitrary_self_types() { self.err_ctxt() .report_mismatched_types(&cause, method_self_ty, self_ty, terr) .emit(); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 1be711887d9f..b60fa8bbfa14 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -404,7 +404,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { mode, })); } else if bad_ty.reached_raw_pointer - && !self.tcx.features().arbitrary_self_types_pointers + && !self.tcx.features().arbitrary_self_types_pointers() && !self.tcx.sess.at_least_rust_2018() { // this case used to be allowed by the compiler, @@ -429,8 +429,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = self.resolve_vars_if_possible(ty.value); let guar = match *ty.kind() { ty::Infer(ty::TyVar(_)) => { - let raw_ptr_call = - bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types; + let raw_ptr_call = bad_ty.reached_raw_pointer + && !self.tcx.features().arbitrary_self_types(); let mut err = self.err_ctxt().emit_inference_failure_err( self.body_id, span, @@ -1146,7 +1146,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } ty::Adt(def, args) - if self.tcx.features().pin_ergonomics + if self.tcx.features().pin_ergonomics() && self.tcx.is_lang_item(def.did(), hir::LangItem::Pin) => { // make sure this is a pinned reference (and not a `Pin` or something) @@ -1195,7 +1195,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { self_ty: Ty<'tcx>, unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>, ) -> Option> { - if !self.tcx.features().pin_ergonomics { + if !self.tcx.features().pin_ergonomics() { return None; } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index e961752b24c2..cba6586f01dd 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -442,7 +442,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let features = self.tcx.features(); - if features.ref_pat_eat_one_layer_2024 || features.ref_pat_eat_one_layer_2024_structural { + if features.ref_pat_eat_one_layer_2024() || features.ref_pat_eat_one_layer_2024_structural() + { def_br = def_br.cap_ref_mutability(max_ref_mutbl.as_mutbl()); if def_br == ByRef::Yes(Mutability::Not) { max_ref_mutbl = MutblCap::Not; @@ -490,7 +491,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - if self.tcx.features().string_deref_patterns + if self.tcx.features().string_deref_patterns() && let hir::ExprKind::Lit(Spanned { node: ast::LitKind::Str(..), .. }) = lt.kind { let tcx = self.tcx; @@ -675,10 +676,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let bm = match user_bind_annot { BindingMode(ByRef::No, Mutability::Mut) if matches!(def_br, ByRef::Yes(_)) => { if pat.span.at_least_rust_2024() - && (self.tcx.features().ref_pat_eat_one_layer_2024 - || self.tcx.features().ref_pat_eat_one_layer_2024_structural) + && (self.tcx.features().ref_pat_eat_one_layer_2024() + || self.tcx.features().ref_pat_eat_one_layer_2024_structural()) { - if !self.tcx.features().mut_ref { + if !self.tcx.features().mut_ref() { feature_err( &self.tcx.sess, sym::mut_ref, @@ -2152,8 +2153,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { let tcx = self.tcx; let features = tcx.features(); - let ref_pat_eat_one_layer_2024 = features.ref_pat_eat_one_layer_2024; - let ref_pat_eat_one_layer_2024_structural = features.ref_pat_eat_one_layer_2024_structural; + let ref_pat_eat_one_layer_2024 = features.ref_pat_eat_one_layer_2024(); + let ref_pat_eat_one_layer_2024_structural = + features.ref_pat_eat_one_layer_2024_structural(); let no_ref_mut_behind_and = ref_pat_eat_one_layer_2024 || ref_pat_eat_one_layer_2024_structural; diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 63cf483aa227..9e8a314bc4ae 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -488,7 +488,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let final_upvar_tys = self.final_upvar_tys(closure_def_id); debug!(?closure_hir_id, ?args, ?final_upvar_tys); - if self.tcx.features().unsized_locals || self.tcx.features().unsized_fn_params { + if self.tcx.features().unsized_locals() || self.tcx.features().unsized_fn_params() { for capture in self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id) { diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index d3d092be2223..391e640f8bcb 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -830,7 +830,7 @@ impl<'cx, 'tcx> Resolver<'cx, 'tcx> { value = tcx.fold_regions(value, |_, _| tcx.lifetimes.re_erased); // Normalize consts in writeback, because GCE doesn't normalize eagerly. - if tcx.features().generic_const_exprs { + if tcx.features().generic_const_exprs() { value = value.fold_with(&mut EagerlyNormalizeConsts { tcx, param_env: self.fcx.param_env }); } diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index a006786aa75b..1f46155abc88 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -68,7 +68,7 @@ pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) { // if the `rustc_attrs` feature is not enabled, then the // attributes we are interested in cannot be present anyway, so // skip the walk. - if !tcx.features().rustc_attrs { + if !tcx.features().rustc_attrs() { return; } diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index d25fe4219b58..2075d4214c13 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -140,7 +140,7 @@ pub(crate) fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { } // can't add `#[rustc_clean]` etc without opting into this feature - if !tcx.features().rustc_attrs { + if !tcx.features().rustc_attrs() { return; } diff --git a/compiler/rustc_lint/src/async_fn_in_trait.rs b/compiler/rustc_lint/src/async_fn_in_trait.rs index 63a8a949e969..9923f05df3c7 100644 --- a/compiler/rustc_lint/src/async_fn_in_trait.rs +++ b/compiler/rustc_lint/src/async_fn_in_trait.rs @@ -95,7 +95,7 @@ impl<'tcx> LateLintPass<'tcx> for AsyncFnInTrait { && let hir::IsAsync::Async(async_span) = sig.header.asyncness { // RTN can be used to bound `async fn` in traits in a better way than "always" - if cx.tcx.features().return_type_notation { + if cx.tcx.features().return_type_notation() { return; } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 125fe9b3f16f..71c667b2cd6b 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1235,7 +1235,7 @@ impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller { def_id: LocalDefId, ) { if fn_kind.asyncness().is_async() - && !cx.tcx.features().async_fn_track_caller + && !cx.tcx.features().async_fn_track_caller() // Now, check if the function has the `#[track_caller]` attribute && let Some(attr) = cx.tcx.get_attr(def_id, sym::track_caller) { @@ -1424,7 +1424,7 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { // See also `tests/ui/const-generics/generic_const_exprs/type-alias-bounds.rs`. let ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); if ty.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) - && cx.tcx.features().generic_const_exprs + && cx.tcx.features().generic_const_exprs() { return; } @@ -1538,7 +1538,7 @@ impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { use rustc_middle::ty::ClauseKind; - if cx.tcx.features().trivial_bounds { + if cx.tcx.features().trivial_bounds() { let predicates = cx.tcx.predicates_of(item.owner_id); for &(predicate, span) in predicates.predicates { let predicate_kind_name = match predicate.kind().skip_binder() { diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index 58fd11fcc293..bdfcc2c0a100 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -243,7 +243,7 @@ impl_lint_pass!( impl<'tcx> LateLintPass<'tcx> for IfLetRescope { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { - if expr.span.edition().at_least_rust_2024() || !cx.tcx.features().if_let_rescope { + if expr.span.edition().at_least_rust_2024() || !cx.tcx.features().if_let_rescope() { return; } if let (Level::Allow, _) = cx.tcx.lint_level_at_node(IF_LET_RESCOPE, expr.hir_id) { diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index d029ad934079..cc40b67ab271 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -263,8 +263,8 @@ where && parent == self.parent_def_id { let opaque_span = self.tcx.def_span(opaque_def_id); - let new_capture_rules = - opaque_span.at_least_rust_2024() || self.tcx.features().lifetime_capture_rules_2024; + let new_capture_rules = opaque_span.at_least_rust_2024() + || self.tcx.features().lifetime_capture_rules_2024(); if !new_capture_rules && !opaque.bounds.iter().any(|bound| matches!(bound, hir::GenericBound::Use(..))) { diff --git a/compiler/rustc_lint/src/tail_expr_drop_order.rs b/compiler/rustc_lint/src/tail_expr_drop_order.rs index 44a36142ed48..04f769bf5517 100644 --- a/compiler/rustc_lint/src/tail_expr_drop_order.rs +++ b/compiler/rustc_lint/src/tail_expr_drop_order.rs @@ -137,7 +137,7 @@ impl<'tcx> LateLintPass<'tcx> for TailExprDropOrder { _: Span, def_id: rustc_span::def_id::LocalDefId, ) { - if cx.tcx.sess.at_least_rust_2024() && cx.tcx.features().shorter_tail_lifetimes { + if cx.tcx.sess.at_least_rust_2024() && cx.tcx.features().shorter_tail_lifetimes() { Self::check_fn_or_closure(cx, fn_kind, body, def_id); } } diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 39fa23766b5d..641d1d8e7981 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -170,7 +170,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { let mut upstream_in_dylibs = FxHashSet::default(); - if tcx.features().rustc_private { + if tcx.features().rustc_private() { // We need this to prevent users of `rustc_driver` from linking dynamically to `std` // which does not work as `std` is also statically linked into `rustc_driver`. diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index c7953d50406a..1e6bc413118e 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -265,7 +265,7 @@ impl<'tcx> Collector<'tcx> { NativeLibKind::RawDylib } "link-arg" => { - if !features.link_arg_attribute { + if !features.link_arg_attribute() { feature_err( sess, sym::link_arg_attribute, @@ -314,7 +314,7 @@ impl<'tcx> Collector<'tcx> { .emit_err(errors::LinkCfgSinglePredicate { span: item.span() }); continue; }; - if !features.link_cfg { + if !features.link_cfg() { feature_err( sess, sym::link_cfg, @@ -384,7 +384,7 @@ impl<'tcx> Collector<'tcx> { }; macro report_unstable_modifier($feature: ident) { - if !features.$feature { + if !features.$feature() { // FIXME: make this translatable #[expect(rustc::untranslatable_diagnostic)] feature_err( diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index afe03531861c..ec678c7515b0 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1765,7 +1765,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_stability(&mut self, def_id: DefId) { // The query lookup can take a measurable amount of time in crates with many items. Check if // the stability attributes are even enabled before using their queries. - if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { + if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { if let Some(stab) = self.tcx.lookup_stability(def_id) { record!(self.tables.lookup_stability[def_id] <- stab) } @@ -1776,7 +1776,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_const_stability(&mut self, def_id: DefId) { // The query lookup can take a measurable amount of time in crates with many items. Check if // the stability attributes are even enabled before using their queries. - if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { + if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { if let Some(stab) = self.tcx.lookup_const_stability(def_id) { record!(self.tables.lookup_const_stability[def_id] <- stab) } @@ -1787,7 +1787,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_default_body_stability(&mut self, def_id: DefId) { // The query lookup can take a measurable amount of time in crates with many items. Check if // the stability attributes are even enabled before using their queries. - if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { + if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) { record!(self.tables.lookup_default_body_stability[def_id] <- stab) } diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 59bc55269a30..2ecf1d0bcf85 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -116,7 +116,7 @@ impl<'tcx> TyCtxt<'tcx> { // @lcnr believes that successfully evaluating even though there are // used generic parameters is a bug of evaluation, so checking for it // here does feel somewhat sensible. - if !self.features().generic_const_exprs && ct.args.has_non_region_param() { + if !self.features().generic_const_exprs() && ct.args.has_non_region_param() { let def_kind = self.def_kind(instance.def_id()); assert!( matches!( diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 26dcae001e0e..515aabbe2fc8 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -61,7 +61,7 @@ pub enum OverlapMode { impl OverlapMode { pub fn get(tcx: TyCtxt<'_>, trait_id: DefId) -> OverlapMode { - let with_negative_coherence = tcx.features().with_negative_coherence; + let with_negative_coherence = tcx.features().with_negative_coherence(); let strict_coherence = tcx.has_attr(trait_id, sym::rustc_strict_coherence); if with_negative_coherence { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 9ffdcf646ace..b682524ae39f 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -710,15 +710,15 @@ impl<'tcx> rustc_type_ir::inherent::Safety> for hir::Safety { impl<'tcx> rustc_type_ir::inherent::Features> for &'tcx rustc_feature::Features { fn generic_const_exprs(self) -> bool { - self.generic_const_exprs + self.generic_const_exprs() } fn coroutine_clone(self) -> bool { - self.coroutine_clone + self.coroutine_clone() } fn associated_const_equality(self) -> bool { - self.associated_const_equality + self.associated_const_equality() } } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index dbf88e643c56..7e65df6b27ce 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -398,7 +398,7 @@ impl<'tcx> SizeSkeleton<'tcx> { ), } } - ty::Array(inner, len) if tcx.features().transmute_generic_consts => { + ty::Array(inner, len) if tcx.features().transmute_generic_consts() => { let len_eval = len.try_to_target_usize(tcx); if len_eval == Some(0) { return Ok(SizeSkeleton::Known(Size::from_bytes(0), None)); diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index b5495fa282b6..10c3522eb0e9 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1208,7 +1208,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } - if self.tcx().features().return_type_notation + if self.tcx().features().return_type_notation() && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) = self.tcx().opt_rpitit_info(def_id) && let ty::Alias(_, alias_ty) = diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 74de378c4d78..d8362ccc0a97 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -750,7 +750,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_diverging_default(tcx: TyCtxt<'tcx>) -> Ty<'tcx> { - if tcx.features().never_type_fallback { tcx.types.never } else { tcx.types.unit } + if tcx.features().never_type_fallback() { tcx.types.never } else { tcx.types.unit } } // lang and diagnostic tys diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 9a3049f3be6d..06cbb6c9f1d8 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -877,8 +877,8 @@ impl<'tcx> TyCtxt<'tcx> { // FIXME(effects): This is suspicious and should probably not be done, // especially now that we enforce host effects and then properly handle // effect vars during fallback. - let mut host_always_on = - !self.features().effects || self.sess.opts.unstable_opts.unleash_the_miri_inside_of_you; + let mut host_always_on = !self.features().effects() + || self.sess.opts.unstable_opts.unleash_the_miri_inside_of_you; // Compute the constness required by the context. let const_context = self.hir().body_const_context(def_id); @@ -1826,8 +1826,8 @@ pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool { /// cause an ICE that we otherwise may want to prevent. pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { if (matches!(tcx.fn_sig(def_id).skip_binder().abi(), Abi::RustIntrinsic) - && tcx.features().intrinsics) - || (tcx.has_attr(def_id, sym::rustc_intrinsic) && tcx.features().rustc_attrs) + && tcx.features().intrinsics()) + || (tcx.has_attr(def_id, sym::rustc_intrinsic) && tcx.features().rustc_attrs()) { Some(ty::IntrinsicDef { name: tcx.item_name(def_id.into()), diff --git a/compiler/rustc_mir_build/src/build/expr/as_operand.rs b/compiler/rustc_mir_build/src/build/expr/as_operand.rs index 1e67e759aa20..112eac32264f 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_operand.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_operand.rs @@ -163,7 +163,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let tcx = this.tcx; - if tcx.features().unsized_fn_params { + if tcx.features().unsized_fn_params() { let ty = expr.ty; let param_env = this.param_env; diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index 7170aebee7d2..37cedd8cf5cd 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -149,7 +149,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if let ty::Adt(def, _) = ty.kind() && tcx.is_lang_item(def.did(), LangItem::String) { - if !tcx.features().string_deref_patterns { + if !tcx.features().string_deref_patterns() { span_bug!( test.span, "matching on `String` went through without enabling string_deref_patterns" diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 5995d60e7e07..5faefe2f25f4 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -777,7 +777,7 @@ impl<'tcx> Cx<'tcx> { if_then_scope: region::Scope { id: then.hir_id.local_id, data: { - if expr.span.at_least_rust_2024() && tcx.features().if_let_rescope { + if expr.span.at_least_rust_2024() && tcx.features().if_let_rescope() { region::ScopeData::IfThenRescope } else { region::ScopeData::IfThen diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index ae77bce6bb19..8498df59ce65 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -1126,7 +1126,7 @@ fn report_non_exhaustive_match<'p, 'tcx>( .map(|witness| cx.print_witness_pat(witness)) .collect::>() .join(" | "); - if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns { + if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns() { // Arms with a never pattern don't take a body. pattern } else { diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 0a413d68020d..cd2910589777 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -1497,7 +1497,7 @@ fn check_field_tys_sized<'tcx>( ) { // No need to check if unsized_locals/unsized_fn_params is disabled, // since we will error during typeck. - if !tcx.features().unsized_locals && !tcx.features().unsized_fn_params { + if !tcx.features().unsized_locals() && !tcx.features().unsized_fn_params() { return; } diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index daf868559bca..79c62372df02 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -288,7 +288,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { values: FxIndexSet::with_capacity_and_hasher(num_values, Default::default()), evaluated: IndexVec::with_capacity(num_values), next_opaque: Some(1), - feature_unsized_locals: tcx.features().unsized_locals, + feature_unsized_locals: tcx.features().unsized_locals(), ssa, dominators, reused_locals: BitSet::new_empty(local_decls.len()), diff --git a/compiler/rustc_passes/src/abi_test.rs b/compiler/rustc_passes/src/abi_test.rs index d0cc123c41a8..b1267562f7b8 100644 --- a/compiler/rustc_passes/src/abi_test.rs +++ b/compiler/rustc_passes/src/abi_test.rs @@ -12,7 +12,7 @@ use super::layout_test::ensure_wf; use crate::errors::{AbiInvalidAttribute, AbiNe, AbiOf, UnrecognizedField}; pub fn test_abi(tcx: TyCtxt<'_>) { - if !tcx.features().rustc_attrs { + if !tcx.features().rustc_attrs() { // if the `rustc_attrs` feature is not enabled, don't bother testing ABI return; } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 298c065b0599..864428448238 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1187,7 +1187,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { sym::rust_logo => { if self.check_attr_crate_level(attr, meta, hir_id) - && !self.tcx.features().rustdoc_internals + && !self.tcx.features().rustdoc_internals() { feature_err( &self.tcx.sess, @@ -1774,7 +1774,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } sym::align => { if let (Target::Fn | Target::Method(MethodKind::Inherent), false) = - (target, self.tcx.features().fn_align) + (target, self.tcx.features().fn_align()) { feature_err( &self.tcx.sess, diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index ca13ca11673f..f5ece513956e 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -105,7 +105,7 @@ impl<'tcx> CheckConstVisitor<'tcx> { // If this crate is not using stability attributes, or this function is not claiming to be a // stable `const fn`, that is all that is required. - if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) { + if !tcx.features().staged_api() || tcx.has_attr(def_id, sym::rustc_const_unstable) { return true; } diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 3aef88e771f5..93729a7f6df8 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -18,7 +18,7 @@ use crate::errors::{ }; pub fn test_layout(tcx: TyCtxt<'_>) { - if !tcx.features().rustc_attrs { + if !tcx.features().rustc_attrs() { // if the `rustc_attrs` feature is not enabled, don't bother testing layout return; } diff --git a/compiler/rustc_passes/src/lib_features.rs b/compiler/rustc_passes/src/lib_features.rs index 91ba2fa7548f..8a360c017adb 100644 --- a/compiler/rustc_passes/src/lib_features.rs +++ b/compiler/rustc_passes/src/lib_features.rs @@ -144,7 +144,7 @@ impl<'tcx> Visitor<'tcx> for LibFeatureCollector<'tcx> { fn lib_features(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> LibFeatures { // If `staged_api` is not enabled then we aren't allowed to define lib // features; there is no point collecting them. - if !tcx.features().staged_api { + if !tcx.features().staged_api() { return LibFeatures::default(); } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 80ac2741c386..1bbb0caa58d3 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -144,7 +144,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } } - if !self.tcx.features().staged_api { + if !self.tcx.features().staged_api() { // Propagate unstability. This can happen even for non-staged-api crates in case // -Zforce-unstable-if-unmarked is set. if let Some(stab) = self.parent_stab { @@ -541,7 +541,7 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { } fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) { - if !self.tcx.features().staged_api { + if !self.tcx.features().staged_api() { return; } @@ -734,7 +734,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { // items. hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => { let features = self.tcx.features(); - if features.staged_api { + if features.staged_api() { let attrs = self.tcx.hir().attrs(item.hir_id()); let stab = attr::find_stability(self.tcx.sess, attrs, item.span); let const_stab = attr::find_const_stability(self.tcx.sess, attrs, item.span); @@ -762,7 +762,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable // needs to have an error emitted. - if features.const_trait_impl + if features.const_trait_impl() && self.tcx.is_const_trait_impl_raw(item.owner_id.to_def_id()) && const_stab.is_some_and(|(stab, _)| stab.is_const_stable()) { @@ -926,7 +926,7 @@ impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> { /// libraries, identify activated features that don't exist and error about them. pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { let is_staged_api = - tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api; + tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api(); if is_staged_api { let effective_visibilities = &tcx.effective_visibilities(()); let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities }; diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 70a9319d6668..0e132b27fb4c 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -891,7 +891,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { print::write_slice_like(&mut s, &prefix, has_dot_dot, &suffix).unwrap(); s } - Never if self.tcx.features().never_patterns => "!".to_string(), + Never if self.tcx.features().never_patterns() => "!".to_string(), Never | Wildcard | NonExhaustive | Hidden | PrivateUninhabited => "_".to_string(), Missing { .. } => bug!( "trying to convert a `Missing` constructor into a `Pat`; this is probably a bug, @@ -915,7 +915,7 @@ fn would_print_as_wildcard(tcx: TyCtxt<'_>, p: &WitnessPat<'_, '_>) -> bool { | Constructor::NonExhaustive | Constructor::Hidden | Constructor::PrivateUninhabited => true, - Constructor::Never if !tcx.features().never_patterns => true, + Constructor::Never if !tcx.features().never_patterns() => true, _ => false, } } @@ -929,7 +929,7 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { type PatData = &'p Pat<'tcx>; fn is_exhaustive_patterns_feature_on(&self) -> bool { - self.tcx.features().exhaustive_patterns + self.tcx.features().exhaustive_patterns() } fn ctor_arity(&self, ctor: &crate::constructor::Constructor, ty: &Self::Ty) -> usize { diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 78c37688d34c..68b16a129102 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -115,7 +115,7 @@ impl<'tcx> HashStable> for rustc_feature::Features { self.enabled_lang_features().hash_stable(hcx, hasher); self.enabled_lib_features().hash_stable(hcx, hasher); - self.all_lang_features()[..].hash_stable(hcx, hasher); + // FIXME: why do we hash something that is a compile-time constant? for feature in rustc_feature::UNSTABLE_FEATURES.iter() { feature.feature.name.hash_stable(hcx, hasher); } diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 8ae77902bce6..b80e0e196ca0 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -606,7 +606,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { Scope::BuiltinTypes => match this.builtin_types_bindings.get(&ident.name) { Some(binding) => { if matches!(ident.name, sym::f16) - && !this.tcx.features().f16 + && !this.tcx.features().f16() && !ident.span.allows_unstable(sym::f16) && finalize.is_some() && innermost_result.is_none() @@ -620,7 +620,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { .emit(); } if matches!(ident.name, sym::f128) - && !this.tcx.features().f128 + && !this.tcx.features().f128() && !ident.span.allows_unstable(sym::f128) && finalize.is_some() && innermost_result.is_none() diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 98db36b12be6..033cd7d58705 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -2683,7 +2683,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { self.with_generic_param_rib( &generics.params, RibKind::Item( - if self.r.tcx.features().generic_const_items { + if self.r.tcx.features().generic_const_items() { HasGenericParams::Yes(generics.span) } else { HasGenericParams::No @@ -2888,7 +2888,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { RibKind::Normal => { // FIXME(non_lifetime_binders): Stop special-casing // const params to error out here. - if self.r.tcx.features().non_lifetime_binders + if self.r.tcx.features().non_lifetime_binders() && matches!(param.kind, GenericParamKind::Type { .. }) { Res::Def(def_kind, def_id.to_def_id()) @@ -4411,10 +4411,10 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { let tcx = self.r.tcx(); let gate_err_sym_msg = match prim { - PrimTy::Float(FloatTy::F16) if !tcx.features().f16 => { + PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => { Some((sym::f16, "the type `f16` is unstable")) } - PrimTy::Float(FloatTy::F128) if !tcx.features().f128 => { + PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => { Some((sym::f128, "the type `f128` is unstable")) } _ => None, @@ -4565,7 +4565,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } AnonConstKind::InlineConst => ConstantHasGenerics::Yes, AnonConstKind::ConstArg(_) => { - if self.r.tcx.features().generic_const_exprs || is_trivial_const_arg { + if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg { ConstantHasGenerics::Yes } else { ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg) diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 50fbdcaf9dc2..f0632a21091b 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1198,7 +1198,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // const generics. Of course, `Struct` and `Enum` may contain ty params, too, but the // benefits of including them here outweighs the small number of false positives. Some(Res::Def(DefKind::Struct | DefKind::Enum, _)) - if self.r.tcx.features().adt_const_params => + if self.r.tcx.features().adt_const_params() => { Applicability::MaybeIncorrect } @@ -2773,7 +2773,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // Avoid suggesting placing lifetime parameters on constant items unless the relevant // feature is enabled. Suggest the parent item as a possible location if applicable. if let LifetimeBinderKind::ConstItem = kind - && !self.r.tcx().features().generic_const_items + && !self.r.tcx().features().generic_const_items() { continue; } @@ -2934,7 +2934,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { .emit(); } NoConstantGenericsReason::NonTrivialConstArg => { - assert!(!self.r.tcx.features().generic_const_exprs); + assert!(!self.r.tcx.features().generic_const_exprs()); self.r .dcx() .create_err(errors::ParamInNonTrivialAnonConst { diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 5e38fb5b6c51..a9ebffea8a10 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -661,7 +661,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } // We are trying to avoid reporting this error if other related errors were reported. - if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes { + if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() { let is_macro = match res { Res::Def(..) => true, Res::NonMacroAttr(..) => false, @@ -690,7 +690,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { && namespace.ident.name == sym::diagnostic && !(attribute.ident.name == sym::on_unimplemented || (attribute.ident.name == sym::do_not_recommend - && self.tcx.features().do_not_recommend)) + && self.tcx.features().do_not_recommend())) { let distance = edit_distance(attribute.ident.name.as_str(), sym::on_unimplemented.as_str(), 5); diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index 8cfb65c1c509..73bd8d7555b8 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -18,7 +18,7 @@ pub fn report_symbol_names(tcx: TyCtxt<'_>) { // if the `rustc_attrs` feature is not enabled, then the // attributes we are interested in cannot be present anyway, so // skip the walk. - if !tcx.features().rustc_attrs { + if !tcx.features().rustc_attrs() { return; } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 549beafd1969..9ee4963a3603 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -3026,7 +3026,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { obligation: &PredicateObligation<'tcx>, span: Span, ) -> Result, ErrorGuaranteed> { - if !self.tcx.features().generic_const_exprs { + if !self.tcx.features().generic_const_exprs() { let guar = self .dcx() .struct_span_err(span, "constant expression depends on a generic parameter") diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index ff542cfbec12..1fe93cb017ab 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -3044,7 +3044,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if local { err.note("all local variables must have a statically known size"); } - if !tcx.features().unsized_locals { + if !tcx.features().unsized_locals() { err.help("unsized locals are gated as an unstable feature"); } } @@ -3125,7 +3125,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err.note("all function arguments must have a statically known size"); } if tcx.sess.opts.unstable_features.is_nightly_build() - && !tcx.features().unsized_fn_params + && !tcx.features().unsized_fn_params() { err.help("unsized fn params are gated as an unstable feature"); } @@ -4510,7 +4510,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { trait_ref: ty::PolyTraitRef<'tcx>, ) { // Don't suggest if RTN is active -- we should prefer a where-clause bound instead. - if self.tcx.features().return_type_notation { + if self.tcx.features().return_type_notation() { return; } diff --git a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs index c258832bf2be..1be3c9644546 100644 --- a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs +++ b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs @@ -40,7 +40,7 @@ pub fn is_const_evaluatable<'tcx>( ty::ConstKind::Infer(_) => return Err(NotConstEvaluatable::MentionsInfer), }; - if tcx.features().generic_const_exprs { + if tcx.features().generic_const_exprs() { let ct = tcx.expand_abstract_consts(unexpanded_ct); let is_anon_ct = if let ty::ConstKind::Unevaluated(uv) = ct.kind() { diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs index 364a13b3a759..cc0450e0b057 100644 --- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs +++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs @@ -254,7 +254,7 @@ fn super_predicates_have_non_lifetime_binders( trait_def_id: DefId, ) -> SmallVec<[Span; 1]> { // If non_lifetime_binders is disabled, then exit early - if !tcx.features().non_lifetime_binders { + if !tcx.features().non_lifetime_binders() { return SmallVec::new(); } tcx.explicit_super_predicates_of(trait_def_id) @@ -327,7 +327,7 @@ pub fn dyn_compatibility_violations_for_assoc_item( .collect(), // Associated types can only be dyn-compatible if they have `Self: Sized` bounds. ty::AssocKind::Type => { - if !tcx.features().generic_associated_types_extended + if !tcx.features().generic_associated_types_extended() && !tcx.generics_of(item.def_id).is_own_empty() && !item.is_impl_trait_in_trait() { diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index e56f18669707..2bdeb00bdacb 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -598,7 +598,7 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { ty::PredicateKind::ConstEquate(c1, c2) => { let tcx = self.selcx.tcx(); assert!( - tcx.features().generic_const_exprs, + tcx.features().generic_const_exprs(), "`ConstEquate` without a feature gate: {c1:?} {c2:?}", ); // FIXME: we probably should only try to unify abstract constants diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index cffb9b598416..cdf24887e763 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -346,7 +346,7 @@ pub fn normalize_param_env_or_error<'tcx>( let mut predicates: Vec<_> = util::elaborate( tcx, unnormalized_env.caller_bounds().into_iter().map(|predicate| { - if tcx.features().generic_const_exprs { + if tcx.features().generic_const_exprs() { return predicate; } diff --git a/compiler/rustc_trait_selection/src/traits/normalize.rs b/compiler/rustc_trait_selection/src/traits/normalize.rs index d246d37f7486..12e00ec79ac4 100644 --- a/compiler/rustc_trait_selection/src/traits/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/normalize.rs @@ -402,7 +402,7 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx #[instrument(skip(self), level = "debug")] fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> { let tcx = self.selcx.tcx(); - if tcx.features().generic_const_exprs + if tcx.features().generic_const_exprs() || !needs_normalization(&constant, self.param_env.reveal()) { constant diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index cc634b65a0bf..38722c0ff7c5 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -189,7 +189,7 @@ pub(super) fn poly_project_and_unify_term<'cx, 'tcx>( ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e), ProjectAndUnifyResult::Holds(obligations) if old_universe != new_universe - && selcx.tcx().features().generic_associated_types_extended => + && selcx.tcx().features().generic_associated_types_extended() => { // If the `generic_associated_types_extended` feature is active, then we ignore any // obligations references lifetimes from any universe greater than or equal to the 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 ac38c9e24a29..eea3867190d3 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -876,7 +876,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } if let Some(principal) = data.principal() { - if !self.infcx.tcx.features().dyn_compatible_for_dispatch { + if !self.infcx.tcx.features().dyn_compatible_for_dispatch() { principal.with_self_ty(self.tcx(), self_ty) } else if self.tcx().is_dyn_compatible(principal.def_id()) { principal.with_self_ty(self.tcx(), self_ty) @@ -936,7 +936,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } let tcx = self.tcx(); - if tcx.features().trait_upcasting { + if tcx.features().trait_upcasting() { return None; } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 9a49fd7e77e9..e7d3004aa203 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -402,7 +402,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let mut assume = predicate.trait_ref.args.const_at(2); // FIXME(min_generic_const_exprs): We should shallowly normalize this. - if self.tcx().features().generic_const_exprs { + if self.tcx().features().generic_const_exprs() { assume = assume.normalize_internal(self.tcx(), obligation.param_env); } let Some(assume) = @@ -626,7 +626,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { for assoc_type in assoc_types { let defs: &ty::Generics = tcx.generics_of(assoc_type); - if !defs.own_params.is_empty() && !tcx.features().generic_associated_types_extended { + if !defs.own_params.is_empty() && !tcx.features().generic_associated_types_extended() { tcx.dcx().span_delayed_bug( obligation.cause.span, "GATs in trait object shouldn't have been considered", diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 4757430a21cb..d5b1c5a97daa 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -865,7 +865,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::PredicateKind::ConstEquate(c1, c2) => { let tcx = self.tcx(); assert!( - tcx.features().generic_const_exprs, + tcx.features().generic_const_exprs(), "`ConstEquate` without a feature gate: {c1:?} {c2:?}", ); @@ -2195,7 +2195,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { match self.tcx().coroutine_movability(coroutine_def_id) { hir::Movability::Static => None, hir::Movability::Movable => { - if self.tcx().features().coroutine_clone { + if self.tcx().features().coroutine_clone() { let resolved_upvars = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty()); let resolved_witness = diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index b82a34336458..0e45f7a195f0 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -136,7 +136,7 @@ pub fn translate_args_with_cause<'tcx>( } pub(super) fn specialization_enabled_in(tcx: TyCtxt<'_>, _: LocalCrate) -> bool { - tcx.features().specialization || tcx.features().min_specialization + tcx.features().specialization() || tcx.features().min_specialization() } /// Is `impl1` a specialization of `impl2`? diff --git a/compiler/rustc_trait_selection/src/traits/structural_normalize.rs b/compiler/rustc_trait_selection/src/traits/structural_normalize.rs index f8d98eb856e8..23b5f62b5ca4 100644 --- a/compiler/rustc_trait_selection/src/traits/structural_normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/structural_normalize.rs @@ -82,7 +82,7 @@ impl<'tcx> At<'_, 'tcx> { } Ok(self.infcx.resolve_vars_if_possible(new_infer_ct)) - } else if self.infcx.tcx.features().generic_const_exprs { + } else if self.infcx.tcx.features().generic_const_exprs() { Ok(ct.normalize_internal(self.infcx.tcx, self.param_env)) } else { Ok(self.normalize(ct).into_value_registering_obligations(self.infcx, fulfill_cx)) diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 07e68e5a3e81..8904a9a68580 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -836,7 +836,7 @@ impl<'a, 'tcx> TypeVisitor> for WfPredicates<'a, 'tcx> { // obligations that don't refer to Self and // checking those - let defer_to_coercion = tcx.features().dyn_compatible_for_dispatch; + let defer_to_coercion = tcx.features().dyn_compatible_for_dispatch(); if !defer_to_coercion { if let Some(principal) = data.principal_def_id() { diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index a057caa93295..a3210dd80d77 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -181,7 +181,7 @@ fn associated_item_from_impl_item_ref(impl_item_ref: &hir::ImplItemRef) -> ty::A fn associated_type_for_effects(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { // don't synthesize the associated type even if the user has written `const_trait` // if the effects feature is disabled. - if !tcx.features().effects { + if !tcx.features().effects() { return None; } let (feed, parent_did) = match tcx.def_kind(def_id) { diff --git a/compiler/rustc_ty_utils/src/consts.rs b/compiler/rustc_ty_utils/src/consts.rs index 391985ce88a2..4b770d9938c2 100644 --- a/compiler/rustc_ty_utils/src/consts.rs +++ b/compiler/rustc_ty_utils/src/consts.rs @@ -406,7 +406,7 @@ fn thir_abstract_const<'tcx>( tcx: TyCtxt<'tcx>, def: LocalDefId, ) -> Result>>, ErrorGuaranteed> { - if !tcx.features().generic_const_exprs { + if !tcx.features().generic_const_exprs() { return Ok(None); } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 848f2abe6a9f..bf168809e28c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2189,7 +2189,7 @@ pub(crate) fn clean_middle_ty<'tcx>( } ty::Alias(ty::Weak, data) => { - if cx.tcx.features().lazy_type_alias { + if cx.tcx.features().lazy_type_alias() { // Weak type alias `data` represents the `type X` in `type X = Y`. If we need `Y`, // we need to use `type_of`. let path = clean_middle_path( diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 2e3050eee2fb..6090de16d55b 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -966,8 +966,8 @@ pub(crate) trait AttributesExt { fn cfg(&self, tcx: TyCtxt<'_>, hidden_cfg: &FxHashSet) -> Option> { let sess = tcx.sess; - let doc_cfg_active = tcx.features().doc_cfg; - let doc_auto_cfg_active = tcx.features().doc_auto_cfg; + let doc_cfg_active = tcx.features().doc_cfg(); + let doc_auto_cfg_active = tcx.features().doc_auto_cfg(); fn single(it: T) -> Option { let mut iter = it.into_iter(); diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index f4579d855315..484bdb5627c3 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -116,7 +116,7 @@ pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item find_testable_code(dox, &mut tests, ErrorCodes::No, false, None); - if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples { + if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples() { if should_have_doc_example(cx, item) { debug!("reporting error for {item:?} (hir_id={hir_id:?})"); let sp = item.attr_span(cx.tcx); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 2f0ea8d618c1..140fda709188 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1419,7 +1419,7 @@ impl LinkCollector<'_, '_> { && key.path_str.contains("::") // We only want to check this if this is an associated item. { - if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers { + if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() { self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item); return None; } else { diff --git a/src/tools/clippy/clippy_lints/src/empty_enum.rs b/src/tools/clippy/clippy_lints/src/empty_enum.rs index 70eb81fa09c1..b0389fd9a2f6 100644 --- a/src/tools/clippy/clippy_lints/src/empty_enum.rs +++ b/src/tools/clippy/clippy_lints/src/empty_enum.rs @@ -64,7 +64,7 @@ impl LateLintPass<'_> for EmptyEnum { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if let ItemKind::Enum(..) = item.kind // Only suggest the `never_type` if the feature is enabled - && cx.tcx.features().never_type + && cx.tcx.features().never_type() && let Some(adt) = cx.tcx.type_of(item.owner_id).instantiate_identity().ty_adt_def() && adt.variants().is_empty() { diff --git a/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs b/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs index f9ffbc5dc0b8..20984bc40caf 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs @@ -114,7 +114,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>]) { let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect(); for (&(i, arm1), &(j, arm2)) in search_same(&indexed_arms, hash, eq) { if matches!(arm2.pat.kind, PatKind::Wild) { - if !cx.tcx.features().non_exhaustive_omitted_patterns_lint + if !cx.tcx.features().non_exhaustive_omitted_patterns_lint() || is_lint_allowed(cx, NON_EXHAUSTIVE_OMITTED_PATTERNS, arm2.hir_id) { let arm_span = adjusted_arm_span(cx, arm1.span); diff --git a/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs b/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs index 564c598a334c..42d9efe4ff6f 100644 --- a/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs +++ b/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs @@ -251,7 +251,7 @@ fn emit_redundant_guards<'tcx>( fn expr_can_be_pat(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { for_each_expr_without_closures(expr, |expr| { if match expr.kind { - ExprKind::ConstBlock(..) => cx.tcx.features().inline_const_pat, + ExprKind::ConstBlock(..) => cx.tcx.features().inline_const_pat(), ExprKind::Call(c, ..) if let ExprKind::Path(qpath) = c.kind => { // Allow ctors matches!(cx.qpath_res(&qpath, c.hir_id), Res::Def(DefKind::Ctor(..), ..)) From 7340b9c7c2056ad994aac0071f44f7323d751fa9 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 23 Oct 2024 07:29:25 +0100 Subject: [PATCH 152/366] rustc_feature: remove no-longer-needed macro --- compiler/rustc_feature/src/builtin_attrs.rs | 44 ++++++++++----------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 5ba4491e97f5..753195bf691c 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -12,33 +12,31 @@ use crate::{Features, Stability}; type GateFn = fn(&Features) -> bool; -macro_rules! cfg_fn { - ($field: ident) => { - Features::$field as GateFn - }; -} - pub type GatedCfg = (Symbol, Symbol, GateFn); /// `cfg(...)`'s that are feature gated. const GATED_CFGS: &[GatedCfg] = &[ // (name in cfg, feature, function to check if the feature is enabled) - (sym::overflow_checks, sym::cfg_overflow_checks, cfg_fn!(cfg_overflow_checks)), - (sym::ub_checks, sym::cfg_ub_checks, cfg_fn!(cfg_ub_checks)), - (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)), + (sym::overflow_checks, sym::cfg_overflow_checks, Features::cfg_overflow_checks), + (sym::ub_checks, sym::cfg_ub_checks, Features::cfg_ub_checks), + (sym::target_thread_local, sym::cfg_target_thread_local, Features::cfg_target_thread_local), ( sym::target_has_atomic_equal_alignment, sym::cfg_target_has_atomic_equal_alignment, - cfg_fn!(cfg_target_has_atomic_equal_alignment), + Features::cfg_target_has_atomic_equal_alignment, ), - (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)), - (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)), - (sym::version, sym::cfg_version, cfg_fn!(cfg_version)), - (sym::relocation_model, sym::cfg_relocation_model, cfg_fn!(cfg_relocation_model)), - (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, cfg_fn!(cfg_sanitizer_cfi)), - (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, cfg_fn!(cfg_sanitizer_cfi)), + ( + sym::target_has_atomic_load_store, + sym::cfg_target_has_atomic, + Features::cfg_target_has_atomic, + ), + (sym::sanitize, sym::cfg_sanitize, Features::cfg_sanitize), + (sym::version, sym::cfg_version, Features::cfg_version), + (sym::relocation_model, sym::cfg_relocation_model, Features::cfg_relocation_model), + (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi), + (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi), // this is consistent with naming of the compiler flag it's for - (sym::fmt_debug, sym::fmt_debug, cfg_fn!(fmt_debug)), + (sym::fmt_debug, sym::fmt_debug, Features::fmt_debug), ]; /// Find a gated cfg determined by the `pred`icate which is given the cfg's name. @@ -220,7 +218,7 @@ macro_rules! gated { safety: AttributeSafety::Unsafe, template: $tpl, duplicates: $duplicates, - gate: Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)), + gate: Gated(Stability::Unstable, sym::$gate, $msg, Features::$gate), } }; (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $msg:expr $(,)?) => { @@ -231,7 +229,7 @@ macro_rules! gated { safety: AttributeSafety::Unsafe, template: $tpl, duplicates: $duplicates, - gate: Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)), + gate: Gated(Stability::Unstable, sym::$attr, $msg, Features::$attr), } }; ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $msg:expr $(,)?) => { @@ -242,7 +240,7 @@ macro_rules! gated { safety: AttributeSafety::Normal, template: $tpl, duplicates: $duplicates, - gate: Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)), + gate: Gated(Stability::Unstable, sym::$gate, $msg, Features::$gate), } }; ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $msg:expr $(,)?) => { @@ -253,7 +251,7 @@ macro_rules! gated { safety: AttributeSafety::Normal, template: $tpl, duplicates: $duplicates, - gate: Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)), + gate: Gated(Stability::Unstable, sym::$attr, $msg, Features::$attr), } }; } @@ -282,7 +280,7 @@ macro_rules! rustc_attr { safety: AttributeSafety::Normal, template: $tpl, duplicates: $duplicates, - gate: Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs)), + gate: Gated(Stability::Unstable, sym::rustc_attrs, $msg, Features::rustc_attrs), } }; } @@ -935,7 +933,7 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ Stability::Unstable, sym::rustc_attrs, "diagnostic items compiler internal support for linting", - cfg_fn!(rustc_attrs), + Features::rustc_attrs, ), }, gated!( From 6ad17bd30c68c90792cb0e4fca8208be41493f6b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 23 Oct 2024 07:34:35 +0100 Subject: [PATCH 153/366] get rid of feature list in target feature logic --- .../rustc_codegen_ssa/src/target_features.rs | 26 ++----------------- 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index d99307106092..0845bcc5749f 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -5,7 +5,6 @@ use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::Applicability; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; -use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::TargetFeature; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; @@ -61,30 +60,9 @@ pub(crate) fn from_target_feature( return None; }; - // Only allow features whose feature gates have been enabled. + // Only allow target features whose feature gates have been enabled. let allowed = match feature_gate.as_ref().copied() { - Some(sym::arm_target_feature) => rust_features.arm_target_feature(), - Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature(), - Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature(), - Some(sym::mips_target_feature) => rust_features.mips_target_feature(), - Some(sym::riscv_target_feature) => rust_features.riscv_target_feature(), - Some(sym::avx512_target_feature) => rust_features.avx512_target_feature(), - Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature(), - Some(sym::tbm_target_feature) => rust_features.tbm_target_feature(), - Some(sym::wasm_target_feature) => rust_features.wasm_target_feature(), - Some(sym::rtm_target_feature) => rust_features.rtm_target_feature(), - Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature(), - Some(sym::bpf_target_feature) => rust_features.bpf_target_feature(), - Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature(), - Some(sym::csky_target_feature) => rust_features.csky_target_feature(), - Some(sym::loongarch_target_feature) => rust_features.loongarch_target_feature(), - Some(sym::lahfsahf_target_feature) => rust_features.lahfsahf_target_feature(), - Some(sym::prfchw_target_feature) => rust_features.prfchw_target_feature(), - Some(sym::sha512_sm_x86) => rust_features.sha512_sm_x86(), - Some(sym::x86_amx_intrinsics) => rust_features.x86_amx_intrinsics(), - Some(sym::xop_target_feature) => rust_features.xop_target_feature(), - Some(sym::s390x_target_feature) => rust_features.s390x_target_feature(), - Some(name) => bug!("unknown target feature gate {}", name), + Some(name) => rust_features.enabled(name), None => true, }; if !allowed { From e82bca6f32bd74e018c8bd46fe33986eae514189 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 23 Oct 2024 08:18:19 +0100 Subject: [PATCH 154/366] remove no longer needd UnstableFeature type --- compiler/rustc_expand/src/config.rs | 2 +- compiler/rustc_feature/src/lib.rs | 4 ++-- compiler/rustc_feature/src/unstable.rs | 16 +++++----------- .../rustc_query_system/src/ich/impls_syntax.rs | 2 +- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 7546c830a0b3..af27077f2428 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -103,7 +103,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - } // If the enabled feature is unstable, record it. - if UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name).is_some() { + if UNSTABLE_FEATURES.iter().find(|f| name == f.name).is_some() { // When the ICE comes from core, alloc or std (approximation of the standard // library), there's a chance that the person hitting the ICE may be using // -Zbuild-std or similar with an untested target. The bug is probably in the diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index 8f4c0b0ac95f..7c4996c1412b 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -94,8 +94,8 @@ impl UnstableFeatures { fn find_lang_feature_issue(feature: Symbol) -> Option> { // Search in all the feature lists. - if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| f.feature.name == feature) { - return f.feature.issue; + if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| f.name == feature) { + return f.issue; } if let Some(f) = ACCEPTED_FEATURES.iter().find(|f| f.name == feature) { return f.issue; diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 93e91c0984c7..9c6de079e2fa 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -6,10 +6,6 @@ use rustc_span::symbol::{Symbol, sym}; use super::{Feature, to_nonzero}; -pub struct UnstableFeature { - pub feature: Feature, -} - #[derive(PartialEq)] enum FeatureStatus { Default, @@ -82,13 +78,11 @@ macro_rules! declare_features { )+) => { /// Unstable language features that are being implemented or being /// considered for acceptance (stabilization) or removal. - pub const UNSTABLE_FEATURES: &[UnstableFeature] = &[ - $(UnstableFeature { - feature: Feature { - name: sym::$feature, - since: $ver, - issue: to_nonzero($issue), - }, + pub const UNSTABLE_FEATURES: &[Feature] = &[ + $(Feature { + name: sym::$feature, + since: $ver, + issue: to_nonzero($issue), }),+ ]; diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 68b16a129102..52dd336313ad 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -117,7 +117,7 @@ impl<'tcx> HashStable> for rustc_feature::Features { // FIXME: why do we hash something that is a compile-time constant? for feature in rustc_feature::UNSTABLE_FEATURES.iter() { - feature.feature.name.hash_stable(hcx, hasher); + feature.name.hash_stable(hcx, hasher); } } } From 44638853f545632c68d9a85f85df3418ae09f248 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 23 Oct 2024 08:20:02 +0100 Subject: [PATCH 155/366] rename lang feature lists to include LANG --- compiler/rustc_expand/src/config.rs | 9 +++++---- compiler/rustc_feature/src/accepted.rs | 2 +- compiler/rustc_feature/src/lib.rs | 12 ++++++------ compiler/rustc_feature/src/removed.rs | 2 +- compiler/rustc_feature/src/unstable.rs | 2 +- compiler/rustc_passes/src/stability.rs | 6 +++--- compiler/rustc_query_system/src/ich/impls_syntax.rs | 2 +- 7 files changed, 18 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index af27077f2428..5bd9e2fbcb9b 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -11,7 +11,8 @@ use rustc_ast::{ use rustc_attr as attr; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_feature::{ - ACCEPTED_FEATURES, AttributeSafety, Features, REMOVED_FEATURES, UNSTABLE_FEATURES, + ACCEPTED_LANG_FEATURES, AttributeSafety, Features, REMOVED_LANG_FEATURES, + UNSTABLE_LANG_FEATURES, }; use rustc_lint_defs::BuiltinLintDiag; use rustc_parse::validate_attr; @@ -77,7 +78,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - }; // If the enabled feature has been removed, issue an error. - if let Some(f) = REMOVED_FEATURES.iter().find(|f| name == f.feature.name) { + if let Some(f) = REMOVED_LANG_FEATURES.iter().find(|f| name == f.feature.name) { sess.dcx().emit_err(FeatureRemoved { span: mi.span(), reason: f.reason.map(|reason| FeatureRemovedReason { reason }), @@ -86,7 +87,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - } // If the enabled feature is stable, record it. - if let Some(f) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) { + if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| name == f.name) { let since = Some(Symbol::intern(f.since)); features.set_enabled_lang_feature(name, mi.span(), since); continue; @@ -103,7 +104,7 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - } // If the enabled feature is unstable, record it. - if UNSTABLE_FEATURES.iter().find(|f| name == f.name).is_some() { + if UNSTABLE_LANG_FEATURES.iter().find(|f| name == f.name).is_some() { // When the ICE comes from core, alloc or std (approximation of the standard // library), there's a chance that the person hitting the ICE may be using // -Zbuild-std or similar with an untested target. The bug is probably in the diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 534458046945..4f71bdaca1b1 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -9,7 +9,7 @@ macro_rules! declare_features { $(#[doc = $doc:tt])* (accepted, $feature:ident, $ver:expr, $issue:expr), )+) => { /// Formerly unstable features that have now been accepted (stabilized). - pub const ACCEPTED_FEATURES: &[Feature] = &[ + pub const ACCEPTED_LANG_FEATURES: &[Feature] = &[ $(Feature { name: sym::$feature, since: $ver, diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index 7c4996c1412b..216793485e55 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -94,13 +94,13 @@ impl UnstableFeatures { fn find_lang_feature_issue(feature: Symbol) -> Option> { // Search in all the feature lists. - if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| f.name == feature) { + if let Some(f) = UNSTABLE_LANG_FEATURES.iter().find(|f| f.name == feature) { return f.issue; } - if let Some(f) = ACCEPTED_FEATURES.iter().find(|f| f.name == feature) { + if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature) { return f.issue; } - if let Some(f) = REMOVED_FEATURES.iter().find(|f| f.feature.name == feature) { + if let Some(f) = REMOVED_LANG_FEATURES.iter().find(|f| f.feature.name == feature) { return f.feature.issue; } panic!("feature `{feature}` is not declared anywhere"); @@ -127,12 +127,12 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option { /// Formerly unstable features that have now been removed. - pub const REMOVED_FEATURES: &[RemovedFeature] = &[ + pub const REMOVED_LANG_FEATURES: &[RemovedFeature] = &[ $(RemovedFeature { feature: Feature { name: sym::$feature, diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 9c6de079e2fa..8f4c208f1fbb 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -78,7 +78,7 @@ macro_rules! declare_features { )+) => { /// Unstable language features that are being implemented or being /// considered for acceptance (stabilization) or removal. - pub const UNSTABLE_FEATURES: &[Feature] = &[ + pub const UNSTABLE_LANG_FEATURES: &[Feature] = &[ $(Feature { name: sym::$feature, since: $ver, diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 1bbb0caa58d3..a176b2bb1ad4 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -10,7 +10,7 @@ use rustc_attr::{ }; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet}; -use rustc_feature::ACCEPTED_FEATURES; +use rustc_feature::ACCEPTED_LANG_FEATURES; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId}; @@ -248,7 +248,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } if let Stability { level: Unstable { .. }, feature } = stab { - if ACCEPTED_FEATURES.iter().find(|f| f.name == feature).is_some() { + if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { self.tcx .dcx() .emit_err(errors::UnstableAttrForAlreadyStableFeature { span, item_sp }); @@ -261,7 +261,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } if let Some(ConstStability { level: Unstable { .. }, feature, .. }) = const_stab { - if ACCEPTED_FEATURES.iter().find(|f| f.name == feature).is_some() { + if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { self.tcx.dcx().emit_err(errors::UnstableAttrForAlreadyStableFeature { span: const_span.unwrap(), // If const_stab contains Some(..), same is true for const_span item_sp, diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 52dd336313ad..29a28b10a068 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -116,7 +116,7 @@ impl<'tcx> HashStable> for rustc_feature::Features { self.enabled_lib_features().hash_stable(hcx, hasher); // FIXME: why do we hash something that is a compile-time constant? - for feature in rustc_feature::UNSTABLE_FEATURES.iter() { + for feature in rustc_feature::UNSTABLE_LANG_FEATURES.iter() { feature.name.hash_stable(hcx, hasher); } } From 4fdc63ce384ff42a8f3b12e6a93891bea3c8ffd1 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 10:24:58 +0200 Subject: [PATCH 156/366] Don't emit edits for postfix adjustment hints --- .../crates/ide/src/inlay_hints/adjustment.rs | 51 ++++++++++--------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs index 8f239f6029b7..0e0d50b1f35d 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs @@ -104,6 +104,7 @@ pub(super) fn hints( }; let iter: &mut dyn Iterator = iter.as_mut().either(|it| it as _, |it| it as _); + let mut allow_edit = !postfix; for Adjustment { source, target, kind } in iter { if source == target { cov_mark::hit!(same_type_adjustment); @@ -113,6 +114,7 @@ pub(super) fn hints( // FIXME: Add some nicer tooltips to each of these let (text, coercion) = match kind { Adjust::NeverToAny if config.adjustment_hints == AdjustmentHints::Always => { + allow_edit = false; ("", "never to any") } Adjust::Deref(None) => ("*", "dereference"), @@ -133,6 +135,7 @@ pub(super) fn hints( // some of these could be represented via `as` casts, but that's not too nice and // handling everything as a prefix expr makes the `(` and `)` insertion easier Adjust::Pointer(cast) if config.adjustment_hints == AdjustmentHints::Always => { + allow_edit = false; match cast { PointerCast::ReifyFnPointer => { ("", "fn item to fn pointer") @@ -179,30 +182,32 @@ pub(super) fn hints( if pre.is_none() && post.is_none() { return None; } - let edit = { - let mut b = TextEditBuilder::default(); - if let Some(pre) = &pre { - b.insert( - pre.range.start(), - pre.label.parts.iter().map(|part| &*part.text).collect::(), - ); + if allow_edit { + let edit = { + let mut b = TextEditBuilder::default(); + if let Some(pre) = &pre { + b.insert( + pre.range.start(), + pre.label.parts.iter().map(|part| &*part.text).collect::(), + ); + } + if let Some(post) = &post { + b.insert( + post.range.end(), + post.label.parts.iter().map(|part| &*part.text).collect::(), + ); + } + b.finish() + }; + match (&mut pre, &mut post) { + (Some(pre), Some(post)) => { + pre.text_edit = Some(edit.clone()); + post.text_edit = Some(edit); + } + (Some(pre), None) => pre.text_edit = Some(edit), + (None, Some(post)) => post.text_edit = Some(edit), + (None, None) => (), } - if let Some(post) = &post { - b.insert( - post.range.end(), - post.label.parts.iter().map(|part| &*part.text).collect::(), - ); - } - b.finish() - }; - match (&mut pre, &mut post) { - (Some(pre), Some(post)) => { - pre.text_edit = Some(edit.clone()); - post.text_edit = Some(edit); - } - (Some(pre), None) => pre.text_edit = Some(edit), - (None, Some(post)) => post.text_edit = Some(edit), - (None, None) => (), } acc.extend(pre); acc.extend(post); From 1b5921641a39e28d97549ced449476c1d325f0ec Mon Sep 17 00:00:00 2001 From: guliwa Date: Sun, 29 Sep 2024 22:09:56 +0000 Subject: [PATCH 157/366] Refactor change detection for rustdoc and download-rustc --- src/bootstrap/src/core/build_steps/tool.rs | 29 ++--------- src/bootstrap/src/core/config/config.rs | 58 +++++++--------------- 2 files changed, 22 insertions(+), 65 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 50f71e167db9..bb837eb81379 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1,8 +1,6 @@ use std::path::PathBuf; use std::{env, fs}; -use build_helper::git::get_closest_merge_commit; - use crate::core::build_steps::compile; use crate::core::build_steps::toolstate::ToolState; use crate::core::builder; @@ -10,7 +8,7 @@ use crate::core::builder::{Builder, Cargo as CargoCommand, RunConfig, ShouldRun, use crate::core::config::TargetSelection; use crate::utils::channel::GitInfo; use crate::utils::exec::{BootstrapCommand, command}; -use crate::utils::helpers::{add_dylib_path, exe, git, t}; +use crate::utils::helpers::{add_dylib_path, exe, t}; use crate::{Compiler, Kind, Mode, gha}; #[derive(Debug, Clone, Hash, PartialEq, Eq)] @@ -596,28 +594,11 @@ impl Step for Rustdoc { && target_compiler.stage > 0 && builder.rust_info().is_managed_git_subrepository() { - let commit = get_closest_merge_commit( - Some(&builder.config.src), - &builder.config.git_config(), - &[], - ) - .unwrap(); + let files_to_track = &["src/librustdoc", "src/tools/rustdoc"]; - let librustdoc_src = builder.config.src.join("src/librustdoc"); - let rustdoc_src = builder.config.src.join("src/tools/rustdoc"); - - // FIXME: The change detection logic here is quite similar to `Config::download_ci_rustc_commit`. - // It would be better to unify them. - let has_changes = !git(Some(&builder.config.src)) - .allow_failure() - .run_always() - .args(["diff-index", "--quiet", &commit]) - .arg("--") - .arg(librustdoc_src) - .arg(rustdoc_src) - .run(builder); - - if !has_changes { + // Check if unchanged + if builder.config.last_modified_commit(files_to_track, "download-rustc", true).is_some() + { let precompiled_rustdoc = builder .config .ci_rustc_dir() diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index aeb81b146382..9466b046a656 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -2754,25 +2754,25 @@ impl Config { } }; - let files_to_track = &[ - self.src.join("compiler"), - self.src.join("library"), - self.src.join("src/version"), - self.src.join("src/stage0"), - self.src.join("src/ci/channel"), - ]; + let files_to_track = + &["compiler", "library", "src/version", "src/stage0", "src/ci/channel"]; // Look for a version to compare to based on the current commit. // Only commits merged by bors will have CI artifacts. - let commit = - get_closest_merge_commit(Some(&self.src), &self.git_config(), files_to_track).unwrap(); - if commit.is_empty() { - println!("ERROR: could not find commit hash for downloading rustc"); - println!("HELP: maybe your repository history is too shallow?"); - println!("HELP: consider disabling `download-rustc`"); - println!("HELP: or fetch enough history to include one upstream commit"); - crate::exit!(1); - } + let commit = match self.last_modified_commit(files_to_track, "download-rustc", if_unchanged) + { + Some(commit) => commit, + None => { + if if_unchanged { + return None; + } + println!("ERROR: could not find commit hash for downloading rustc"); + println!("HELP: maybe your repository history is too shallow?"); + println!("HELP: consider disabling `download-rustc`"); + println!("HELP: or fetch enough history to include one upstream commit"); + crate::exit!(1); + } + }; if CiEnv::is_ci() && { let head_sha = @@ -2787,31 +2787,7 @@ impl Config { return None; } - // Warn if there were changes to the compiler or standard library since the ancestor commit. - let has_changes = !t!(helpers::git(Some(&self.src)) - .args(["diff-index", "--quiet", &commit]) - .arg("--") - .args(files_to_track) - .as_command_mut() - .status()) - .success(); - if has_changes { - if if_unchanged { - if self.is_verbose() { - println!( - "WARNING: saw changes to compiler/ or library/ since {commit}; \ - ignoring `download-rustc`" - ); - } - return None; - } - println!( - "WARNING: `download-rustc` is enabled, but there are changes to \ - compiler/ or library/" - ); - } - - Some(commit.to_string()) + Some(commit) } fn parse_download_ci_llvm( From 2eb7e0d3702f90d684a15b18af00f37e6ab05644 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Wed, 23 Oct 2024 09:31:43 +0000 Subject: [PATCH 158/366] CI: rfl: use rust-next temporary commit Commit c95bbb59a9b22f9b838b15d28319185c1c884329 within rust-next contains some changes required to be compatible with upcoming arbitraty self types work. Roll RFL CI forward to the latest rust-next to include that work. Related: https://github.com/rust-lang/rust/pull/130225 https://github.com/rust-lang/rust/issues/44874 --- src/ci/docker/scripts/rfl-build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ci/docker/scripts/rfl-build.sh b/src/ci/docker/scripts/rfl-build.sh index 27dbfc6040ce..f07515f7784f 100755 --- a/src/ci/docker/scripts/rfl-build.sh +++ b/src/ci/docker/scripts/rfl-build.sh @@ -2,7 +2,7 @@ set -euo pipefail -LINUX_VERSION=v6.12-rc2 +LINUX_VERSION=28e848386b92645f93b9f2fdba5882c3ca7fb3e2 # Build rustc, rustdoc, cargo, clippy-driver and rustfmt ../x.py build --stage 2 library rustdoc clippy rustfmt From ecdc2441b6a96603dd7188652adf86e06c2dc513 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Wed, 23 Oct 2024 02:45:24 -0700 Subject: [PATCH 159/366] "innermost", "outermost", "leftmost", and "rightmost" don't need hyphens These are all standard dictionary words and don't require hyphenation. --- compiler/rustc_codegen_gcc/src/type_of.rs | 2 +- compiler/rustc_codegen_llvm/src/type_of.rs | 2 +- compiler/rustc_codegen_ssa/src/base.rs | 2 +- compiler/rustc_errors/src/emitter.rs | 8 ++--- compiler/rustc_expand/messages.ftl | 2 +- compiler/rustc_expand/src/mbe/metavar_expr.rs | 4 +-- compiler/rustc_expand/src/mbe/transcribe.rs | 2 +- compiler/rustc_hir_typeck/src/upvar.rs | 2 +- compiler/rustc_mir_build/src/build/scope.rs | 8 ++--- .../rustc_mir_dataflow/src/value_analysis.rs | 2 +- compiler/rustc_parse/src/lexer/diagnostics.rs | 2 +- library/alloc/src/collections/btree/append.rs | 2 +- library/alloc/src/collections/btree/fix.rs | 2 +- library/alloc/src/collections/btree/node.rs | 4 +-- library/core/src/iter/adapters/mod.rs | 2 +- src/doc/rustc/src/symbol-mangling/v0.md | 2 +- .../count-and-length-are-distinct.rs | 34 +++++++++---------- .../rfc-3086-metavar-expr/syntax-errors.rs | 4 +-- .../syntax-errors.stderr | 4 +-- 19 files changed, 45 insertions(+), 45 deletions(-) diff --git a/compiler/rustc_codegen_gcc/src/type_of.rs b/compiler/rustc_codegen_gcc/src/type_of.rs index 183e9ddf8bf9..db874afe1ab9 100644 --- a/compiler/rustc_codegen_gcc/src/type_of.rs +++ b/compiler/rustc_codegen_gcc/src/type_of.rs @@ -197,7 +197,7 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`. /// If the type is an unsized struct, the regular layout is generated, - /// with the inner-most trailing unsized field using the "minimal unit" + /// with the innermost trailing unsized field using the "minimal unit" /// of that field's type - this is useful for taking the address of /// that field and ensuring the struct has the right alignment. fn gcc_type<'gcc>(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc> { diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 1af666f818bb..6be4c3f034f1 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -191,7 +191,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`. /// If the type is an unsized struct, the regular layout is generated, - /// with the inner-most trailing unsized field using the "minimal unit" + /// with the innermost trailing unsized field using the "minimal unit" /// of that field's type - this is useful for taking the address of /// that field and ensuring the struct has the right alignment. fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type { diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index f3d9a7d37e6c..a726ee73aaa2 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -888,7 +888,7 @@ impl CrateInfo { // below. // // In order to get this left-to-right dependency ordering, we use the reverse - // postorder of all crates putting the leaves at the right-most positions. + // postorder of all crates putting the leaves at the rightmost positions. let mut compiler_builtins = None; let mut used_crates: Vec<_> = tcx .postorder_cnums(()) diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 1adb6b9dcfee..0ccc71ae06c4 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -58,9 +58,9 @@ impl HumanReadableErrorType { struct Margin { /// The available whitespace in the left that can be consumed when centering. pub whitespace_left: usize, - /// The column of the beginning of left-most span. + /// The column of the beginning of leftmost span. pub span_left: usize, - /// The column of the end of right-most span. + /// The column of the end of rightmost span. pub span_right: usize, /// The beginning of the line to be displayed. pub computed_left: usize, @@ -128,7 +128,7 @@ impl Margin { } else { 0 }; - // We want to show as much as possible, max_line_len is the right-most boundary for the + // We want to show as much as possible, max_line_len is the rightmost boundary for the // relevant code. self.computed_right = max(max_line_len, self.computed_left); @@ -685,7 +685,7 @@ impl HumanEmitter { buffer.puts(line_offset, code_offset, "...", Style::LineNumber); } if margin.was_cut_right(line_len) { - // We have stripped some code after the right-most span end, make it clear we did so. + // We have stripped some code after the rightmost span end, make it clear we did so. buffer.puts(line_offset, code_offset + taken - 3, "...", Style::LineNumber); } buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber); diff --git a/compiler/rustc_expand/messages.ftl b/compiler/rustc_expand/messages.ftl index 57bac9d09d5e..fcf3352bfc59 100644 --- a/compiler/rustc_expand/messages.ftl +++ b/compiler/rustc_expand/messages.ftl @@ -25,7 +25,7 @@ expand_collapse_debuginfo_illegal = illegal value for attribute #[collapse_debuginfo(no|external|yes)] expand_count_repetition_misplaced = - `count` can not be placed inside the inner-most repetition + `count` can not be placed inside the innermost repetition expand_crate_name_in_cfg_attr = `crate_name` within an `#![cfg_attr]` attribute is forbidden diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index c4ba98f581e4..810a5d30c7ec 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -23,11 +23,11 @@ pub(crate) enum MetaVarExpr { /// Ignore a meta-variable for repetition without expansion. Ignore(Ident), - /// The index of the repetition at a particular depth, where 0 is the inner-most + /// The index of the repetition at a particular depth, where 0 is the innermost /// repetition. The `usize` is the depth. Index(usize), - /// The length of the repetition at a particular depth, where 0 is the inner-most + /// The length of the repetition at a particular depth, where 0 is the innermost /// repetition. The `usize` is the depth. Len(usize), } diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index fb6fe0bb1d77..34811ca2b356 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -570,7 +570,7 @@ fn lockstep_iter_size( } } -/// Used solely by the `count` meta-variable expression, counts the outer-most repetitions at a +/// Used solely by the `count` meta-variable expression, counts the outermost repetitions at a /// given optional nested depth. /// /// For example, a macro parameter of `$( { $( $foo:ident ),* } )*` called with `{ a, b } { c }`: diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 63cf483aa227..308e7f98f424 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -2457,7 +2457,7 @@ fn truncate_capture_for_optimization( ) -> (Place<'_>, ty::UpvarCapture) { let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not)); - // Find the right-most deref (if any). All the projections that come after this + // Find the rightmost deref (if any). All the projections that come after this // are fields or other "in-place pointer adjustments"; these refer therefore to // data owned by whatever pointer is being dereferenced here. let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind); diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index dfc82f705a81..a7e56b8f589b 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -1048,8 +1048,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // | +------------|outer_scope cache|--+ | // +------------------------------|middle_scope cache|------+ // - // Now, a new, inner-most scope is added along with a new drop into - // both inner-most and outer-most scopes: + // Now, a new, innermost scope is added along with a new drop into + // both innermost and outermost scopes: // // +------------------------------------------------------------+ // | +----------------------------------+ | @@ -1061,11 +1061,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // +----=----------------|invalid middle_scope cache|-----------+ // // If, when adding `drop(new)` we do not invalidate the cached blocks for both - // outer_scope and middle_scope, then, when building drops for the inner (right-most) + // outer_scope and middle_scope, then, when building drops for the inner (rightmost) // scope, the old, cached blocks, without `drop(new)` will get used, producing the // wrong results. // - // Note that this code iterates scopes from the inner-most to the outer-most, + // Note that this code iterates scopes from the innermost to the outermost, // invalidating caches of each scope visited. This way bare minimum of the // caches gets invalidated. i.e., if a new drop is added into the middle scope, the // cache of outer scope stays intact. diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index faee40faa3f5..d0f62bd82d17 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -1177,7 +1177,7 @@ struct PlaceInfo<'tcx> { /// The projection used to go from parent to this node (only None for root). proj_elem: Option, - /// The left-most child. + /// The leftmost child. first_child: Option, /// Index of the sibling to the right of this node. diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs index 41108c91f2eb..e1f19beb53ae 100644 --- a/compiler/rustc_parse/src/lexer/diagnostics.rs +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -85,7 +85,7 @@ pub(super) fn report_suspicious_mismatch_block( } } - // Find the inner-most span candidate for final report + // Find the innermost span candidate for final report let candidate_span = matched_spans.into_iter().rev().find(|&(_, same_ident)| !same_ident).map(|(span, _)| span); diff --git a/library/alloc/src/collections/btree/append.rs b/library/alloc/src/collections/btree/append.rs index 47372938fbed..d137d2721ee4 100644 --- a/library/alloc/src/collections/btree/append.rs +++ b/library/alloc/src/collections/btree/append.rs @@ -79,7 +79,7 @@ impl Root { } open_node.push(key, value, right_tree); - // Go down to the right-most leaf again. + // Go down to the rightmost leaf again. cur_node = open_node.forget_type().last_leaf_edge().into_node(); } diff --git a/library/alloc/src/collections/btree/fix.rs b/library/alloc/src/collections/btree/fix.rs index 95fb52b7f77b..09edea3555ad 100644 --- a/library/alloc/src/collections/btree/fix.rs +++ b/library/alloc/src/collections/btree/fix.rs @@ -102,7 +102,7 @@ impl Root { pub fn fix_right_border_of_plentiful(&mut self) { let mut cur_node = self.borrow_mut(); while let Internal(internal) = cur_node.force() { - // Check if right-most child is underfull. + // Check if rightmost child is underfull. let mut last_kv = internal.last_kv().consider_for_balancing(); debug_assert!(last_kv.left_child_len() >= MIN_LEN * 2); let right_child_len = last_kv.right_child_len(); diff --git a/library/alloc/src/collections/btree/node.rs b/library/alloc/src/collections/btree/node.rs index 5c513d34fc9d..2a853ef42162 100644 --- a/library/alloc/src/collections/btree/node.rs +++ b/library/alloc/src/collections/btree/node.rs @@ -1521,7 +1521,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { right_node.val_area_mut(..count - 1), ); - // Move the left-most stolen pair to the parent. + // Move the leftmost stolen pair to the parent. let k = left_node.key_area_mut(new_left_len).assume_init_read(); let v = left_node.val_area_mut(new_left_len).assume_init_read(); let (k, v) = self.parent.replace_kv(k, v); @@ -1570,7 +1570,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { // Move leaf data. { - // Move the right-most stolen pair to the parent. + // Move the rightmost stolen pair to the parent. let k = right_node.key_area_mut(count - 1).assume_init_read(); let v = right_node.val_area_mut(count - 1).assume_init_read(); let (k, v) = self.parent.replace_kv(k, v); diff --git a/library/core/src/iter/adapters/mod.rs b/library/core/src/iter/adapters/mod.rs index 6d30f350337a..2a0ef0189d16 100644 --- a/library/core/src/iter/adapters/mod.rs +++ b/library/core/src/iter/adapters/mod.rs @@ -71,7 +71,7 @@ pub use self::{ /// this can be useful for specializing [`FromIterator`] implementations or recovering the /// remaining elements after an iterator has been partially exhausted. /// -/// Note that implementations do not necessarily have to provide access to the inner-most +/// Note that implementations do not necessarily have to provide access to the innermost /// source of a pipeline. A stateful intermediate adapter might eagerly evaluate a part /// of the pipeline and expose its internal storage as source. /// diff --git a/src/doc/rustc/src/symbol-mangling/v0.md b/src/doc/rustc/src/symbol-mangling/v0.md index 6329e878c5c8..109942518fc9 100644 --- a/src/doc/rustc/src/symbol-mangling/v0.md +++ b/src/doc/rustc/src/symbol-mangling/v0.md @@ -1208,7 +1208,7 @@ The compiler has some latitude in how an entity is encoded as long as the symbol * Named functions, methods, and statics shall be represented by a *[path]* production. -* Paths should be rooted at the inner-most entity that can act as a path root. +* Paths should be rooted at the innermost entity that can act as a path root. Roots can be crate-ids, inherent impls, trait impls, and (for items within default methods) trait definitions. * The compiler is free to choose disambiguation indices and namespace tags from diff --git a/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs b/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs index 131d4166de04..8ca453273cd8 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs @@ -6,9 +6,9 @@ fn main() { macro_rules! one_nested_count_and_len { ( $( [ $( $l:literal ),* ] ),* ) => { [ - // outer-most repetition + // outermost repetition $( - // inner-most repetition + // innermost repetition $( ${ignore($l)} ${index()}, ${len()}, )* @@ -23,34 +23,34 @@ fn main() { [ // # ["foo"] - // ## inner-most repetition (first iteration) + // ## innermost repetition (first iteration) // - // `index` is 0 because this is the first inner-most iteration. - // `len` is 1 because there is only one inner-most repetition, "foo". + // `index` is 0 because this is the first innermost iteration. + // `len` is 1 because there is only one innermost repetition, "foo". 0, 1, - // ## outer-most repetition (first iteration) + // ## outermost repetition (first iteration) // // `count` is 1 because of "foo", i,e, `$l` has only one repetition, - // `index` is 0 because this is the first outer-most iteration. - // `len` is 2 because there are 2 outer-most repetitions, ["foo"] and ["bar", "baz"] + // `index` is 0 because this is the first outermost iteration. + // `len` is 2 because there are 2 outermost repetitions, ["foo"] and ["bar", "baz"] 1, 0, 2, // # ["bar", "baz"] - // ## inner-most repetition (first iteration) + // ## innermost repetition (first iteration) // - // `index` is 0 because this is the first inner-most iteration + // `index` is 0 because this is the first innermost iteration // `len` is 2 because there are repetitions, "bar" and "baz" 0, 2, - // ## inner-most repetition (second iteration) + // ## innermost repetition (second iteration) // - // `index` is 1 because this is the second inner-most iteration + // `index` is 1 because this is the second innermost iteration // `len` is 2 because there are repetitions, "bar" and "baz" 1, 2, - // ## outer-most repetition (second iteration) + // ## outermost repetition (second iteration) // // `count` is 2 because of "bar" and "baz", i,e, `$l` has two repetitions, - // `index` is 1 because this is the second outer-most iteration - // `len` is 2 because there are 2 outer-most repetitions, ["foo"] and ["bar", "baz"] + // `index` is 1 because this is the second outermost iteration + // `len` is 2 because there are 2 outermost repetitions, ["foo"] and ["bar", "baz"] 2, 1, 2, // # last count @@ -61,7 +61,7 @@ fn main() { // Based on the above explanation, the following macros should be straightforward - // Grouped from the outer-most to the inner-most + // Grouped from the outermost to the innermost macro_rules! three_nested_count { ( $( { $( [ $( ( $( $i:ident )* ) )* ] )* } )* ) => { &[ @@ -156,7 +156,7 @@ fn main() { ][..] ); - // Grouped from the outer-most to the inner-most + // Grouped from the outermost to the innermost macro_rules! three_nested_len { ( $( { $( [ $( ( $( $i:ident )* ) )* ] )* } )* ) => { &[ diff --git a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs index 1eda5f5bb6bc..78cede92526b 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs @@ -10,12 +10,12 @@ macro_rules! curly__no_rhs_dollar__round { macro_rules! curly__no_rhs_dollar__no_round { ( $i:ident ) => { ${ count($i) } }; - //~^ ERROR `count` can not be placed inside the inner-most repetition + //~^ ERROR `count` can not be placed inside the innermost repetition } macro_rules! curly__rhs_dollar__no_round { ( $i:ident ) => { ${ count($i) } }; - //~^ ERROR `count` can not be placed inside the inner-most repetition + //~^ ERROR `count` can not be placed inside the innermost repetition } #[rustfmt::skip] // autoformatters can break a few of the error traces diff --git a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr index 2c44ad2e0a4a..ce7694ecb1da 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr +++ b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr @@ -196,13 +196,13 @@ error: expected identifier or string literal LL | ( $( $i:ident ),* ) => { ${ {} } }; | ^^ -error: `count` can not be placed inside the inner-most repetition +error: `count` can not be placed inside the innermost repetition --> $DIR/syntax-errors.rs:12:24 | LL | ( $i:ident ) => { ${ count($i) } }; | ^^^^^^^^^^^^^ -error: `count` can not be placed inside the inner-most repetition +error: `count` can not be placed inside the innermost repetition --> $DIR/syntax-errors.rs:17:24 | LL | ( $i:ident ) => { ${ count($i) } }; From ac3db41b3904ec0b5738b48533183cd8d8bba3fb Mon Sep 17 00:00:00 2001 From: usamoi Date: Wed, 23 Oct 2024 18:09:17 +0800 Subject: [PATCH 160/366] fix dyn incompatible hint message --- src/tools/rust-analyzer/crates/ide/src/hover/render.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/render.rs b/src/tools/rust-analyzer/crates/ide/src/hover/render.rs index 01fa316d5fce..a31b14dbd3e3 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/render.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/render.rs @@ -1042,7 +1042,7 @@ fn render_dyn_compatibility( } DynCompatibilityViolation::HasNonCompatibleSuperTrait(super_trait) => { let name = hir::Trait::from(super_trait).name(db); - format_to!(buf, "has a object unsafe supertrait `{}`", name.as_str()); + format_to!(buf, "has a dyn incompatible supertrait `{}`", name.as_str()); } } } From 6570a6fe92002d352fecbaad0176c678030c6d2e Mon Sep 17 00:00:00 2001 From: DianQK Date: Tue, 22 Oct 2024 10:46:10 +0800 Subject: [PATCH 161/366] Add a test case for #131164 --- .../rust-lld-link-script-provide/main.rs | 7 +++++++ .../rust-lld-link-script-provide/rmake.rs | 18 ++++++++++++++++++ .../rust-lld-link-script-provide/script.t | 1 + 3 files changed, 26 insertions(+) create mode 100644 tests/run-make/rust-lld-link-script-provide/main.rs create mode 100644 tests/run-make/rust-lld-link-script-provide/rmake.rs create mode 100644 tests/run-make/rust-lld-link-script-provide/script.t diff --git a/tests/run-make/rust-lld-link-script-provide/main.rs b/tests/run-make/rust-lld-link-script-provide/main.rs new file mode 100644 index 000000000000..5c19e7a4bbf6 --- /dev/null +++ b/tests/run-make/rust-lld-link-script-provide/main.rs @@ -0,0 +1,7 @@ +#[no_mangle] +fn foo() {} + +#[no_mangle] +fn bar() {} + +fn main() {} diff --git a/tests/run-make/rust-lld-link-script-provide/rmake.rs b/tests/run-make/rust-lld-link-script-provide/rmake.rs new file mode 100644 index 000000000000..e78a411bc15f --- /dev/null +++ b/tests/run-make/rust-lld-link-script-provide/rmake.rs @@ -0,0 +1,18 @@ +// This test ensures that the “symbol not found” error does not occur +// when the symbols in the `PROVIDE` of the link script can be eliminated. +// This is a regression test for #131164. + +//@ needs-rust-lld +//@ only-x86_64-unknown-linux-gnu + +use run_make_support::rustc; + +fn main() { + rustc() + .input("main.rs") + .arg("-Zlinker-features=+lld") + .arg("-Clink-self-contained=+linker") + .arg("-Zunstable-options") + .link_arg("-Tscript.t") + .run(); +} diff --git a/tests/run-make/rust-lld-link-script-provide/script.t b/tests/run-make/rust-lld-link-script-provide/script.t new file mode 100644 index 000000000000..4c4c6ddfc36b --- /dev/null +++ b/tests/run-make/rust-lld-link-script-provide/script.t @@ -0,0 +1 @@ +PROVIDE(foo = bar); From f4c8ff33de0cd9ba5b465356c00908d817cb5c0e Mon Sep 17 00:00:00 2001 From: July Tikhonov Date: Wed, 23 Oct 2024 19:17:36 +0600 Subject: [PATCH 162/366] fix documentation of ptr::dangling() function --- library/core/src/ptr/mod.rs | 4 ++-- library/core/src/ptr/non_null.rs | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index f769b5158771..ea185f0fbe58 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -602,7 +602,7 @@ pub const fn without_provenance(addr: usize) -> *const T { unsafe { mem::transmute(addr) } } -/// Creates a new pointer that is dangling, but well-aligned. +/// Creates a new pointer that is dangling, but non-null and well-aligned. /// /// This is useful for initializing types which lazily allocate, like /// `Vec::new` does. @@ -645,7 +645,7 @@ pub const fn without_provenance_mut(addr: usize) -> *mut T { unsafe { mem::transmute(addr) } } -/// Creates a new pointer that is dangling, but well-aligned. +/// Creates a new pointer that is dangling, but non-null and well-aligned. /// /// This is useful for initializing types which lazily allocate, like /// `Vec::new` does. diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index d91bbe1a5a19..d80e1e700aa4 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -107,9 +107,7 @@ impl NonNull { #[must_use] #[inline] pub const fn dangling() -> Self { - // SAFETY: mem::align_of() returns a non-zero usize which is then casted - // to a *mut T. Therefore, `ptr` is not null and the conditions for - // calling new_unchecked() are respected. + // SAFETY: ptr::dangling_mut() returns a non-null well-aligned pointer. unsafe { let ptr = crate::ptr::dangling_mut::(); NonNull::new_unchecked(ptr) From b515bbfb850febc9282a1b2a72ed31076a23c04a Mon Sep 17 00:00:00 2001 From: July Tikhonov Date: Wed, 23 Oct 2024 19:37:51 +0600 Subject: [PATCH 163/366] fix a typo in documentation of pointer::sub_ptr() --- library/core/src/ptr/const_ptr.rs | 2 +- library/core/src/ptr/mut_ptr.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 9ee0fb5948e1..facf38894d3b 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -704,7 +704,7 @@ impl *const T { /// but it provides slightly more information to the optimizer, which can /// sometimes allow it to optimize slightly better with some backends. /// - /// This method can be though of as recovering the `count` that was passed + /// This method can be thought of as recovering the `count` that was passed /// to [`add`](#method.add) (or, with the parameters in the other order, /// to [`sub`](#method.sub)). The following are all equivalent, assuming /// that their safety preconditions are met: diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 782934fc311d..031939cf0d51 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -867,7 +867,7 @@ impl *mut T { /// but it provides slightly more information to the optimizer, which can /// sometimes allow it to optimize slightly better with some backends. /// - /// This method can be though of as recovering the `count` that was passed + /// This method can be thought of as recovering the `count` that was passed /// to [`add`](#method.add) (or, with the parameters in the other order, /// to [`sub`](#method.sub)). The following are all equivalent, assuming /// that their safety preconditions are met: From 21d95fb7b29b108de74af101b9ebdf5e401088d5 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 20 Oct 2024 18:17:11 +0000 Subject: [PATCH 164/366] More compare_impl_item simplifications --- .../src/check/compare_impl_item.rs | 125 ++++++++---------- compiler/rustc_middle/src/ty/generics.rs | 4 +- compiler/rustc_type_ir/src/binder.rs | 42 +++++- 3 files changed, 95 insertions(+), 76 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 610311f40582..fc5ec31cda80 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -43,14 +43,13 @@ mod refine; /// - `impl_m`: type of the method we are checking /// - `trait_m`: the method in the trait /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation +#[instrument(level = "debug", skip(tcx))] pub(super) fn compare_impl_method<'tcx>( tcx: TyCtxt<'tcx>, impl_m: ty::AssocItem, trait_m: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) { - debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref); - let _: Result<_, ErrorGuaranteed> = try { check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?; compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?; @@ -167,8 +166,6 @@ fn compare_method_predicate_entailment<'tcx>( trait_m: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let trait_to_impl_args = impl_trait_ref.args; - // This node-id should be used for the `body_id` field on each // `ObligationCause` (and the `FnCtxt`). // @@ -183,13 +180,13 @@ fn compare_method_predicate_entailment<'tcx>( kind: impl_m.kind, }); - // Create mapping from impl to placeholder. - let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id); - - // Create mapping from trait to placeholder. - let trait_to_placeholder_args = - impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args); - debug!("compare_impl_method: trait_to_placeholder_args={:?}", trait_to_placeholder_args); + // Create mapping from trait method to impl method. + let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto( + tcx, + impl_m.container_id(tcx), + impl_trait_ref.args, + ); + debug!(?trait_to_impl_args); let impl_m_predicates = tcx.predicates_of(impl_m.def_id); let trait_m_predicates = tcx.predicates_of(trait_m.def_id); @@ -204,28 +201,22 @@ fn compare_method_predicate_entailment<'tcx>( let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap()); let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates; hybrid_preds.extend( - trait_m_predicates - .instantiate_own(tcx, trait_to_placeholder_args) - .map(|(predicate, _)| predicate), + trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate), ); - // Construct trait parameter environment and then shift it into the placeholder viewpoint. - // The key step here is to update the caller_bounds's predicates to be - // the new hybrid bounds we computed. let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id); let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause); + debug!(caller_bounds=?param_env.caller_bounds()); let infcx = &tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new_with_diagnostics(infcx); - debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds()); - // Create obligations for each predicate declared by the impl // definition in the context of the hybrid param-env. This makes // sure that the impl's method's where clauses are not more // restrictive than the trait's method (and the impl itself). - let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_args); + let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity(); for (predicate, span) in impl_m_own_bounds { let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); let predicate = ocx.normalize(&normalize_cause, param_env, predicate); @@ -252,7 +243,6 @@ fn compare_method_predicate_entailment<'tcx>( // any associated types appearing in the fn arguments or return // type. - // Compute placeholder form of impl and trait method tys. let mut wf_tys = FxIndexSet::default(); let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars( @@ -263,9 +253,9 @@ fn compare_method_predicate_entailment<'tcx>( let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id); let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig); - debug!("compare_impl_method: impl_fty={:?}", impl_sig); + debug!(?impl_sig); - let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_placeholder_args); + let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args); let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig); // Next, add all inputs and output as well-formed tys. Importantly, @@ -276,9 +266,7 @@ fn compare_method_predicate_entailment<'tcx>( // We also have to add the normalized trait signature // as we don't normalize during implied bounds computation. wf_tys.extend(trait_sig.inputs_and_output.iter()); - let trait_fty = Ty::new_fn_ptr(tcx, ty::Binder::dummy(trait_sig)); - - debug!("compare_impl_method: trait_fty={:?}", trait_fty); + debug!(?trait_sig); // FIXME: We'd want to keep more accurate spans than "the method signature" when // processing the comparison between the trait and impl fn, but we sadly lose them @@ -451,8 +439,6 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( // just so we don't ICE during instantiation later. check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?; - let trait_to_impl_args = impl_trait_ref.args; - let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id); let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span(); let cause = @@ -462,18 +448,18 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( kind: impl_m.kind, }); - // Create mapping from impl to placeholder. - let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id); - - // Create mapping from trait to placeholder. - let trait_to_placeholder_args = - impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args); + // Create mapping from trait to impl (i.e. impl trait header + impl method identity args). + let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto( + tcx, + impl_m.container_id(tcx), + impl_trait_ref.args, + ); let hybrid_preds = tcx .predicates_of(impl_m.container_id(tcx)) .instantiate_identity(tcx) .into_iter() - .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_placeholder_args)) + .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args)) .map(|(clause, _)| clause); let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error( @@ -507,7 +493,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( .instantiate_binder_with_fresh_vars( return_span, infer::HigherRankedType, - tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_placeholder_args), + tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args), ) .fold_with(&mut collector); @@ -701,7 +687,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( // Also, we only need to account for a difference in trait and impl args, // since we previously enforce that the trait method and impl method have the // same generics. - let num_trait_args = trait_to_impl_args.len(); + let num_trait_args = impl_trait_ref.args.len(); let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len(); let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions { tcx, @@ -1037,12 +1023,7 @@ fn check_region_bounds_on_impl_item<'tcx>( let trait_generics = tcx.generics_of(trait_m.def_id); let trait_params = trait_generics.own_counts().lifetimes; - debug!( - "check_region_bounds_on_impl_item: \ - trait_generics={:?} \ - impl_generics={:?}", - trait_generics, impl_generics - ); + debug!(?trait_generics, ?impl_generics); // Must have same number of early-bound lifetime parameters. // Unfortunately, if the user screws up the bounds, then this @@ -1706,8 +1687,7 @@ pub(super) fn compare_impl_const_raw( let trait_const_item = tcx.associated_item(trait_const_item_def); let impl_trait_ref = tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().instantiate_identity(); - - debug!("compare_impl_const(impl_trait_ref={:?})", impl_trait_ref); + debug!(?impl_trait_ref); compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?; compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?; @@ -1718,6 +1698,7 @@ pub(super) fn compare_impl_const_raw( /// The equivalent of [compare_method_predicate_entailment], but for associated constants /// instead of associated functions. // FIXME(generic_const_items): If possible extract the common parts of `compare_{type,const}_predicate_entailment`. +#[instrument(level = "debug", skip(tcx))] fn compare_const_predicate_entailment<'tcx>( tcx: TyCtxt<'tcx>, impl_ct: ty::AssocItem, @@ -1732,13 +1713,14 @@ fn compare_const_predicate_entailment<'tcx>( // because we shouldn't really have to deal with lifetimes or // predicates. In fact some of this should probably be put into // shared functions because of DRY violations... - let impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id); - let trait_to_impl_args = - impl_args.rebase_onto(tcx, impl_ct.container_id(tcx), impl_trait_ref.args); + let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto( + tcx, + impl_ct.container_id(tcx), + impl_trait_ref.args, + ); // Create a parameter environment that represents the implementation's - // method. - // Compute placeholder form of impl and trait const tys. + // associated const. let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity(); let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args); @@ -1772,7 +1754,7 @@ fn compare_const_predicate_entailment<'tcx>( let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new_with_diagnostics(&infcx); - let impl_ct_own_bounds = impl_ct_predicates.instantiate_own(tcx, impl_args); + let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity(); for (predicate, span) in impl_ct_own_bounds { let cause = ObligationCause::misc(span, impl_ct_def_id); let predicate = ocx.normalize(&cause, param_env, predicate); @@ -1783,20 +1765,15 @@ fn compare_const_predicate_entailment<'tcx>( // There is no "body" here, so just pass dummy id. let impl_ty = ocx.normalize(&cause, param_env, impl_ty); - - debug!("compare_const_impl: impl_ty={:?}", impl_ty); + debug!(?impl_ty); let trait_ty = ocx.normalize(&cause, param_env, trait_ty); - - debug!("compare_const_impl: trait_ty={:?}", trait_ty); + debug!(?trait_ty); let err = ocx.sup(&cause, param_env, trait_ty, impl_ty); if let Err(terr) = err { - debug!( - "checking associated const for compatibility: impl ty {:?}, trait ty {:?}", - impl_ty, trait_ty - ); + debug!(?impl_ty, ?trait_ty); // Locate the Span containing just the type of the offending impl let (ty, _) = tcx.hir().expect_impl_item(impl_ct_def_id).expect_const(); @@ -1841,14 +1818,13 @@ fn compare_const_predicate_entailment<'tcx>( ocx.resolve_regions_and_report_errors(impl_ct_def_id, &outlives_env) } +#[instrument(level = "debug", skip(tcx))] pub(super) fn compare_impl_ty<'tcx>( tcx: TyCtxt<'tcx>, impl_ty: ty::AssocItem, trait_ty: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) { - debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref); - let _: Result<(), ErrorGuaranteed> = try { compare_number_of_generics(tcx, impl_ty, trait_ty, false)?; compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?; @@ -1860,20 +1836,23 @@ pub(super) fn compare_impl_ty<'tcx>( /// The equivalent of [compare_method_predicate_entailment], but for associated types /// instead of associated functions. +#[instrument(level = "debug", skip(tcx))] fn compare_type_predicate_entailment<'tcx>( tcx: TyCtxt<'tcx>, impl_ty: ty::AssocItem, trait_ty: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id); - let trait_to_impl_args = - impl_args.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.args); + let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto( + tcx, + impl_ty.container_id(tcx), + impl_trait_ref.args, + ); let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id); let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id); - let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_args); + let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity(); if impl_ty_own_bounds.len() == 0 { // Nothing to check. return Ok(()); @@ -1883,7 +1862,7 @@ fn compare_type_predicate_entailment<'tcx>( // `ObligationCause` (and the `FnCtxt`). This is what // `regionck_item` expects. let impl_ty_def_id = impl_ty.def_id.expect_local(); - debug!("compare_type_predicate_entailment: trait_to_impl_args={:?}", trait_to_impl_args); + debug!(?trait_to_impl_args); // The predicates declared by the impl definition, the trait and the // associated type in the trait are assumed. @@ -1894,18 +1873,18 @@ fn compare_type_predicate_entailment<'tcx>( .instantiate_own(tcx, trait_to_impl_args) .map(|(predicate, _)| predicate), ); - - debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds); + debug!(?hybrid_preds); let impl_ty_span = tcx.def_span(impl_ty_def_id); let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id); + let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause); + debug!(caller_bounds=?param_env.caller_bounds()); + let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new_with_diagnostics(&infcx); - debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds()); - for (predicate, span) in impl_ty_own_bounds { let cause = ObligationCause::misc(span, impl_ty_def_id); let predicate = ocx.normalize(&cause, param_env, predicate); @@ -2005,11 +1984,11 @@ pub(super) fn check_type_bounds<'tcx>( .explicit_item_bounds(trait_ty.def_id) .iter_instantiated_copied(tcx, rebased_args) .map(|(concrete_ty_bound, span)| { - debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound); + debug!(?concrete_ty_bound); traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound) }) .collect(); - debug!("check_type_bounds: item_bounds={:?}", obligations); + debug!(item_bounds=?obligations); // Normalize predicates with the assumption that the GAT may always normalize // to its definition type. This should be the param-env we use to *prove* the @@ -2028,7 +2007,7 @@ pub(super) fn check_type_bounds<'tcx>( } else { ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate) }; - debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate); + debug!(?normalized_predicate); obligation.predicate = normalized_predicate; ocx.register_obligation(obligation); diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index 660686f4aa28..63534a3d0174 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -395,7 +395,9 @@ impl<'tcx> GenericPredicates<'tcx> { EarlyBinder::bind(self.predicates).iter_instantiated_copied(tcx, args) } - pub fn instantiate_own_identity(self) -> impl Iterator, Span)> { + pub fn instantiate_own_identity( + self, + ) -> impl Iterator, Span)> + DoubleEndedIterator + ExactSizeIterator { EarlyBinder::bind(self.predicates).iter_identity_copied() } diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index f20beb797500..c06a578d8ec7 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -496,8 +496,8 @@ where /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity), /// but on an iterator of values that deref to a `TypeFoldable`. - pub fn iter_identity_copied(self) -> impl Iterator::Target> { - self.value.into_iter().map(|v| *v) + pub fn iter_identity_copied(self) -> IterIdentityCopied { + IterIdentityCopied { it: self.value.into_iter() } } } @@ -546,6 +546,44 @@ where { } +pub struct IterIdentityCopied { + it: Iter::IntoIter, +} + +impl Iterator for IterIdentityCopied +where + Iter::Item: Deref, + ::Target: Copy, +{ + type Item = ::Target; + + fn next(&mut self) -> Option { + self.it.next().map(|i| *i) + } + + fn size_hint(&self) -> (usize, Option) { + self.it.size_hint() + } +} + +impl DoubleEndedIterator for IterIdentityCopied +where + Iter::IntoIter: DoubleEndedIterator, + Iter::Item: Deref, + ::Target: Copy, +{ + fn next_back(&mut self) -> Option { + self.it.next_back().map(|i| *i) + } +} + +impl ExactSizeIterator for IterIdentityCopied +where + Iter::IntoIter: ExactSizeIterator, + Iter::Item: Deref, + ::Target: Copy, +{ +} pub struct EarlyBinderIter { t: T, _tcx: PhantomData, From 33f27d135e2d537b72adf8e67958a69e4fb81236 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Wed, 23 Oct 2024 09:57:57 -0700 Subject: [PATCH 165/366] fix: Handle missing time offsets gracefully The tracing_subscribe docs state that missing offsets likely mean that we're in a multithreaded context: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/time/struct.OffsetTime.html#method.local_rfc_3339 We're not in a multithreaded context at this point, but some platforms (e.g. OpenBSD) still don't have time offsets available. Since this is only a rust-analyzer debugging convenience, just use system time logging in this situation. Fixes #18384 --- .../rust-analyzer/src/tracing/config.rs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/config.rs index 5ab2dc2b67a2..02ae4186ab69 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/tracing/config.rs @@ -58,14 +58,22 @@ where let writer = self.writer; let ra_fmt_layer = tracing_subscriber::fmt::layer() - .with_timer( - time::OffsetTime::local_rfc_3339() - .expect("Could not get local offset, make sure you're on the main thread"), - ) .with_target(false) .with_ansi(false) - .with_writer(writer) - .with_filter(targets_filter); + .with_writer(writer); + + let ra_fmt_layer = match time::OffsetTime::local_rfc_3339() { + Ok(timer) => { + // If we can get the time offset, format logs with the timezone. + ra_fmt_layer.with_timer(timer).boxed() + } + Err(_) => { + // Use system time if we can't get the time offset. This should + // never happen on Linux, but can happen on e.g. OpenBSD. + ra_fmt_layer.boxed() + } + } + .with_filter(targets_filter); let chalk_layer = match self.chalk_filter { Some(chalk_filter) => { From 03048096f6c4ed89ee2a5d6c86cd8268d0bc61bd Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 23 Oct 2024 19:44:17 +0200 Subject: [PATCH 166/366] stop hashing compile-time constant --- compiler/rustc_query_system/src/ich/impls_syntax.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 29a28b10a068..0665401df8e8 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -111,13 +111,8 @@ impl<'a> HashStable> for SourceFile { impl<'tcx> HashStable> for rustc_feature::Features { fn hash_stable(&self, hcx: &mut StableHashingContext<'tcx>, hasher: &mut StableHasher) { // Unfortunately we cannot exhaustively list fields here, since the - // struct is macro generated. + // struct has private fields (to ensure its invariant is maintained) self.enabled_lang_features().hash_stable(hcx, hasher); self.enabled_lib_features().hash_stable(hcx, hasher); - - // FIXME: why do we hash something that is a compile-time constant? - for feature in rustc_feature::UNSTABLE_LANG_FEATURES.iter() { - feature.name.hash_stable(hcx, hasher); - } } } From 0689b2139fa90aeb6f42930ee783cc2f322cd265 Mon Sep 17 00:00:00 2001 From: Ding Xiang Fei Date: Mon, 21 Oct 2024 04:47:02 +0800 Subject: [PATCH 167/366] stabilize shorter-tail-lifetimes --- compiler/rustc_feature/src/accepted.rs | 2 ++ compiler/rustc_feature/src/unstable.rs | 2 -- .../rustc_hir_analysis/src/check/region.rs | 4 +--- .../rustc_lint/src/tail_expr_drop_order.rs | 23 +++++++++---------- tests/ui/drop/drop_order.rs | 12 ++++++++++ .../drop/lint-tail-expr-drop-order-gated.rs | 12 ++++------ tests/ui/drop/lint-tail-expr-drop-order.rs | 4 +--- .../ui/drop/lint-tail-expr-drop-order.stderr | 8 +++---- ...xpr-drop-order-negative.edition2024.stderr | 2 +- .../ui/drop/tail-expr-drop-order-negative.rs | 2 -- tests/ui/drop/tail-expr-drop-order.rs | 1 - .../refcell-in-tail-expr.edition2021.stderr | 2 +- tests/ui/lifetimes/refcell-in-tail-expr.rs | 2 -- ...rter-tail-expr-lifetime.edition2021.stderr | 2 +- .../lifetimes/shorter-tail-expr-lifetime.rs | 2 -- .../ui/lifetimes/tail-expr-in-nested-expr.rs | 2 -- .../lifetimes/tail-expr-in-nested-expr.stderr | 2 +- .../ui/lifetimes/tail-expr-lock-poisoning.rs | 1 - 18 files changed, 39 insertions(+), 46 deletions(-) diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 4f71bdaca1b1..ac922f184dd8 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -364,6 +364,8 @@ declare_features! ( (accepted, self_in_typedefs, "1.32.0", Some(49303)), /// Allows `Self` struct constructor (RFC 2302). (accepted, self_struct_ctor, "1.32.0", Some(51994)), + /// Shortern the tail expression lifetime + (accepted, shorter_tail_lifetimes, "CURRENT_RUSTC_VERSION", Some(123739)), /// Allows using subslice patterns, `[a, .., b]` and `[a, xs @ .., b]`. (accepted, slice_patterns, "1.42.0", Some(62254)), /// Allows use of `&foo[a..b]` as a slicing syntax. diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 8f4c208f1fbb..152eb2edb050 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -571,8 +571,6 @@ declare_features! ( (unstable, rust_cold_cc, "1.63.0", Some(97544)), /// Allows use of x86 SHA512, SM3 and SM4 target-features and intrinsics (unstable, sha512_sm_x86, "1.82.0", Some(126624)), - /// Shortern the tail expression lifetime - (unstable, shorter_tail_lifetimes, "1.79.0", Some(123739)), /// Allows the use of SIMD types in functions declared in `extern` blocks. (unstable, simd_ffi, "1.0.0", Some(27731)), /// Allows specialization of implementations (RFC 1210). diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 312fb16c93aa..bfa088fdefc9 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -167,9 +167,7 @@ fn resolve_block<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, blk: &'tcx h } } if let Some(tail_expr) = blk.expr { - if visitor.tcx.features().shorter_tail_lifetimes() - && blk.span.edition().at_least_rust_2024() - { + if blk.span.edition().at_least_rust_2024() { visitor.terminating_scopes.insert(tail_expr.hir_id.local_id); } visitor.visit_expr(tail_expr); diff --git a/compiler/rustc_lint/src/tail_expr_drop_order.rs b/compiler/rustc_lint/src/tail_expr_drop_order.rs index 04f769bf5517..89763059877c 100644 --- a/compiler/rustc_lint/src/tail_expr_drop_order.rs +++ b/compiler/rustc_lint/src/tail_expr_drop_order.rs @@ -14,15 +14,14 @@ use rustc_span::edition::Edition; use crate::{LateContext, LateLintPass}; declare_lint! { - /// The `tail_expr_drop_order` lint looks for those values generated at the tail expression location, that of type - /// with a significant `Drop` implementation, such as locks. - /// In case there are also local variables of type with significant `Drop` implementation as well, - /// this lint warns you of a potential transposition in the drop order. - /// Your discretion on the new drop order introduced by Edition 2024 is required. + /// The `tail_expr_drop_order` lint looks for those values generated at the tail expression location, + /// that runs a custom `Drop` destructor. + /// Some of them may be dropped earlier in Edition 2024 that they used to in Edition 2021 and prior. + /// This lint detects those cases and provides you information on those values and their custom destructor implementations. + /// Your discretion on this information is required. /// /// ### Example - /// ```rust,edition2024 - /// #![feature(shorter_tail_lifetimes)] + /// ```rust,edition2021 /// #![warn(tail_expr_drop_order)] /// struct Droppy(i32); /// impl Droppy { @@ -37,12 +36,12 @@ declare_lint! { /// println!("loud drop {}", self.0); /// } /// } - /// fn edition_2024() -> i32 { + /// fn edition_2021() -> i32 { /// let another_droppy = Droppy(0); /// Droppy(1).get() /// } /// fn main() { - /// edition_2024(); + /// edition_2021(); /// } /// ``` /// @@ -137,7 +136,7 @@ impl<'tcx> LateLintPass<'tcx> for TailExprDropOrder { _: Span, def_id: rustc_span::def_id::LocalDefId, ) { - if cx.tcx.sess.at_least_rust_2024() && cx.tcx.features().shorter_tail_lifetimes() { + if !body.value.span.edition().at_least_rust_2024() { Self::check_fn_or_closure(cx, fn_kind, body, def_id); } } @@ -185,8 +184,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LintVisitor<'a, 'tcx> { impl<'a, 'tcx> LintVisitor<'a, 'tcx> { fn check_block_inner(&mut self, block: &Block<'tcx>) { - if !block.span.at_least_rust_2024() { - // We only lint for Edition 2024 onwards + if block.span.at_least_rust_2024() { + // We only lint up to Edition 2021 return; } let Some(tail_expr) = block.expr else { return }; diff --git a/tests/ui/drop/drop_order.rs b/tests/ui/drop/drop_order.rs index cf0625380074..29b68d666fc6 100644 --- a/tests/ui/drop/drop_order.rs +++ b/tests/ui/drop/drop_order.rs @@ -105,6 +105,7 @@ impl DropOrderCollector { () => self.print(10), } + #[cfg(edition2021)] match { match self.option_loud_drop(14) { _ => { @@ -115,6 +116,17 @@ impl DropOrderCollector { } { _ => self.print(12), } + #[cfg(edition2024)] + match { + match self.option_loud_drop(12) { + _ => { + self.print(11); + self.option_loud_drop(14) + } + } + } { + _ => self.print(13), + } match { loop { diff --git a/tests/ui/drop/lint-tail-expr-drop-order-gated.rs b/tests/ui/drop/lint-tail-expr-drop-order-gated.rs index b22e72bcfad2..fde542c756f2 100644 --- a/tests/ui/drop/lint-tail-expr-drop-order-gated.rs +++ b/tests/ui/drop/lint-tail-expr-drop-order-gated.rs @@ -1,15 +1,11 @@ -// This test ensures that `tail_expr_drop_order` does not activate in case Edition 2024 is not used -// or the feature gate `shorter_tail_lifetimes` is disabled. +// This test is to demonstrate that the lint is gated behind Edition and +// is triggered only for Edition 2021 and before. -//@ revisions: neither no_feature_gate edition_less_than_2024 //@ check-pass -//@ [neither] edition: 2021 -//@ [no_feature_gate] compile-flags: -Z unstable-options -//@ [no_feature_gate] edition: 2024 -//@ [edition_less_than_2024] edition: 2021 +//@ edition: 2024 +//@ compile-flags: -Z unstable-options #![deny(tail_expr_drop_order)] -#![cfg_attr(edition_less_than_2024, feature(shorter_tail_lifetimes))] struct LoudDropper; impl Drop for LoudDropper { diff --git a/tests/ui/drop/lint-tail-expr-drop-order.rs b/tests/ui/drop/lint-tail-expr-drop-order.rs index 0aa0ef026101..d61abae51870 100644 --- a/tests/ui/drop/lint-tail-expr-drop-order.rs +++ b/tests/ui/drop/lint-tail-expr-drop-order.rs @@ -1,12 +1,10 @@ -//@ compile-flags: -Z unstable-options -//@ edition: 2024 +//@ edition: 2021 // Edition 2024 lint for change in drop order at tail expression // This lint is to capture potential change in program semantics // due to implementation of RFC 3606 #![deny(tail_expr_drop_order)] -#![feature(shorter_tail_lifetimes)] struct LoudDropper; impl Drop for LoudDropper { diff --git a/tests/ui/drop/lint-tail-expr-drop-order.stderr b/tests/ui/drop/lint-tail-expr-drop-order.stderr index 630f0a80f092..6775c4ce6d15 100644 --- a/tests/ui/drop/lint-tail-expr-drop-order.stderr +++ b/tests/ui/drop/lint-tail-expr-drop-order.stderr @@ -1,5 +1,5 @@ error: these values and local bindings have significant drop implementation that will have a different drop order from that of Edition 2021 - --> $DIR/lint-tail-expr-drop-order.rs:29:15 + --> $DIR/lint-tail-expr-drop-order.rs:27:15 | LL | let x = LoudDropper; | - these values have significant drop implementation and will observe changes in drop order under Edition 2024 @@ -10,13 +10,13 @@ LL | x.get() + LoudDropper.get() = warning: this changes meaning in Rust 2024 = note: for more information, see issue #123739 note: the lint level is defined here - --> $DIR/lint-tail-expr-drop-order.rs:8:9 + --> $DIR/lint-tail-expr-drop-order.rs:7:9 | LL | #![deny(tail_expr_drop_order)] | ^^^^^^^^^^^^^^^^^^^^ error: these values and local bindings have significant drop implementation that will have a different drop order from that of Edition 2021 - --> $DIR/lint-tail-expr-drop-order.rs:36:23 + --> $DIR/lint-tail-expr-drop-order.rs:34:23 | LL | let x = LoudDropper; | - these values have significant drop implementation and will observe changes in drop order under Edition 2024 @@ -27,7 +27,7 @@ LL | move || x.get() + LoudDropper.get() = note: for more information, see issue #123739 error: these values and local bindings have significant drop implementation that will have a different drop order from that of Edition 2021 - --> $DIR/lint-tail-expr-drop-order.rs:65:19 + --> $DIR/lint-tail-expr-drop-order.rs:63:19 | LL | let x = LoudDropper; | - these values have significant drop implementation and will observe changes in drop order under Edition 2024 diff --git a/tests/ui/drop/tail-expr-drop-order-negative.edition2024.stderr b/tests/ui/drop/tail-expr-drop-order-negative.edition2024.stderr index 75fc34e409b5..bcce796570e2 100644 --- a/tests/ui/drop/tail-expr-drop-order-negative.edition2024.stderr +++ b/tests/ui/drop/tail-expr-drop-order-negative.edition2024.stderr @@ -1,5 +1,5 @@ error[E0716]: temporary value dropped while borrowed - --> $DIR/tail-expr-drop-order-negative.rs:11:15 + --> $DIR/tail-expr-drop-order-negative.rs:9:15 | LL | x.replace(std::cell::RefCell::new(123).borrow()).is_some() | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement diff --git a/tests/ui/drop/tail-expr-drop-order-negative.rs b/tests/ui/drop/tail-expr-drop-order-negative.rs index c570b3a1ee23..5ad04d0a67ef 100644 --- a/tests/ui/drop/tail-expr-drop-order-negative.rs +++ b/tests/ui/drop/tail-expr-drop-order-negative.rs @@ -3,8 +3,6 @@ //@ [edition2024] edition: 2024 //@ [edition2021] check-pass -#![feature(shorter_tail_lifetimes)] - fn why_would_you_do_this() -> bool { let mut x = None; // Make a temporary `RefCell` and put a `Ref` that borrows it in `x`. diff --git a/tests/ui/drop/tail-expr-drop-order.rs b/tests/ui/drop/tail-expr-drop-order.rs index 5d87f980b156..80968b823f9a 100644 --- a/tests/ui/drop/tail-expr-drop-order.rs +++ b/tests/ui/drop/tail-expr-drop-order.rs @@ -4,7 +4,6 @@ //@ edition: 2024 //@ run-pass -#![feature(shorter_tail_lifetimes)] #![allow(unused_imports)] #![allow(dead_code)] #![allow(unused_variables)] diff --git a/tests/ui/lifetimes/refcell-in-tail-expr.edition2021.stderr b/tests/ui/lifetimes/refcell-in-tail-expr.edition2021.stderr index 858be42d5409..157a1c5e09b0 100644 --- a/tests/ui/lifetimes/refcell-in-tail-expr.edition2021.stderr +++ b/tests/ui/lifetimes/refcell-in-tail-expr.edition2021.stderr @@ -1,5 +1,5 @@ error[E0597]: `cell` does not live long enough - --> $DIR/refcell-in-tail-expr.rs:12:27 + --> $DIR/refcell-in-tail-expr.rs:10:27 | LL | let cell = std::cell::RefCell::new(0u8); | ---- binding `cell` declared here diff --git a/tests/ui/lifetimes/refcell-in-tail-expr.rs b/tests/ui/lifetimes/refcell-in-tail-expr.rs index b1814c1e3271..595e951f3731 100644 --- a/tests/ui/lifetimes/refcell-in-tail-expr.rs +++ b/tests/ui/lifetimes/refcell-in-tail-expr.rs @@ -4,8 +4,6 @@ //@ [edition2024] compile-flags: -Zunstable-options //@ [edition2024] check-pass -#![cfg_attr(edition2024, feature(shorter_tail_lifetimes))] - fn main() { let cell = std::cell::RefCell::new(0u8); diff --git a/tests/ui/lifetimes/shorter-tail-expr-lifetime.edition2021.stderr b/tests/ui/lifetimes/shorter-tail-expr-lifetime.edition2021.stderr index ad28ae2f80d6..3c074c5c3a2c 100644 --- a/tests/ui/lifetimes/shorter-tail-expr-lifetime.edition2021.stderr +++ b/tests/ui/lifetimes/shorter-tail-expr-lifetime.edition2021.stderr @@ -1,5 +1,5 @@ error[E0597]: `c` does not live long enough - --> $DIR/shorter-tail-expr-lifetime.rs:10:5 + --> $DIR/shorter-tail-expr-lifetime.rs:8:5 | LL | let c = std::cell::RefCell::new(".."); | - binding `c` declared here diff --git a/tests/ui/lifetimes/shorter-tail-expr-lifetime.rs b/tests/ui/lifetimes/shorter-tail-expr-lifetime.rs index 0392b6c6d9ad..4195a8b6c32b 100644 --- a/tests/ui/lifetimes/shorter-tail-expr-lifetime.rs +++ b/tests/ui/lifetimes/shorter-tail-expr-lifetime.rs @@ -3,8 +3,6 @@ //@ [edition2024] edition: 2024 //@ [edition2024] run-pass -#![cfg_attr(edition2024, feature(shorter_tail_lifetimes))] - fn f() -> usize { let c = std::cell::RefCell::new(".."); c.borrow().len() //[edition2021]~ ERROR: `c` does not live long enough diff --git a/tests/ui/lifetimes/tail-expr-in-nested-expr.rs b/tests/ui/lifetimes/tail-expr-in-nested-expr.rs index a8989f22f4b5..2ac97aff2b09 100644 --- a/tests/ui/lifetimes/tail-expr-in-nested-expr.rs +++ b/tests/ui/lifetimes/tail-expr-in-nested-expr.rs @@ -1,8 +1,6 @@ //@ edition: 2024 //@ compile-flags: -Zunstable-options -#![feature(shorter_tail_lifetimes)] - fn main() { let _ = { String::new().as_str() }.len(); //~^ ERROR temporary value dropped while borrowed diff --git a/tests/ui/lifetimes/tail-expr-in-nested-expr.stderr b/tests/ui/lifetimes/tail-expr-in-nested-expr.stderr index f699d184bdb1..96e88eaca922 100644 --- a/tests/ui/lifetimes/tail-expr-in-nested-expr.stderr +++ b/tests/ui/lifetimes/tail-expr-in-nested-expr.stderr @@ -1,5 +1,5 @@ error[E0716]: temporary value dropped while borrowed - --> $DIR/tail-expr-in-nested-expr.rs:7:15 + --> $DIR/tail-expr-in-nested-expr.rs:5:15 | LL | let _ = { String::new().as_str() }.len(); | ^^^^^^^^^^^^^--------- diff --git a/tests/ui/lifetimes/tail-expr-lock-poisoning.rs b/tests/ui/lifetimes/tail-expr-lock-poisoning.rs index cdfd35304b44..ec74596a08da 100644 --- a/tests/ui/lifetimes/tail-expr-lock-poisoning.rs +++ b/tests/ui/lifetimes/tail-expr-lock-poisoning.rs @@ -4,7 +4,6 @@ //@ [edition2024] edition: 2024 //@ run-pass //@ needs-unwind -#![cfg_attr(edition2024, feature(shorter_tail_lifetimes))] use std::sync::Mutex; From d7f137ea7a0e648cc545cfb55b2f4b6658ff9cae Mon Sep 17 00:00:00 2001 From: Jason Boatman Date: Wed, 23 Oct 2024 12:57:11 -0500 Subject: [PATCH 168/366] Fix checking for `false` `labelDetailsSupport` value. --- .../rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs index 3b19284f2411..871cde58dce0 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs @@ -212,7 +212,8 @@ impl ClientCapabilities { .label_details_support .as_ref() })() - .is_some() + .copied() + .unwrap_or_default() } fn completion_item(&self) -> Option { From 2e3091d66ccd2e474ac63beaace3813c0f085cfa Mon Sep 17 00:00:00 2001 From: clubby789 Date: Sat, 19 Oct 2024 14:02:40 +0000 Subject: [PATCH 169/366] Don't allow test revisions that conflict with built in cfgs --- src/tools/compiletest/src/common.rs | 18 ++++++++++++++++++ src/tools/compiletest/src/lib.rs | 1 + src/tools/compiletest/src/runtest.rs | 3 +++ tests/ui/lint/lint-missing-doc-expect.rs | 4 ++-- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index ff059940f7cc..3e6423e474ad 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -376,6 +376,7 @@ pub struct Config { pub only_modified: bool, pub target_cfgs: OnceLock, + pub builtin_cfg_names: OnceLock>, pub nocapture: bool, @@ -440,6 +441,11 @@ impl Config { self.target_cfg().panic == PanicStrategy::Unwind } + /// Get the list of builtin, 'well known' cfg names + pub fn builtin_cfg_names(&self) -> &HashSet { + self.builtin_cfg_names.get_or_init(|| builtin_cfg_names(self)) + } + pub fn has_threads(&self) -> bool { // Wasm targets don't have threads unless `-threads` is in the target // name, such as `wasm32-wasip1-threads`. @@ -651,6 +657,18 @@ pub enum Endian { Big, } +fn builtin_cfg_names(config: &Config) -> HashSet { + rustc_output( + config, + &["--print=check-cfg", "-Zunstable-options", "--check-cfg=cfg()"], + Default::default(), + ) + .lines() + .map(|l| if let Some((name, _)) = l.split_once('=') { name.to_string() } else { l.to_string() }) + .chain(std::iter::once(String::from("test"))) + .collect() +} + fn rustc_output(config: &Config, args: &[&str], envs: HashMap) -> String { let mut command = Command::new(&config.rustc_path); add_dylib_path(&mut command, iter::once(&config.compile_lib_path)); diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index 7d6ede9bcdac..54ba98ffcc4b 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -356,6 +356,7 @@ pub fn parse_config(args: Vec) -> Config { force_rerun: matches.opt_present("force-rerun"), target_cfgs: OnceLock::new(), + builtin_cfg_names: OnceLock::new(), nocapture: matches.opt_present("nocapture"), diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 36c5106ddad0..fc409ba3762e 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -478,6 +478,9 @@ impl<'test> TestCx<'test> { "error: redundant cfg argument `{normalized_revision}` is already created by the revision" ); } + if self.config.builtin_cfg_names().contains(&normalized_revision) { + panic!("error: revision `{normalized_revision}` collides with a builtin cfg"); + } cmd.args(cfg_arg); } diff --git a/tests/ui/lint/lint-missing-doc-expect.rs b/tests/ui/lint/lint-missing-doc-expect.rs index 991f65003dc2..b1abf8b69620 100644 --- a/tests/ui/lint/lint-missing-doc-expect.rs +++ b/tests/ui/lint/lint-missing-doc-expect.rs @@ -1,10 +1,10 @@ // Make sure that `#[expect(missing_docs)]` is always correctly fulfilled. //@ check-pass -//@ revisions: lib bin test +//@ revisions: lib bin test_ //@ [lib]compile-flags: --crate-type lib //@ [bin]compile-flags: --crate-type bin -//@ [test]compile-flags: --test +//@ [test_]compile-flags: --test #[expect(missing_docs)] pub fn foo() {} From fd36b3a4a8168fcadecac2317e407bbd0eaeb1d2 Mon Sep 17 00:00:00 2001 From: Ding Xiang Fei Date: Sat, 5 Oct 2024 17:44:53 +0800 Subject: [PATCH 170/366] s/SmartPointer/CoerceReferent/g move derive_smart_pointer into removed set --- .../{smart_ptr.rs => coerce_pointee.rs} | 20 +-- .../rustc_builtin_macros/src/deriving/mod.rs | 2 +- compiler/rustc_builtin_macros/src/lib.rs | 2 +- compiler/rustc_feature/src/removed.rs | 2 + compiler/rustc_feature/src/unstable.rs | 4 +- compiler/rustc_passes/src/check_attr.rs | 2 +- compiler/rustc_span/src/symbol.rs | 3 +- library/core/src/marker.rs | 7 +- .../deriving/auxiliary/another-proc-macro.rs | 2 +- .../ui/deriving/built-in-proc-macro-scope.rs | 6 +- .../deriving/built-in-proc-macro-scope.stdout | 4 +- ... => coerce-pointee-bounds-issue-127647.rs} | 16 +-- ...rs => deriving-coerce-pointee-expanded.rs} | 10 +- ...> deriving-coerce-pointee-expanded.stdout} | 4 +- ...-neg.rs => deriving-coerce-pointee-neg.rs} | 94 ++++++++------ .../deriving-coerce-pointee-neg.stderr | 119 ++++++++++++++++++ ...-pointer.rs => deriving-coerce-pointee.rs} | 6 +- .../deriving-smart-pointer-neg.stderr | 119 ------------------ .../deriving/proc-macro-attribute-mixing.rs | 4 +- .../proc-macro-attribute-mixing.stdout | 4 +- .../feature-gate-derive-coerce-pointee.rs | 9 ++ .../feature-gate-derive-coerce-pointee.stderr | 23 ++++ .../feature-gate-derive-smart-pointer.rs | 9 -- .../feature-gate-derive-smart-pointer.stderr | 23 ---- 24 files changed, 257 insertions(+), 237 deletions(-) rename compiler/rustc_builtin_macros/src/deriving/{smart_ptr.rs => coerce_pointee.rs} (95%) rename tests/ui/deriving/{smart-pointer-bounds-issue-127647.rs => coerce-pointee-bounds-issue-127647.rs} (82%) rename tests/ui/deriving/{deriving-smart-pointer-expanded.rs => deriving-coerce-pointee-expanded.rs} (75%) rename tests/ui/deriving/{deriving-smart-pointer-expanded.stdout => deriving-coerce-pointee-expanded.stdout} (96%) rename tests/ui/deriving/{deriving-smart-pointer-neg.rs => deriving-coerce-pointee-neg.rs} (50%) create mode 100644 tests/ui/deriving/deriving-coerce-pointee-neg.stderr rename tests/ui/deriving/{deriving-smart-pointer.rs => deriving-coerce-pointee.rs} (90%) delete mode 100644 tests/ui/deriving/deriving-smart-pointer-neg.stderr create mode 100644 tests/ui/feature-gates/feature-gate-derive-coerce-pointee.rs create mode 100644 tests/ui/feature-gates/feature-gate-derive-coerce-pointee.stderr delete mode 100644 tests/ui/feature-gates/feature-gate-derive-smart-pointer.rs delete mode 100644 tests/ui/feature-gates/feature-gate-derive-smart-pointer.stderr diff --git a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs similarity index 95% rename from compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs rename to compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs index 731945f5cbfb..53e938ee216b 100644 --- a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs +++ b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs @@ -19,7 +19,7 @@ macro_rules! path { ($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } } -pub(crate) fn expand_deriving_smart_ptr( +pub(crate) fn expand_deriving_coerce_pointee( cx: &ExtCtxt<'_>, span: Span, _mitem: &MetaItem, @@ -41,7 +41,7 @@ pub(crate) fn expand_deriving_smart_ptr( cx.dcx() .struct_span_err( span, - "`SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]`", + "`CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]`", ) .emit(); return; @@ -54,7 +54,7 @@ pub(crate) fn expand_deriving_smart_ptr( cx.dcx() .struct_span_err( span, - "`SmartPointer` can only be derived on `struct`s with at least one field", + "`CoercePointee` can only be derived on `struct`s with at least one field", ) .emit(); return; @@ -64,7 +64,7 @@ pub(crate) fn expand_deriving_smart_ptr( cx.dcx() .struct_span_err( span, - "`SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]`", + "`CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]`", ) .emit(); return; @@ -94,10 +94,10 @@ pub(crate) fn expand_deriving_smart_ptr( .collect(); let pointee_param_idx = if type_params.is_empty() { - // `#[derive(SmartPointer)]` requires at least one generic type on the target `struct` + // `#[derive(CoercePointee)]` requires at least one generic type on the target `struct` cx.dcx().struct_span_err( span, - "`SmartPointer` can only be derived on `struct`s that are generic over at least one type", + "`CoercePointee` can only be derived on `struct`s that are generic over at least one type", ).emit(); return; } else if type_params.len() == 1 { @@ -113,7 +113,7 @@ pub(crate) fn expand_deriving_smart_ptr( (None, _) => { cx.dcx().struct_span_err( span, - "exactly one generic type parameter must be marked as #[pointee] to derive SmartPointer traits", + "exactly one generic type parameter must be marked as #[pointee] to derive CoercePointee traits", ).emit(); return; } @@ -121,7 +121,7 @@ pub(crate) fn expand_deriving_smart_ptr( cx.dcx() .struct_span_err( vec![one, another], - "only one type parameter can be marked as `#[pointee]` when deriving SmartPointer traits", + "only one type parameter can be marked as `#[pointee]` when deriving CoercePointee traits", ) .emit(); return; @@ -185,7 +185,7 @@ pub(crate) fn expand_deriving_smart_ptr( .struct_span_err( pointee_ty_ident.span, format!( - "`derive(SmartPointer)` requires {} to be marked `?Sized`", + "`derive(CoercePointee)` requires {} to be marked `?Sized`", pointee_ty_ident.name ), ) @@ -195,7 +195,7 @@ pub(crate) fn expand_deriving_smart_ptr( let arg = GenericArg::Type(s_ty.clone()); let unsize = cx.path_all(span, true, path!(span, core::marker::Unsize), vec![arg]); pointee.bounds.push(cx.trait_bound(unsize, false)); - // Drop `#[pointee]` attribute since it should not be recognized outside `derive(SmartPointer)` + // Drop `#[pointee]` attribute since it should not be recognized outside `derive(CoercePointee)` pointee.attrs.retain(|attr| !attr.has_name(sym::pointee)); } diff --git a/compiler/rustc_builtin_macros/src/deriving/mod.rs b/compiler/rustc_builtin_macros/src/deriving/mod.rs index e884c0ec7189..681fbd1651db 100644 --- a/compiler/rustc_builtin_macros/src/deriving/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/mod.rs @@ -22,12 +22,12 @@ macro path_std($($x:tt)*) { pub(crate) mod bounds; pub(crate) mod clone; +pub(crate) mod coerce_pointee; pub(crate) mod debug; pub(crate) mod decodable; pub(crate) mod default; pub(crate) mod encodable; pub(crate) mod hash; -pub(crate) mod smart_ptr; #[path = "cmp/eq.rs"] pub(crate) mod eq; diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index 377d7f542cf4..9eee92164cf1 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -133,7 +133,7 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) { PartialOrd: partial_ord::expand_deriving_partial_ord, RustcDecodable: decodable::expand_deriving_rustc_decodable, RustcEncodable: encodable::expand_deriving_rustc_encodable, - SmartPointer: smart_ptr::expand_deriving_smart_ptr, + CoercePointee: coerce_pointee::expand_deriving_coerce_pointee, } let client = proc_macro::bridge::client::Client::expand1(proc_macro::quote); diff --git a/compiler/rustc_feature/src/removed.rs b/compiler/rustc_feature/src/removed.rs index fe3a67fd6670..8d2e1e8c8041 100644 --- a/compiler/rustc_feature/src/removed.rs +++ b/compiler/rustc_feature/src/removed.rs @@ -85,6 +85,8 @@ declare_features! ( /// Allows default type parameters to influence type inference. (removed, default_type_parameter_fallback, "1.82.0", Some(27336), Some("never properly implemented; requires significant design work")), + /// Allows deriving traits as per `SmartPointer` specification + (removed, derive_smart_pointer, "1.79.0", Some(123430), Some("replaced by `CoercePointee`")), /// Allows using `#[doc(keyword = "...")]`. (removed, doc_keyword, "1.28.0", Some(51315), Some("merged into `#![feature(rustdoc_internals)]`")), diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 8f4c208f1fbb..760bcce89ec7 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -425,8 +425,8 @@ declare_features! ( (unstable, deprecated_suggestion, "1.61.0", Some(94785)), /// Allows deref patterns. (incomplete, deref_patterns, "1.79.0", Some(87121)), - /// Allows deriving `SmartPointer` traits - (unstable, derive_smart_pointer, "1.79.0", Some(123430)), + /// Allows deriving traits as per `CoercePointee` specification + (unstable, derive_coerce_pointee, "1.79.0", Some(123430)), /// Controls errors in trait implementations. (unstable, do_not_recommend, "1.67.0", Some(51992)), /// Tells rustdoc to automatically generate `#[doc(cfg(...))]`. diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 864428448238..a364ceb66285 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -262,7 +262,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::cfg_attr // need to be fixed | sym::cfi_encoding // FIXME(cfi_encoding) - | sym::pointee // FIXME(derive_smart_pointer) + | sym::pointee // FIXME(derive_coerce_pointee) | sym::omit_gdb_pretty_printer_section // FIXME(omit_gdb_pretty_printer_section) | sym::used // handled elsewhere to restrict to static items | sym::repr // handled elsewhere to restrict to type decls items diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 3ab482072b8f..e758bab0913a 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -174,6 +174,7 @@ symbols! { Center, Cleanup, Clone, + CoercePointee, CoerceUnsized, Command, ConstParamTy, @@ -315,7 +316,6 @@ symbols! { Sized, SliceIndex, SliceIter, - SmartPointer, Some, SpanCtxt, String, @@ -740,6 +740,7 @@ symbols! { deref_pure, deref_target, derive, + derive_coerce_pointee, derive_const, derive_default_enum, derive_smart_pointer, diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index aed6be4c6277..de67d7f0c89f 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -1063,10 +1063,11 @@ pub trait FnPtr: Copy + Clone { } /// Derive macro generating impls of traits related to smart pointers. -#[rustc_builtin_macro(SmartPointer, attributes(pointee))] +#[rustc_builtin_macro(CoercePointee, attributes(pointee))] #[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize)] -#[unstable(feature = "derive_smart_pointer", issue = "123430")] -pub macro SmartPointer($item:item) { +#[unstable(feature = "derive_coerce_pointee", issue = "123430")] +#[cfg(not(bootstrap))] +pub macro CoercePointee($item:item) { /* compiler built-in */ } diff --git a/tests/ui/deriving/auxiliary/another-proc-macro.rs b/tests/ui/deriving/auxiliary/another-proc-macro.rs index a05175c9de92..c992cde4066b 100644 --- a/tests/ui/deriving/auxiliary/another-proc-macro.rs +++ b/tests/ui/deriving/auxiliary/another-proc-macro.rs @@ -6,7 +6,7 @@ extern crate proc_macro; -use proc_macro::{quote, TokenStream}; +use proc_macro::{TokenStream, quote}; #[proc_macro_derive(AnotherMacro, attributes(pointee))] pub fn derive(_input: TokenStream) -> TokenStream { diff --git a/tests/ui/deriving/built-in-proc-macro-scope.rs b/tests/ui/deriving/built-in-proc-macro-scope.rs index 41c95f63b135..6c473aefc5b0 100644 --- a/tests/ui/deriving/built-in-proc-macro-scope.rs +++ b/tests/ui/deriving/built-in-proc-macro-scope.rs @@ -2,14 +2,14 @@ //@ aux-build: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded -#![feature(derive_smart_pointer)] +#![feature(derive_coerce_pointee)] #[macro_use] extern crate another_proc_macro; -use another_proc_macro::{pointee, AnotherMacro}; +use another_proc_macro::{AnotherMacro, pointee}; -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr<'a, #[pointee] T: ?Sized> { data: &'a mut T, diff --git a/tests/ui/deriving/built-in-proc-macro-scope.stdout b/tests/ui/deriving/built-in-proc-macro-scope.stdout index c649b7a9a574..07767dc229fd 100644 --- a/tests/ui/deriving/built-in-proc-macro-scope.stdout +++ b/tests/ui/deriving/built-in-proc-macro-scope.stdout @@ -4,7 +4,7 @@ //@ aux-build: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded -#![feature(derive_smart_pointer)] +#![feature(derive_coerce_pointee)] #[prelude_import] use ::std::prelude::rust_2015::*; #[macro_use] @@ -13,7 +13,7 @@ extern crate std; #[macro_use] extern crate another_proc_macro; -use another_proc_macro::{pointee, AnotherMacro}; +use another_proc_macro::{AnotherMacro, pointee}; #[repr(transparent)] pub struct Ptr<'a, #[pointee] T: ?Sized> { diff --git a/tests/ui/deriving/smart-pointer-bounds-issue-127647.rs b/tests/ui/deriving/coerce-pointee-bounds-issue-127647.rs similarity index 82% rename from tests/ui/deriving/smart-pointer-bounds-issue-127647.rs rename to tests/ui/deriving/coerce-pointee-bounds-issue-127647.rs index 4cae1b32896f..a1aabf1cb527 100644 --- a/tests/ui/deriving/smart-pointer-bounds-issue-127647.rs +++ b/tests/ui/deriving/coerce-pointee-bounds-issue-127647.rs @@ -1,8 +1,8 @@ //@ check-pass -#![feature(derive_smart_pointer)] +#![feature(derive_coerce_pointee)] -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr<'a, #[pointee] T: OnDrop + ?Sized, X> { data: &'a mut T, @@ -13,7 +13,7 @@ pub trait OnDrop { fn on_drop(&mut self); } -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr2<'a, #[pointee] T: ?Sized, X> where @@ -25,7 +25,7 @@ where pub trait MyTrait {} -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr3<'a, #[pointee] T: ?Sized, X> where @@ -35,14 +35,14 @@ where x: core::marker::PhantomData, } -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr4<'a, #[pointee] T: MyTrait + ?Sized, X> { data: &'a mut T, x: core::marker::PhantomData, } -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr5<'a, #[pointee] T: ?Sized, X> where @@ -56,7 +56,7 @@ where pub struct Ptr5Companion(core::marker::PhantomData); pub struct Ptr5Companion2; -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct Ptr6<'a, #[pointee] T: ?Sized, X: MyTrait = (), const PARAM: usize = 0> { data: &'a mut T, @@ -65,7 +65,7 @@ pub struct Ptr6<'a, #[pointee] T: ?Sized, X: MyTrait = (), const PARAM: usize // a reduced example from https://lore.kernel.org/all/20240402-linked-list-v1-1-b1c59ba7ae3b@google.com/ #[repr(transparent)] -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] pub struct ListArc<#[pointee] T, const ID: u64 = 0> where T: ListArcSafe + ?Sized, diff --git a/tests/ui/deriving/deriving-smart-pointer-expanded.rs b/tests/ui/deriving/deriving-coerce-pointee-expanded.rs similarity index 75% rename from tests/ui/deriving/deriving-smart-pointer-expanded.rs rename to tests/ui/deriving/deriving-coerce-pointee-expanded.rs index e48ad3dd4bc6..94be7031fb77 100644 --- a/tests/ui/deriving/deriving-smart-pointer-expanded.rs +++ b/tests/ui/deriving/deriving-coerce-pointee-expanded.rs @@ -1,17 +1,17 @@ //@ check-pass //@ compile-flags: -Zunpretty=expanded -#![feature(derive_smart_pointer)] -use std::marker::SmartPointer; +#![feature(derive_coerce_pointee)] +use std::marker::CoercePointee; pub trait MyTrait {} -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct MyPointer<'a, #[pointee] T: ?Sized> { ptr: &'a T, } -#[derive(core::marker::SmartPointer)] +#[derive(core::marker::CoercePointee)] #[repr(transparent)] pub struct MyPointer2<'a, Y, Z: MyTrait, #[pointee] T: ?Sized + MyTrait, X: MyTrait = ()> where @@ -21,7 +21,7 @@ where x: core::marker::PhantomData, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct MyPointerWithoutPointee<'a, T: ?Sized> { ptr: &'a T, diff --git a/tests/ui/deriving/deriving-smart-pointer-expanded.stdout b/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout similarity index 96% rename from tests/ui/deriving/deriving-smart-pointer-expanded.stdout rename to tests/ui/deriving/deriving-coerce-pointee-expanded.stdout index 68ef17f2b054..d6eaca5cba18 100644 --- a/tests/ui/deriving/deriving-smart-pointer-expanded.stdout +++ b/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout @@ -2,12 +2,12 @@ #![no_std] //@ check-pass //@ compile-flags: -Zunpretty=expanded -#![feature(derive_smart_pointer)] +#![feature(derive_coerce_pointee)] #[prelude_import] use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; -use std::marker::SmartPointer; +use std::marker::CoercePointee; pub trait MyTrait {} diff --git a/tests/ui/deriving/deriving-smart-pointer-neg.rs b/tests/ui/deriving/deriving-coerce-pointee-neg.rs similarity index 50% rename from tests/ui/deriving/deriving-smart-pointer-neg.rs rename to tests/ui/deriving/deriving-coerce-pointee-neg.rs index 41d3039236f7..deef35cdf701 100644 --- a/tests/ui/deriving/deriving-smart-pointer-neg.rs +++ b/tests/ui/deriving/deriving-coerce-pointee-neg.rs @@ -1,115 +1,131 @@ -#![feature(derive_smart_pointer, arbitrary_self_types)] +#![feature(derive_coerce_pointee, arbitrary_self_types)] extern crate core; -use std::marker::SmartPointer; +use std::marker::CoercePointee; -#[derive(SmartPointer)] -//~^ ERROR: `SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]` +#[derive(CoercePointee)] +//~^ ERROR: `CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]` enum NotStruct<'a, T: ?Sized> { Variant(&'a T), } -#[derive(SmartPointer)] -//~^ ERROR: `SmartPointer` can only be derived on `struct`s with at least one field +#[derive(CoercePointee)] +//~^ ERROR: `CoercePointee` can only be derived on `struct`s with at least one field #[repr(transparent)] struct NoField<'a, #[pointee] T: ?Sized> {} //~^ ERROR: lifetime parameter `'a` is never used //~| ERROR: type parameter `T` is never used -#[derive(SmartPointer)] -//~^ ERROR: `SmartPointer` can only be derived on `struct`s with at least one field +#[derive(CoercePointee)] +//~^ ERROR: `CoercePointee` can only be derived on `struct`s with at least one field #[repr(transparent)] struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); //~^ ERROR: lifetime parameter `'a` is never used //~| ERROR: type parameter `T` is never used -#[derive(SmartPointer)] -//~^ ERROR: `SmartPointer` can only be derived on `struct`s that are generic over at least one type +#[derive(CoercePointee)] +//~^ ERROR: `CoercePointee` can only be derived on `struct`s that are generic over at least one type #[repr(transparent)] struct NoGeneric<'a>(&'a u8); -#[derive(SmartPointer)] -//~^ ERROR: exactly one generic type parameter must be marked as #[pointee] to derive SmartPointer traits +#[derive(CoercePointee)] +//~^ ERROR: exactly one generic type parameter must be marked as #[pointee] to derive CoercePointee traits #[repr(transparent)] struct AmbiguousPointee<'a, T1: ?Sized, T2: ?Sized> { a: (&'a T1, &'a T2), } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct TooManyPointees<'a, #[pointee] A: ?Sized, #[pointee] B: ?Sized>((&'a A, &'a B)); -//~^ ERROR: only one type parameter can be marked as `#[pointee]` when deriving SmartPointer traits +//~^ ERROR: only one type parameter can be marked as `#[pointee]` when deriving CoercePointee traits -#[derive(SmartPointer)] -//~^ ERROR: `SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]` +#[derive(CoercePointee)] +//~^ ERROR: `CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]` struct NotTransparent<'a, #[pointee] T: ?Sized> { ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct NoMaybeSized<'a, #[pointee] T> { - //~^ ERROR: `derive(SmartPointer)` requires T to be marked `?Sized` + //~^ ERROR: `derive(CoercePointee)` requires T to be marked `?Sized` ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct PointeeOnField<'a, #[pointee] T: ?Sized> { #[pointee] - //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters - ptr: &'a T -} - -#[derive(SmartPointer)] -#[repr(transparent)] -struct PointeeInTypeConstBlock<'a, T: ?Sized = [u32; const { struct UhOh<#[pointee] T>(T); 10 }]> { //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] +#[repr(transparent)] +struct PointeeInTypeConstBlock< + 'a, + T: ?Sized = [u32; const { + struct UhOh<#[pointee] T>(T); + //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters + 10 + }], +> { + ptr: &'a T, +} + +#[derive(CoercePointee)] #[repr(transparent)] struct PointeeInConstConstBlock< 'a, T: ?Sized, - const V: u32 = { struct UhOh<#[pointee] T>(T); 10 }> - //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters -{ + const V: u32 = { + struct UhOh<#[pointee] T>(T); + //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters + 10 + }, +> { ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct PointeeInAnotherTypeConstBlock<'a, #[pointee] T: ?Sized> { - ptr: PointeeInConstConstBlock<'a, T, { struct UhOh<#[pointee] T>(T); 0 }> - //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters + ptr: PointeeInConstConstBlock< + 'a, + T, + { + struct UhOh<#[pointee] T>(T); + //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters + 0 + }, + >, } // However, reordering attributes should work nevertheless. #[repr(transparent)] -#[derive(SmartPointer)] -struct ThisIsAPossibleSmartPointer<'a, #[pointee] T: ?Sized> { +#[derive(CoercePointee)] +struct ThisIsAPossibleCoercePointee<'a, #[pointee] T: ?Sized> { ptr: &'a T, } // Also, these paths to Sized should work -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct StdSized<'a, #[pointee] T: ?std::marker::Sized> { ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct CoreSized<'a, #[pointee] T: ?core::marker::Sized> { ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct GlobalStdSized<'a, #[pointee] T: ?::std::marker::Sized> { ptr: &'a T, } -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct GlobalCoreSized<'a, #[pointee] T: ?::core::marker::Sized> { ptr: &'a T, diff --git a/tests/ui/deriving/deriving-coerce-pointee-neg.stderr b/tests/ui/deriving/deriving-coerce-pointee-neg.stderr new file mode 100644 index 000000000000..e590d636d0e3 --- /dev/null +++ b/tests/ui/deriving/deriving-coerce-pointee-neg.stderr @@ -0,0 +1,119 @@ +error: `CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]` + --> $DIR/deriving-coerce-pointee-neg.rs:6:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: `CoercePointee` can only be derived on `struct`s with at least one field + --> $DIR/deriving-coerce-pointee-neg.rs:12:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: `CoercePointee` can only be derived on `struct`s with at least one field + --> $DIR/deriving-coerce-pointee-neg.rs:19:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: `CoercePointee` can only be derived on `struct`s that are generic over at least one type + --> $DIR/deriving-coerce-pointee-neg.rs:26:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: exactly one generic type parameter must be marked as #[pointee] to derive CoercePointee traits + --> $DIR/deriving-coerce-pointee-neg.rs:31:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: only one type parameter can be marked as `#[pointee]` when deriving CoercePointee traits + --> $DIR/deriving-coerce-pointee-neg.rs:40:39 + | +LL | struct TooManyPointees<'a, #[pointee] A: ?Sized, #[pointee] B: ?Sized>((&'a A, &'a B)); + | ^ ^ + +error: `CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]` + --> $DIR/deriving-coerce-pointee-neg.rs:43:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: `derive(CoercePointee)` requires T to be marked `?Sized` + --> $DIR/deriving-coerce-pointee-neg.rs:51:36 + | +LL | struct NoMaybeSized<'a, #[pointee] T> { + | ^ + +error: the `#[pointee]` attribute may only be used on generic parameters + --> $DIR/deriving-coerce-pointee-neg.rs:59:5 + | +LL | #[pointee] + | ^^^^^^^^^^ + +error: the `#[pointee]` attribute may only be used on generic parameters + --> $DIR/deriving-coerce-pointee-neg.rs:69:33 + | +LL | struct UhOh<#[pointee] T>(T); + | ^^^^^^^^^^ + +error: the `#[pointee]` attribute may only be used on generic parameters + --> $DIR/deriving-coerce-pointee-neg.rs:83:21 + | +LL | struct UhOh<#[pointee] T>(T); + | ^^^^^^^^^^ + +error: the `#[pointee]` attribute may only be used on generic parameters + --> $DIR/deriving-coerce-pointee-neg.rs:98:25 + | +LL | struct UhOh<#[pointee] T>(T); + | ^^^^^^^^^^ + +error[E0392]: lifetime parameter `'a` is never used + --> $DIR/deriving-coerce-pointee-neg.rs:15:16 + | +LL | struct NoField<'a, #[pointee] T: ?Sized> {} + | ^^ unused lifetime parameter + | + = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` + +error[E0392]: type parameter `T` is never used + --> $DIR/deriving-coerce-pointee-neg.rs:15:31 + | +LL | struct NoField<'a, #[pointee] T: ?Sized> {} + | ^ unused type parameter + | + = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` + +error[E0392]: lifetime parameter `'a` is never used + --> $DIR/deriving-coerce-pointee-neg.rs:22:20 + | +LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); + | ^^ unused lifetime parameter + | + = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` + +error[E0392]: type parameter `T` is never used + --> $DIR/deriving-coerce-pointee-neg.rs:22:35 + | +LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); + | ^ unused type parameter + | + = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` + +error: aborting due to 16 previous errors + +For more information about this error, try `rustc --explain E0392`. diff --git a/tests/ui/deriving/deriving-smart-pointer.rs b/tests/ui/deriving/deriving-coerce-pointee.rs similarity index 90% rename from tests/ui/deriving/deriving-smart-pointer.rs rename to tests/ui/deriving/deriving-coerce-pointee.rs index d34a502da684..26762e4d0fac 100644 --- a/tests/ui/deriving/deriving-smart-pointer.rs +++ b/tests/ui/deriving/deriving-coerce-pointee.rs @@ -1,9 +1,9 @@ //@ run-pass -#![feature(derive_smart_pointer, arbitrary_self_types)] +#![feature(derive_coerce_pointee, arbitrary_self_types)] -use std::marker::SmartPointer; +use std::marker::CoercePointee; -#[derive(SmartPointer)] +#[derive(CoercePointee)] #[repr(transparent)] struct MyPointer<'a, #[pointee] T: ?Sized> { ptr: &'a T, diff --git a/tests/ui/deriving/deriving-smart-pointer-neg.stderr b/tests/ui/deriving/deriving-smart-pointer-neg.stderr deleted file mode 100644 index 9ab117698c7a..000000000000 --- a/tests/ui/deriving/deriving-smart-pointer-neg.stderr +++ /dev/null @@ -1,119 +0,0 @@ -error: `SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]` - --> $DIR/deriving-smart-pointer-neg.rs:6:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: `SmartPointer` can only be derived on `struct`s with at least one field - --> $DIR/deriving-smart-pointer-neg.rs:12:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: `SmartPointer` can only be derived on `struct`s with at least one field - --> $DIR/deriving-smart-pointer-neg.rs:19:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: `SmartPointer` can only be derived on `struct`s that are generic over at least one type - --> $DIR/deriving-smart-pointer-neg.rs:26:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: exactly one generic type parameter must be marked as #[pointee] to derive SmartPointer traits - --> $DIR/deriving-smart-pointer-neg.rs:31:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: only one type parameter can be marked as `#[pointee]` when deriving SmartPointer traits - --> $DIR/deriving-smart-pointer-neg.rs:40:39 - | -LL | struct TooManyPointees<'a, #[pointee] A: ?Sized, #[pointee] B: ?Sized>((&'a A, &'a B)); - | ^ ^ - -error: `SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]` - --> $DIR/deriving-smart-pointer-neg.rs:43:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: `derive(SmartPointer)` requires T to be marked `?Sized` - --> $DIR/deriving-smart-pointer-neg.rs:51:36 - | -LL | struct NoMaybeSized<'a, #[pointee] T> { - | ^ - -error: the `#[pointee]` attribute may only be used on generic parameters - --> $DIR/deriving-smart-pointer-neg.rs:59:5 - | -LL | #[pointee] - | ^^^^^^^^^^ - -error: the `#[pointee]` attribute may only be used on generic parameters - --> $DIR/deriving-smart-pointer-neg.rs:66:74 - | -LL | struct PointeeInTypeConstBlock<'a, T: ?Sized = [u32; const { struct UhOh<#[pointee] T>(T); 10 }]> { - | ^^^^^^^^^^ - -error: the `#[pointee]` attribute may only be used on generic parameters - --> $DIR/deriving-smart-pointer-neg.rs:76:34 - | -LL | const V: u32 = { struct UhOh<#[pointee] T>(T); 10 }> - | ^^^^^^^^^^ - -error: the `#[pointee]` attribute may only be used on generic parameters - --> $DIR/deriving-smart-pointer-neg.rs:85:56 - | -LL | ptr: PointeeInConstConstBlock<'a, T, { struct UhOh<#[pointee] T>(T); 0 }> - | ^^^^^^^^^^ - -error[E0392]: lifetime parameter `'a` is never used - --> $DIR/deriving-smart-pointer-neg.rs:15:16 - | -LL | struct NoField<'a, #[pointee] T: ?Sized> {} - | ^^ unused lifetime parameter - | - = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` - -error[E0392]: type parameter `T` is never used - --> $DIR/deriving-smart-pointer-neg.rs:15:31 - | -LL | struct NoField<'a, #[pointee] T: ?Sized> {} - | ^ unused type parameter - | - = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` - -error[E0392]: lifetime parameter `'a` is never used - --> $DIR/deriving-smart-pointer-neg.rs:22:20 - | -LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); - | ^^ unused lifetime parameter - | - = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` - -error[E0392]: type parameter `T` is never used - --> $DIR/deriving-smart-pointer-neg.rs:22:35 - | -LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); - | ^ unused type parameter - | - = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` - -error: aborting due to 16 previous errors - -For more information about this error, try `rustc --explain E0392`. diff --git a/tests/ui/deriving/proc-macro-attribute-mixing.rs b/tests/ui/deriving/proc-macro-attribute-mixing.rs index 489665ebeb52..80a0d068ce7d 100644 --- a/tests/ui/deriving/proc-macro-attribute-mixing.rs +++ b/tests/ui/deriving/proc-macro-attribute-mixing.rs @@ -1,5 +1,5 @@ // This test certify that we can mix attribute macros from Rust and external proc-macros. -// For instance, `#[derive(Default)]` uses `#[default]` and `#[derive(SmartPointer)]` uses +// For instance, `#[derive(Default)]` uses `#[default]` and `#[derive(CoercePointee)]` uses // `#[pointee]`. // The scoping rule should allow the use of the said two attributes when external proc-macros // are in scope. @@ -8,7 +8,7 @@ //@ aux-build: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded -#![feature(derive_smart_pointer)] +#![feature(derive_coerce_pointee)] #[macro_use] extern crate another_proc_macro; diff --git a/tests/ui/deriving/proc-macro-attribute-mixing.stdout b/tests/ui/deriving/proc-macro-attribute-mixing.stdout index f314f6efbe2b..03128c6c957c 100644 --- a/tests/ui/deriving/proc-macro-attribute-mixing.stdout +++ b/tests/ui/deriving/proc-macro-attribute-mixing.stdout @@ -1,7 +1,7 @@ #![feature(prelude_import)] #![no_std] // This test certify that we can mix attribute macros from Rust and external proc-macros. -// For instance, `#[derive(Default)]` uses `#[default]` and `#[derive(SmartPointer)]` uses +// For instance, `#[derive(Default)]` uses `#[default]` and `#[derive(CoercePointee)]` uses // `#[pointee]`. // The scoping rule should allow the use of the said two attributes when external proc-macros // are in scope. @@ -10,7 +10,7 @@ //@ aux-build: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded -#![feature(derive_smart_pointer)] +#![feature(derive_coerce_pointee)] #[prelude_import] use ::std::prelude::rust_2015::*; #[macro_use] diff --git a/tests/ui/feature-gates/feature-gate-derive-coerce-pointee.rs b/tests/ui/feature-gates/feature-gate-derive-coerce-pointee.rs new file mode 100644 index 000000000000..69bc70e8666a --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-derive-coerce-pointee.rs @@ -0,0 +1,9 @@ +use std::marker::CoercePointee; //~ ERROR use of unstable library feature 'derive_coerce_pointee' + +#[derive(CoercePointee)] //~ ERROR use of unstable library feature 'derive_coerce_pointee' +#[repr(transparent)] +struct MyPointer<'a, #[pointee] T: ?Sized> { + ptr: &'a T, +} + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-derive-coerce-pointee.stderr b/tests/ui/feature-gates/feature-gate-derive-coerce-pointee.stderr new file mode 100644 index 000000000000..0b52ceb782ae --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-derive-coerce-pointee.stderr @@ -0,0 +1,23 @@ +error[E0658]: use of unstable library feature 'derive_coerce_pointee' + --> $DIR/feature-gate-derive-coerce-pointee.rs:3:10 + | +LL | #[derive(CoercePointee)] + | ^^^^^^^^^^^^^ + | + = note: see issue #123430 for more information + = help: add `#![feature(derive_coerce_pointee)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: use of unstable library feature 'derive_coerce_pointee' + --> $DIR/feature-gate-derive-coerce-pointee.rs:1:5 + | +LL | use std::marker::CoercePointee; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #123430 for more information + = help: add `#![feature(derive_coerce_pointee)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/feature-gate-derive-smart-pointer.rs b/tests/ui/feature-gates/feature-gate-derive-smart-pointer.rs deleted file mode 100644 index 7b4764ee768a..000000000000 --- a/tests/ui/feature-gates/feature-gate-derive-smart-pointer.rs +++ /dev/null @@ -1,9 +0,0 @@ -use std::marker::SmartPointer; //~ ERROR use of unstable library feature 'derive_smart_pointer' - -#[derive(SmartPointer)] //~ ERROR use of unstable library feature 'derive_smart_pointer' -#[repr(transparent)] -struct MyPointer<'a, #[pointee] T: ?Sized> { - ptr: &'a T, -} - -fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-derive-smart-pointer.stderr b/tests/ui/feature-gates/feature-gate-derive-smart-pointer.stderr deleted file mode 100644 index ea4d1271b7c8..000000000000 --- a/tests/ui/feature-gates/feature-gate-derive-smart-pointer.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error[E0658]: use of unstable library feature 'derive_smart_pointer' - --> $DIR/feature-gate-derive-smart-pointer.rs:3:10 - | -LL | #[derive(SmartPointer)] - | ^^^^^^^^^^^^ - | - = note: see issue #123430 for more information - = help: add `#![feature(derive_smart_pointer)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: use of unstable library feature 'derive_smart_pointer' - --> $DIR/feature-gate-derive-smart-pointer.rs:1:5 - | -LL | use std::marker::SmartPointer; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #123430 for more information - = help: add `#![feature(derive_smart_pointer)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0658`. From c11bfd828ee4bace0b547c361c1088e03844af83 Mon Sep 17 00:00:00 2001 From: Laiho Date: Wed, 25 Sep 2024 14:26:41 +0300 Subject: [PATCH 171/366] vectorized SliceContains --- library/core/src/slice/cmp.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/library/core/src/slice/cmp.rs b/library/core/src/slice/cmp.rs index 1769612def0a..9cb00644e644 100644 --- a/library/core/src/slice/cmp.rs +++ b/library/core/src/slice/cmp.rs @@ -257,3 +257,29 @@ impl SliceContains for i8 { memchr::memchr(byte, bytes).is_some() } } + +macro_rules! impl_slice_contains { + ($($t:ty),*) => { + $( + impl SliceContains for $t { + #[inline] + fn slice_contains(&self, arr: &[$t]) -> bool { + // Make our LANE_COUNT 4x the normal lane count (aiming for 128 bit vectors). + // The compiler will nicely unroll it. + const LANE_COUNT: usize = 4 * (128 / (mem::size_of::<$t>() * 8)); + // SIMD + let mut chunks = arr.chunks_exact(LANE_COUNT); + for chunk in &mut chunks { + if chunk.iter().fold(false, |acc, x| acc | (*x == *self)) { + return true; + } + } + // Scalar remainder + return chunks.remainder().iter().any(|x| *x == *self); + } + } + )* + }; +} + +impl_slice_contains!(u16, u32, u64, i16, i32, i64, f32, f64, usize, isize); From bc6b2ec10ea9c18d40eba3c0b76be823687f653d Mon Sep 17 00:00:00 2001 From: Jason Boatman Date: Wed, 23 Oct 2024 13:19:53 -0500 Subject: [PATCH 172/366] Rewrite `label_details_support` condition to be consistent with other parts of the codebase. --- .../crates/rust-analyzer/src/lsp/capabilities.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs index 871cde58dce0..939593dd4533 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs @@ -210,10 +210,7 @@ impl ClientCapabilities { .completion_item .as_ref()? .label_details_support - .as_ref() - })() - .copied() - .unwrap_or_default() + })() == Some(true) } fn completion_item(&self) -> Option { From ed02421badcb3a3725a0c6093e2b5f27a0ec2306 Mon Sep 17 00:00:00 2001 From: rustbot <47979223+rustbot@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:01:23 -0400 Subject: [PATCH 173/366] Update books --- src/doc/edition-guide | 2 +- src/doc/embedded-book | 2 +- src/doc/reference | 2 +- src/doc/rustc-dev-guide | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/doc/edition-guide b/src/doc/edition-guide index c7ebae25cb48..1f07c242f816 160000 --- a/src/doc/edition-guide +++ b/src/doc/edition-guide @@ -1 +1 @@ -Subproject commit c7ebae25cb4801a31b6f05353f6d85bfa6feedd1 +Subproject commit 1f07c242f8162a711a5ac5a4ea8fa7ec884ee7a9 diff --git a/src/doc/embedded-book b/src/doc/embedded-book index f40a8b420ec4..ddbf1b4e2858 160000 --- a/src/doc/embedded-book +++ b/src/doc/embedded-book @@ -1 +1 @@ -Subproject commit f40a8b420ec4b4505d9489965e261f1d5c28ba23 +Subproject commit ddbf1b4e2858fedb71b7c42eb15c4576517dc125 diff --git a/src/doc/reference b/src/doc/reference index c64e52a3d306..b2fd0f288b8b 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit c64e52a3d306eac0129f3ad6c6d8806ab99ae2e9 +Subproject commit b2fd0f288b8b94cb34d53a893b9217251bf4e4c1 diff --git a/src/doc/rustc-dev-guide b/src/doc/rustc-dev-guide index 07bc9ca9eb1c..59d94ea75a0b 160000 --- a/src/doc/rustc-dev-guide +++ b/src/doc/rustc-dev-guide @@ -1 +1 @@ -Subproject commit 07bc9ca9eb1cd6d9fbbf758c2753b748804a134f +Subproject commit 59d94ea75a0b157e148af14c73c2dd60efb7b60a From 66ebb47b0428cc16095a9928608f155e74f19df8 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Mon, 21 Oct 2024 10:19:58 -0700 Subject: [PATCH 174/366] Update Cargo.lock due to mdbook extension changes --- src/tools/rustbook/Cargo.lock | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index 060deb183440..27ccb205b50a 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "adler2" @@ -704,6 +704,7 @@ dependencies = [ "semver", "serde_json", "tempfile", + "walkdir", ] [[package]] From 87fb4eaa9d892d3331c2651736d6d141ea827b90 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Wed, 23 Oct 2024 10:51:16 -0700 Subject: [PATCH 175/366] Update reference --- src/doc/reference | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/reference b/src/doc/reference index b2fd0f288b8b..23ce61996654 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit b2fd0f288b8b94cb34d53a893b9217251bf4e4c1 +Subproject commit 23ce619966541bf2c80d45fdfeecf3393e360a13 From df8551b60aa2b3442ccda21ac5a8bcabd2a7d67c Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Wed, 23 Oct 2024 10:52:12 -0700 Subject: [PATCH 176/366] Update rustbook to support new test linking in reference --- src/bootstrap/src/core/build_steps/doc.rs | 9 ++++++++- src/tools/rustbook/src/main.rs | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index ca2b87426478..69ec832a44aa 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -170,7 +170,14 @@ impl Step for RustbookSrc

{ builder.add_rustc_lib_path(compiler, &mut rustbook_cmd); } - rustbook_cmd.arg("build").arg(&src).arg("-d").arg(&out).run(builder); + rustbook_cmd + .arg("build") + .arg(&src) + .arg("-d") + .arg(&out) + .arg("--rust-root") + .arg(&builder.src) + .run(builder); for lang in &self.languages { let out = out.join(lang); diff --git a/src/tools/rustbook/src/main.rs b/src/tools/rustbook/src/main.rs index 2118af613969..f905b9277ff5 100644 --- a/src/tools/rustbook/src/main.rs +++ b/src/tools/rustbook/src/main.rs @@ -22,6 +22,11 @@ fn main() { .required(false) .value_parser(clap::value_parser!(String)); + let root_arg = arg!(--"rust-root" +"Path to the root of the rust source tree") + .required(false) + .value_parser(clap::value_parser!(PathBuf)); + let dir_arg = arg!([dir] "Root directory for the book\n\ (Defaults to the current directory when omitted)") .value_parser(clap::value_parser!(PathBuf)); @@ -37,6 +42,7 @@ fn main() { .about("Build the book from the markdown files") .arg(d_arg) .arg(l_arg) + .arg(root_arg) .arg(&dir_arg), ) .subcommand( @@ -96,7 +102,8 @@ pub fn build(args: &ArgMatches) -> Result3<()> { } if book.config.get_preprocessor("spec").is_some() { - book.with_preprocessor(Spec::new()); + let rust_root = args.get_one::("rust-root").cloned(); + book.with_preprocessor(Spec::new(rust_root)?); } book.build()?; From 8ee548fcf01ea4aa5b17f6daef6f2f86c2f6fde5 Mon Sep 17 00:00:00 2001 From: Zachary S Date: Wed, 23 Oct 2024 14:22:32 -0500 Subject: [PATCH 177/366] const fn str::is_char_boundary --- library/core/src/str/mod.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index e93c52f27999..e5b8e015aea4 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -185,8 +185,9 @@ impl str { /// ``` #[must_use] #[stable(feature = "is_char_boundary", since = "1.9.0")] + #[rustc_const_unstable(feature = "const_is_char_boundary", issue = "131516")] #[inline] - pub fn is_char_boundary(&self, index: usize) -> bool { + pub const fn is_char_boundary(&self, index: usize) -> bool { // 0 is always ok. // Test for 0 explicitly so that it can optimize out the check // easily and skip reading string data for that case. @@ -195,8 +196,8 @@ impl str { return true; } - match self.as_bytes().get(index) { - // For `None` we have two options: + if index >= self.len() { + // For `true` we have two options: // // - index == self.len() // Empty strings are valid, so return true @@ -205,9 +206,9 @@ impl str { // // The check is placed exactly here, because it improves generated // code on higher opt-levels. See PR #84751 for more details. - None => index == self.len(), - - Some(&b) => b.is_utf8_char_boundary(), + index == self.len() + } else { + self.as_bytes()[index].is_utf8_char_boundary() } } From aa493d0b6020f0f166d2e3a2628761b7428a12a1 Mon Sep 17 00:00:00 2001 From: Zachary S Date: Wed, 23 Oct 2024 14:22:56 -0500 Subject: [PATCH 178/366] const fn str::split_at* --- library/core/src/lib.rs | 2 ++ library/core/src/str/mod.rs | 35 +++++++++++++++++++++++++++++------ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index e323e88f2614..8e735bb96ee5 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -196,7 +196,9 @@ #![feature(cfg_target_has_atomic_equal_alignment)] #![feature(cfg_ub_checks)] #![feature(const_for)] +#![feature(const_is_char_boundary)] #![feature(const_precise_live_drops)] +#![feature(const_str_split_at)] #![feature(decl_macro)] #![feature(deprecated_suggestion)] #![feature(doc_cfg)] diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index e5b8e015aea4..f5c39af1d53a 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -640,7 +640,8 @@ impl str { #[inline] #[must_use] #[stable(feature = "str_split_at", since = "1.4.0")] - pub fn split_at(&self, mid: usize) -> (&str, &str) { + #[rustc_const_unstable(feature = "const_str_split_at", issue = "131518")] + pub const fn split_at(&self, mid: usize) -> (&str, &str) { match self.split_at_checked(mid) { None => slice_error_fail(self, 0, mid), Some(pair) => pair, @@ -680,7 +681,8 @@ impl str { #[inline] #[must_use] #[stable(feature = "str_split_at", since = "1.4.0")] - pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) { + #[rustc_const_unstable(feature = "const_str_split_at", issue = "131518")] + pub const fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { // SAFETY: just checked that `mid` is on a char boundary. @@ -719,11 +721,12 @@ impl str { #[inline] #[must_use] #[stable(feature = "split_at_checked", since = "1.80.0")] - pub fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)> { + #[rustc_const_unstable(feature = "const_str_split_at", issue = "131518")] + pub const fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)> { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { // SAFETY: just checked that `mid` is on a char boundary. - Some(unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }) + Some(unsafe { self.split_at_unchecked(mid) }) } else { None } @@ -759,7 +762,9 @@ impl str { #[inline] #[must_use] #[stable(feature = "split_at_checked", since = "1.80.0")] - pub fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut str, &mut str)> { + #[rustc_const_unstable(feature = "const_str_split_at", issue = "131518")] + #[rustc_allow_const_fn_unstable(const_is_char_boundary)] + pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut str, &mut str)> { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { // SAFETY: just checked that `mid` is on a char boundary. @@ -775,7 +780,25 @@ impl str { /// /// The caller must ensure that `mid` is a valid byte offset from the start /// of the string and falls on the boundary of a UTF-8 code point. - unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) { + const unsafe fn split_at_unchecked(&self, mid: usize) -> (&str, &str) { + let len = self.len(); + let ptr = self.as_ptr(); + // SAFETY: caller guarantees `mid` is on a char boundary. + unsafe { + ( + from_utf8_unchecked(slice::from_raw_parts(ptr, mid)), + from_utf8_unchecked(slice::from_raw_parts(ptr.add(mid), len - mid)), + ) + } + } + + /// Divides one string slice into two at an index. + /// + /// # Safety + /// + /// The caller must ensure that `mid` is a valid byte offset from the start + /// of the string and falls on the boundary of a UTF-8 code point. + const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) { let len = self.len(); let ptr = self.as_mut_ptr(); // SAFETY: caller guarantees `mid` is on a char boundary. From eee4037ddf026ea4772fabee87880b77b94b36cf Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Wed, 23 Oct 2024 22:10:53 +0900 Subject: [PATCH 179/366] fix: Prevent public reexport of private item --- .../crates/hir-def/src/find_path.rs | 4 +- .../crates/hir-def/src/nameres/collector.rs | 22 ++++++---- .../crates/hir-def/src/nameres/tests/globs.rs | 39 +++++++++++++++++ .../crates/hir-def/src/visibility.rs | 42 +++++++++++++++++++ 4 files changed, 98 insertions(+), 9 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs b/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs index f5e03e5281e2..a615abd1bbe0 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs @@ -1025,7 +1025,7 @@ pub mod ast { check_found_path( r#" mod bar { - mod foo { pub(super) struct S; } + mod foo { pub(crate) struct S; } pub(crate) use foo::*; } $0 @@ -1047,7 +1047,7 @@ $0 check_found_path( r#" mod bar { - mod foo { pub(super) struct S; } + mod foo { pub(crate) struct S; } pub(crate) use foo::S as U; } $0 diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs index 22b9c2b4e37e..b9aec9369035 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs @@ -985,12 +985,8 @@ impl DefCollector<'_> { for (name, res) in resolutions { match name { Some(name) => { - changed |= self.push_res_and_update_glob_vis( - module_id, - name, - res.with_visibility(vis), - import, - ); + changed |= + self.push_res_and_update_glob_vis(module_id, name, *res, vis, import); } None => { let tr = match res.take_types() { @@ -1043,10 +1039,11 @@ impl DefCollector<'_> { .collect::>(); for (glob_importing_module, glob_import_vis, use_) in glob_imports { + let vis = glob_import_vis.min(vis, &self.def_map).unwrap_or(glob_import_vis); self.update_recursive( glob_importing_module, resolutions, - glob_import_vis, + vis, Some(ImportType::Glob(use_)), depth + 1, ); @@ -1058,8 +1055,19 @@ impl DefCollector<'_> { module_id: LocalModuleId, name: &Name, mut defs: PerNs, + vis: Visibility, def_import_type: Option, ) -> bool { + if let Some((_, v, _)) = defs.types.as_mut() { + *v = v.min(vis, &self.def_map).unwrap_or(vis); + } + if let Some((_, v, _)) = defs.values.as_mut() { + *v = v.min(vis, &self.def_map).unwrap_or(vis); + } + if let Some((_, v, _)) = defs.macros.as_mut() { + *v = v.min(vis, &self.def_map).unwrap_or(vis); + } + let mut changed = false; if let Some(ImportType::Glob(_)) = def_import_type { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/globs.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/globs.rs index a2696055ca10..543ab41cd59a 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/globs.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/globs.rs @@ -412,3 +412,42 @@ use reexport::*; "#]], ); } + +#[test] +fn regression_18308() { + check( + r#" +use outer::*; + +mod outer { + mod inner_superglob { + pub use super::*; + } + + // The importing order matters! + pub use inner_superglob::*; + use super::glob_target::*; +} + +mod glob_target { + pub struct ShouldBePrivate; +} +"#, + expect![[r#" + crate + glob_target: t + outer: t + + crate::glob_target + ShouldBePrivate: t v + + crate::outer + ShouldBePrivate: t v + inner_superglob: t + + crate::outer::inner_superglob + ShouldBePrivate: t v + inner_superglob: t + "#]], + ); +} diff --git a/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs b/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs index 3aeb88047a0d..4edb68359225 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/visibility.rs @@ -191,6 +191,11 @@ impl Visibility { return None; } + let def_block = def_map.block_id(); + if (mod_a.containing_block(), mod_b.containing_block()) != (def_block, def_block) { + return None; + } + let mut a_ancestors = iter::successors(Some(mod_a.local_id), |&m| def_map[m].parent); let mut b_ancestors = @@ -210,6 +215,43 @@ impl Visibility { } } } + + /// Returns the least permissive visibility of `self` and `other`. + /// + /// If there is no subset relation between `self` and `other`, returns `None` (ie. they're only + /// visible in unrelated modules). + pub(crate) fn min(self, other: Visibility, def_map: &DefMap) -> Option { + match (self, other) { + (vis, Visibility::Public) | (Visibility::Public, vis) => Some(vis), + (Visibility::Module(mod_a, expl_a), Visibility::Module(mod_b, expl_b)) => { + if mod_a.krate != mod_b.krate { + return None; + } + + let def_block = def_map.block_id(); + if (mod_a.containing_block(), mod_b.containing_block()) != (def_block, def_block) { + return None; + } + + let mut a_ancestors = + iter::successors(Some(mod_a.local_id), |&m| def_map[m].parent); + let mut b_ancestors = + iter::successors(Some(mod_b.local_id), |&m| def_map[m].parent); + + if a_ancestors.any(|m| m == mod_b.local_id) { + // B is above A + return Some(Visibility::Module(mod_a, expl_b)); + } + + if b_ancestors.any(|m| m == mod_a.local_id) { + // A is above B + return Some(Visibility::Module(mod_b, expl_a)); + } + + None + } + } + } } /// Whether the item was imported through an explicit `pub(crate) use` or just a `use` without From 4d541f7cf3e3e3835f0556a93e6d300b8d2e32da Mon Sep 17 00:00:00 2001 From: David Barsky Date: Wed, 23 Oct 2024 12:44:57 -0700 Subject: [PATCH 180/366] internal: log original syntax on panic --- src/tools/rust-analyzer/crates/span/src/ast_id.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/span/src/ast_id.rs b/src/tools/rust-analyzer/crates/span/src/ast_id.rs index 0ebd72e1514c..1d81d684511c 100644 --- a/src/tools/rust-analyzer/crates/span/src/ast_id.rs +++ b/src/tools/rust-analyzer/crates/span/src/ast_id.rs @@ -224,9 +224,10 @@ impl AstIdMap { match self.map.raw_entry().from_hash(hash, |&idx| self.arena[idx] == ptr) { Some((&idx, &())) => ErasedFileAstId(idx.into_raw().into_u32()), None => panic!( - "Can't find {:?} in AstIdMap:\n{:?}", + "Can't find {:?} in AstIdMap:\n{:?}\n source text: {}", item, self.arena.iter().map(|(_id, i)| i).collect::>(), + item ), } } From dab76eccdfbb6f7b4b445ad05ba4ef004c43e130 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 12 Oct 2024 11:52:30 +0200 Subject: [PATCH 181/366] fix a couple clippy:complexitys double_parens filter_map_identity needless_question_mark redundant_guards --- compiler/rustc_attr/src/builtin.rs | 4 ++-- compiler/rustc_middle/src/mir/pretty.rs | 4 ++-- compiler/rustc_mir_transform/src/coverage/mappings.rs | 2 +- compiler/rustc_mir_transform/src/coverage/spans.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index e412417a9e95..537d8e045311 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -619,11 +619,11 @@ pub fn eval_condition( // we can't use `try_gate_cfg` as symbols don't differentiate between `r#true` // and `true`, and we want to keep the former working without feature gate gate_cfg( - &(( + &( if *b { kw::True } else { kw::False }, sym::cfg_boolean_literals, |features: &Features| features.cfg_boolean_literals(), - )), + ), cfg.span(), sess, features, diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 2a3a070a6e71..faa022b50ef1 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -277,9 +277,9 @@ pub fn create_dump_file<'tcx>( ) })?; } - Ok(fs::File::create_buffered(&file_path).map_err(|e| { + fs::File::create_buffered(&file_path).map_err(|e| { io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}")) - })?) + }) } /////////////////////////////////////////////////////////////////////////// diff --git a/compiler/rustc_mir_transform/src/coverage/mappings.rs b/compiler/rustc_mir_transform/src/coverage/mappings.rs index bc86ae22a0db..2db7c6cf1d6f 100644 --- a/compiler/rustc_mir_transform/src/coverage/mappings.rs +++ b/compiler/rustc_mir_transform/src/coverage/mappings.rs @@ -363,7 +363,7 @@ fn calc_test_vectors_index(conditions: &mut Vec) -> usize { let ConditionInfo { condition_id, true_next_id, false_next_id } = branch.condition_info; [true_next_id, false_next_id] .into_iter() - .filter_map(std::convert::identity) + .flatten() .for_each(|next_id| indegree_stats[next_id] += 1); (condition_id, branch) }) diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index da7d20cf19a6..085c738f1f9f 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -87,7 +87,7 @@ fn remove_unwanted_expansion_spans(covspans: &mut Vec) { covspans.retain(|covspan| { match covspan.expn_kind { // Retain only the first await-related or macro-expanded covspan with this span. - Some(ExpnKind::Desugaring(kind)) if kind == DesugaringKind::Await => { + Some(ExpnKind::Desugaring(DesugaringKind::Await)) => { deduplicated_spans.insert(covspan.span) } Some(ExpnKind::Macro(MacroKind::Bang, _)) => deduplicated_spans.insert(covspan.span), From c8ce15050ca35691c32b4e82f588f93da8c6d4a9 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 22:17:18 +0200 Subject: [PATCH 182/366] Swap query call order in file_item_tree_query --- src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs index 7cb833fdce7c..91a8cbab1a29 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs @@ -103,9 +103,8 @@ impl ItemTree { let _p = tracing::info_span!("file_item_tree_query", ?file_id).entered(); static EMPTY: OnceLock> = OnceLock::new(); - let syntax = db.parse_or_expand(file_id); - let ctx = lower::Ctx::new(db, file_id); + let syntax = db.parse_or_expand(file_id); let mut top_attrs = None; let mut item_tree = match_ast! { match syntax { From 6cb84feef7708ae11aad4f08892c09467d027041 Mon Sep 17 00:00:00 2001 From: Ding Xiang Fei Date: Thu, 24 Oct 2024 04:18:53 +0800 Subject: [PATCH 183/366] apply suggestion --- compiler/rustc_feature/src/unstable.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 760bcce89ec7..4afceb7be2e2 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -425,8 +425,6 @@ declare_features! ( (unstable, deprecated_suggestion, "1.61.0", Some(94785)), /// Allows deref patterns. (incomplete, deref_patterns, "1.79.0", Some(87121)), - /// Allows deriving traits as per `CoercePointee` specification - (unstable, derive_coerce_pointee, "1.79.0", Some(123430)), /// Controls errors in trait implementations. (unstable, do_not_recommend, "1.67.0", Some(51992)), /// Tells rustdoc to automatically generate `#[doc(cfg(...))]`. From 464f4057c28ef3c6ae4acb696ee27f7f3f2112ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 12 Oct 2024 12:59:32 +0200 Subject: [PATCH 184/366] fix some manual_map --- .../src/diagnostics/mutability_errors.rs | 10 +++------- compiler/rustc_hir_typeck/src/method/suggest.rs | 2 +- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index a5f3298b02cc..315851729b1e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -959,13 +959,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { None } } - hir::ExprKind::MethodCall(_, _, args, span) => { - if let Some(def_id) = typeck_results.type_dependent_def_id(*hir_id) { - Some((def_id, *span, *args)) - } else { - None - } - } + hir::ExprKind::MethodCall(_, _, args, span) => typeck_results + .type_dependent_def_id(*hir_id) + .map(|def_id| (def_id, *span, *args)), _ => None, } }; diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 9dd595411486..eaf40a193a63 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -537,7 +537,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && binding_id != self.binding_id { if self.check_and_add_sugg_binding(LetStmt { - ty_hir_id_opt: if let Some(ty) = ty { Some(ty.hir_id) } else { None }, + ty_hir_id_opt: ty.map(|ty| ty.hir_id), binding_id, span: pat.span, init_hir_id: init.hir_id, From d84d659cb523e1156be8f7657879eb168a3f7fd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 12 Oct 2024 21:38:06 +0200 Subject: [PATCH 185/366] clone range in a more obvious way --- compiler/rustc_infer/src/infer/type_variable.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/compiler/rustc_infer/src/infer/type_variable.rs b/compiler/rustc_infer/src/infer/type_variable.rs index 779ce976becc..2086483b94a7 100644 --- a/compiler/rustc_infer/src/infer/type_variable.rs +++ b/compiler/rustc_infer/src/infer/type_variable.rs @@ -187,10 +187,7 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> { value_count: usize, ) -> (Range, Vec) { let range = TyVid::from_usize(value_count)..TyVid::from_usize(self.num_vars()); - ( - range.start..range.end, - (range.start..range.end).map(|index| self.var_origin(index)).collect(), - ) + (range.clone(), range.map(|index| self.var_origin(index)).collect()) } /// Returns indices of all variables that are not yet From 6d569f769c3d7becbd566b4fec5baf9f11e098e1 Mon Sep 17 00:00:00 2001 From: Ding Xiang Fei Date: Mon, 21 Oct 2024 05:06:30 +0800 Subject: [PATCH 186/366] stabilize if_let_rescope --- compiler/rustc_feature/src/accepted.rs | 2 ++ compiler/rustc_feature/src/unstable.rs | 2 -- .../rustc_hir_analysis/src/check/region.rs | 6 ++--- compiler/rustc_lint/src/if_let_rescope.rs | 3 +-- compiler/rustc_mir_build/src/thir/cx/expr.rs | 2 +- tests/ui/drop/drop_order.rs | 2 +- tests/ui/drop/drop_order_if_let_rescope.rs | 1 - .../if-let-rescope-borrowck-suggestions.rs | 1 - ...if-let-rescope-borrowck-suggestions.stderr | 12 ++++----- ...t-if-let-rescope-gated.edition2021.stderr} | 0 tests/ui/drop/lint-if-let-rescope-gated.rs | 22 +++++++-------- .../ui/drop/lint-if-let-rescope-with-macro.rs | 1 - .../lint-if-let-rescope-with-macro.stderr | 6 ++--- tests/ui/drop/lint-if-let-rescope.fixed | 2 +- tests/ui/drop/lint-if-let-rescope.rs | 2 +- .../feature-gate-if-let-rescope.rs | 27 ------------------- .../feature-gate-if-let-rescope.stderr | 18 ------------- tests/ui/mir/mir_let_chains_drop_order.rs | 1 - .../issue-54556-niconii.edition2021.stderr | 2 +- tests/ui/nll/issue-54556-niconii.rs | 2 -- 20 files changed, 30 insertions(+), 84 deletions(-) rename tests/ui/drop/{lint-if-let-rescope-gated.with_feature_gate.stderr => lint-if-let-rescope-gated.edition2021.stderr} (100%) delete mode 100644 tests/ui/feature-gates/feature-gate-if-let-rescope.rs delete mode 100644 tests/ui/feature-gates/feature-gate-if-let-rescope.stderr diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 4f71bdaca1b1..95b33890d69e 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -224,6 +224,8 @@ declare_features! ( (accepted, i128_type, "1.26.0", Some(35118)), /// Allows the use of `if let` expressions. (accepted, if_let, "1.0.0", None), + /// Rescoping temporaries in `if let` to align with Rust 2024. + (accepted, if_let_rescope, "CURRENT_RUSTC_VERSION", Some(124085)), /// Allows top level or-patterns (`p | q`) in `if let` and `while let`. (accepted, if_while_or_patterns, "1.33.0", Some(48215)), /// Allows lifetime elision in `impl` headers. For example: diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 8f4c208f1fbb..63c43c41ca69 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -482,8 +482,6 @@ declare_features! ( (unstable, half_open_range_patterns_in_slices, "1.66.0", Some(67264)), /// Allows `if let` guard in match arms. (unstable, if_let_guard, "1.47.0", Some(51114)), - /// Rescoping temporaries in `if let` to align with Rust 2024. - (unstable, if_let_rescope, "1.83.0", Some(124085)), /// Allows `impl Trait` to be used inside associated types (RFC 2515). (unstable, impl_trait_in_assoc_type, "1.70.0", Some(63063)), /// Allows `impl Trait` as output type in `Fn` traits in return position of functions. diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 312fb16c93aa..e37a7ed29524 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -466,8 +466,7 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h hir::ExprKind::If(cond, then, Some(otherwise)) => { let expr_cx = visitor.cx; - let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope() - { + let data = if expr.span.at_least_rust_2024() { ScopeData::IfThenRescope } else { ScopeData::IfThen @@ -482,8 +481,7 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h hir::ExprKind::If(cond, then, None) => { let expr_cx = visitor.cx; - let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope() - { + let data = if expr.span.at_least_rust_2024() { ScopeData::IfThenRescope } else { ScopeData::IfThen diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index bdfcc2c0a100..afcfbebc14b3 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -24,7 +24,6 @@ declare_lint! { /// ### Example /// /// ```rust,edition2021 - /// #![feature(if_let_rescope)] /// #![warn(if_let_rescope)] /// #![allow(unused_variables)] /// @@ -243,7 +242,7 @@ impl_lint_pass!( impl<'tcx> LateLintPass<'tcx> for IfLetRescope { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { - if expr.span.edition().at_least_rust_2024() || !cx.tcx.features().if_let_rescope() { + if expr.span.edition().at_least_rust_2024() { return; } if let (Level::Allow, _) = cx.tcx.lint_level_at_node(IF_LET_RESCOPE, expr.hir_id) { diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 5faefe2f25f4..24c914da77a0 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -777,7 +777,7 @@ impl<'tcx> Cx<'tcx> { if_then_scope: region::Scope { id: then.hir_id.local_id, data: { - if expr.span.at_least_rust_2024() && tcx.features().if_let_rescope() { + if expr.span.at_least_rust_2024() { region::ScopeData::IfThenRescope } else { region::ScopeData::IfThen diff --git a/tests/ui/drop/drop_order.rs b/tests/ui/drop/drop_order.rs index cf0625380074..9706cb66b19d 100644 --- a/tests/ui/drop/drop_order.rs +++ b/tests/ui/drop/drop_order.rs @@ -4,8 +4,8 @@ //@ [edition2021] edition: 2021 //@ [edition2024] compile-flags: -Z unstable-options //@ [edition2024] edition: 2024 + #![feature(let_chains)] -#![cfg_attr(edition2024, feature(if_let_rescope))] use std::cell::RefCell; use std::convert::TryInto; diff --git a/tests/ui/drop/drop_order_if_let_rescope.rs b/tests/ui/drop/drop_order_if_let_rescope.rs index ae9f381820e1..cea84bbaa2b9 100644 --- a/tests/ui/drop/drop_order_if_let_rescope.rs +++ b/tests/ui/drop/drop_order_if_let_rescope.rs @@ -3,7 +3,6 @@ //@ compile-flags: -Z validate-mir -Zunstable-options #![feature(let_chains)] -#![feature(if_let_rescope)] use std::cell::RefCell; use std::convert::TryInto; diff --git a/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs b/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs index 2476f7cf2580..e055c20d777b 100644 --- a/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs +++ b/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs @@ -1,7 +1,6 @@ //@ edition: 2024 //@ compile-flags: -Z validate-mir -Zunstable-options -#![feature(if_let_rescope)] #![deny(if_let_rescope)] struct Droppy; diff --git a/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr b/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr index 0c6f1ea28d2a..3c87e196af6e 100644 --- a/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr +++ b/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr @@ -1,5 +1,5 @@ error[E0716]: temporary value dropped while borrowed - --> $DIR/if-let-rescope-borrowck-suggestions.rs:22:39 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:21:39 | LL | do_something(if let Some(value) = Droppy.get_ref() { value } else { &0 }); | ^^^^^^ - temporary value is freed at the end of this statement @@ -7,7 +7,7 @@ LL | do_something(if let Some(value) = Droppy.get_ref() { value } else { &0 | creates a temporary value which is freed while still in use | note: lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead - --> $DIR/if-let-rescope-borrowck-suggestions.rs:22:64 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:21:64 | LL | do_something(if let Some(value) = Droppy.get_ref() { value } else { &0 }); | ^ @@ -22,7 +22,7 @@ LL | do_something({ match Droppy.get_ref() { Some(value) => { value } _ => | ~~~~~~~ ++++++++++++++++ ~~~~ ++ error[E0716]: temporary value dropped while borrowed - --> $DIR/if-let-rescope-borrowck-suggestions.rs:24:39 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:23:39 | LL | do_something(if let Some(value) = Droppy.get_ref() { | ^^^^^^ creates a temporary value which is freed while still in use @@ -31,7 +31,7 @@ LL | } else if let Some(value) = Droppy.get_ref() { | - temporary value is freed at the end of this statement | note: lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead - --> $DIR/if-let-rescope-borrowck-suggestions.rs:27:5 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:26:5 | LL | } else if let Some(value) = Droppy.get_ref() { | ^ @@ -53,7 +53,7 @@ LL ~ }}}); | error[E0716]: temporary value dropped while borrowed - --> $DIR/if-let-rescope-borrowck-suggestions.rs:27:33 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:26:33 | LL | } else if let Some(value) = Droppy.get_ref() { | ^^^^^^ creates a temporary value which is freed while still in use @@ -62,7 +62,7 @@ LL | } else { | - temporary value is freed at the end of this statement | note: lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead - --> $DIR/if-let-rescope-borrowck-suggestions.rs:30:5 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:29:5 | LL | } else { | ^ diff --git a/tests/ui/drop/lint-if-let-rescope-gated.with_feature_gate.stderr b/tests/ui/drop/lint-if-let-rescope-gated.edition2021.stderr similarity index 100% rename from tests/ui/drop/lint-if-let-rescope-gated.with_feature_gate.stderr rename to tests/ui/drop/lint-if-let-rescope-gated.edition2021.stderr diff --git a/tests/ui/drop/lint-if-let-rescope-gated.rs b/tests/ui/drop/lint-if-let-rescope-gated.rs index cef5de5a8fe5..ba0246573b40 100644 --- a/tests/ui/drop/lint-if-let-rescope-gated.rs +++ b/tests/ui/drop/lint-if-let-rescope-gated.rs @@ -1,13 +1,13 @@ // This test checks that the lint `if_let_rescope` only actions -// when the feature gate is enabled. -// Edition 2021 is used here because the lint should work especially -// when edition migration towards 2024 is run. +// when Edition 2021 or prior is targeted here because the lint should work especially +// when edition migration towards 2024 is executed. -//@ revisions: with_feature_gate without_feature_gate -//@ [without_feature_gate] check-pass -//@ edition: 2021 +//@ revisions: edition2021 edition2024 +//@ [edition2021] edition: 2021 +//@ [edition2024] edition: 2024 +//@ [edition2024] compile-flags: -Zunstable-options +//@ [edition2024] check-pass -#![cfg_attr(with_feature_gate, feature(if_let_rescope))] #![deny(if_let_rescope)] #![allow(irrefutable_let_patterns)] @@ -25,10 +25,10 @@ impl Droppy { fn main() { if let Some(_value) = Droppy.get() { - //[with_feature_gate]~^ ERROR: `if let` assigns a shorter lifetime since Edition 2024 - //[with_feature_gate]~| HELP: a `match` with a single arm can preserve the drop order up to Edition 2021 - //[with_feature_gate]~| WARN: this changes meaning in Rust 2024 + //[edition2021]~^ ERROR: `if let` assigns a shorter lifetime since Edition 2024 + //[edition2021]~| HELP: a `match` with a single arm can preserve the drop order up to Edition 2021 + //[edition2021]~| WARN: this changes meaning in Rust 2024 } else { - //[with_feature_gate]~^ HELP: the value is now dropped here in Edition 2024 + //[edition2021]~^ HELP: the value is now dropped here in Edition 2024 } } diff --git a/tests/ui/drop/lint-if-let-rescope-with-macro.rs b/tests/ui/drop/lint-if-let-rescope-with-macro.rs index 282b3320d300..e7aeb81f4d1a 100644 --- a/tests/ui/drop/lint-if-let-rescope-with-macro.rs +++ b/tests/ui/drop/lint-if-let-rescope-with-macro.rs @@ -4,7 +4,6 @@ //@ edition:2021 //@ compile-flags: -Z unstable-options -#![feature(if_let_rescope)] #![deny(if_let_rescope)] #![allow(irrefutable_let_patterns)] diff --git a/tests/ui/drop/lint-if-let-rescope-with-macro.stderr b/tests/ui/drop/lint-if-let-rescope-with-macro.stderr index 5fd0c61d17a5..de6cf6e8500e 100644 --- a/tests/ui/drop/lint-if-let-rescope-with-macro.stderr +++ b/tests/ui/drop/lint-if-let-rescope-with-macro.stderr @@ -1,5 +1,5 @@ error: `if let` assigns a shorter lifetime since Edition 2024 - --> $DIR/lint-if-let-rescope-with-macro.rs:13:12 + --> $DIR/lint-if-let-rescope-with-macro.rs:12:12 | LL | if let $p = $e { $($conseq)* } else { $($alt)* } | ^^^ @@ -16,7 +16,7 @@ LL | | }; = warning: this changes meaning in Rust 2024 = note: for more information, see issue #124085 help: the value is now dropped here in Edition 2024 - --> $DIR/lint-if-let-rescope-with-macro.rs:13:38 + --> $DIR/lint-if-let-rescope-with-macro.rs:12:38 | LL | if let $p = $e { $($conseq)* } else { $($alt)* } | ^ @@ -29,7 +29,7 @@ LL | | {} LL | | }; | |_____- in this macro invocation note: the lint level is defined here - --> $DIR/lint-if-let-rescope-with-macro.rs:8:9 + --> $DIR/lint-if-let-rescope-with-macro.rs:7:9 | LL | #![deny(if_let_rescope)] | ^^^^^^^^^^^^^^ diff --git a/tests/ui/drop/lint-if-let-rescope.fixed b/tests/ui/drop/lint-if-let-rescope.fixed index 199068d0fd26..fec2e3b2ae70 100644 --- a/tests/ui/drop/lint-if-let-rescope.fixed +++ b/tests/ui/drop/lint-if-let-rescope.fixed @@ -1,7 +1,7 @@ //@ run-rustfix #![deny(if_let_rescope)] -#![feature(if_let_rescope, stmt_expr_attributes)] +#![feature(stmt_expr_attributes)] #![allow(irrefutable_let_patterns, unused_parens)] fn droppy() -> Droppy { diff --git a/tests/ui/drop/lint-if-let-rescope.rs b/tests/ui/drop/lint-if-let-rescope.rs index 4c043c0266cc..ee184695b97a 100644 --- a/tests/ui/drop/lint-if-let-rescope.rs +++ b/tests/ui/drop/lint-if-let-rescope.rs @@ -1,7 +1,7 @@ //@ run-rustfix #![deny(if_let_rescope)] -#![feature(if_let_rescope, stmt_expr_attributes)] +#![feature(stmt_expr_attributes)] #![allow(irrefutable_let_patterns, unused_parens)] fn droppy() -> Droppy { diff --git a/tests/ui/feature-gates/feature-gate-if-let-rescope.rs b/tests/ui/feature-gates/feature-gate-if-let-rescope.rs deleted file mode 100644 index bd1efd4fb7c1..000000000000 --- a/tests/ui/feature-gates/feature-gate-if-let-rescope.rs +++ /dev/null @@ -1,27 +0,0 @@ -// This test shows the code that could have been accepted by enabling #![feature(if_let_rescope)] - -struct A; -struct B<'a, T>(&'a mut T); - -impl A { - fn f(&mut self) -> Option> { - Some(B(self)) - } -} - -impl<'a, T> Drop for B<'a, T> { - fn drop(&mut self) { - // this is needed to keep NLL's hands off and to ensure - // the inner mutable borrow stays alive - } -} - -fn main() { - let mut a = A; - if let None = a.f().as_ref() { - unreachable!() - } else { - a.f().unwrap(); - //~^ ERROR cannot borrow `a` as mutable more than once at a time - }; -} diff --git a/tests/ui/feature-gates/feature-gate-if-let-rescope.stderr b/tests/ui/feature-gates/feature-gate-if-let-rescope.stderr deleted file mode 100644 index ff1846ae0b1f..000000000000 --- a/tests/ui/feature-gates/feature-gate-if-let-rescope.stderr +++ /dev/null @@ -1,18 +0,0 @@ -error[E0499]: cannot borrow `a` as mutable more than once at a time - --> $DIR/feature-gate-if-let-rescope.rs:24:9 - | -LL | if let None = a.f().as_ref() { - | ----- - | | - | first mutable borrow occurs here - | a temporary with access to the first borrow is created here ... -... -LL | a.f().unwrap(); - | ^ second mutable borrow occurs here -LL | -LL | }; - | - ... and the first borrow might be used here, when that temporary is dropped and runs the destructor for type `Option>` - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/mir/mir_let_chains_drop_order.rs b/tests/ui/mir/mir_let_chains_drop_order.rs index daf0a62fc85f..92199625207e 100644 --- a/tests/ui/mir/mir_let_chains_drop_order.rs +++ b/tests/ui/mir/mir_let_chains_drop_order.rs @@ -8,7 +8,6 @@ // See `mir_drop_order.rs` for more information #![feature(let_chains)] -#![cfg_attr(edition2024, feature(if_let_rescope))] #![allow(irrefutable_let_patterns)] use std::cell::RefCell; diff --git a/tests/ui/nll/issue-54556-niconii.edition2021.stderr b/tests/ui/nll/issue-54556-niconii.edition2021.stderr index 31a03abbc982..abee09ed9503 100644 --- a/tests/ui/nll/issue-54556-niconii.edition2021.stderr +++ b/tests/ui/nll/issue-54556-niconii.edition2021.stderr @@ -1,5 +1,5 @@ error[E0597]: `counter` does not live long enough - --> $DIR/issue-54556-niconii.rs:30:20 + --> $DIR/issue-54556-niconii.rs:28:20 | LL | let counter = Mutex; | ------- binding `counter` declared here diff --git a/tests/ui/nll/issue-54556-niconii.rs b/tests/ui/nll/issue-54556-niconii.rs index 1a7ad17cc84c..f01e0523cbf9 100644 --- a/tests/ui/nll/issue-54556-niconii.rs +++ b/tests/ui/nll/issue-54556-niconii.rs @@ -12,8 +12,6 @@ //@ [edition2024] compile-flags: -Z unstable-options //@ [edition2024] check-pass -#![cfg_attr(edition2024, feature(if_let_rescope))] - struct Mutex; struct MutexGuard<'a>(&'a Mutex); From 2204724a86cf403b272bbac1e3ff474c1eeab021 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Wed, 23 Oct 2024 15:18:43 -0700 Subject: [PATCH 187/366] internal: Pretty-print Config in status command Config can become very big, even for relatively small rust project, and printing everything on one line makes reading the output in VS Code harder. --- .../rust-analyzer/crates/rust-analyzer/src/handlers/request.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs index b4e6e4c29373..5b4b678c0c6e 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs @@ -119,7 +119,7 @@ pub(crate) fn handle_analyzer_status( format_to!(buf, "{}", crate::version()); buf.push_str("\nConfiguration: \n"); - format_to!(buf, "{:?}", snap.config); + format_to!(buf, "{:#?}", snap.config); Ok(buf) } From a53655a023cee5dee1873bd3dfc805d7c460fbeb Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Wed, 23 Oct 2024 19:15:23 -0400 Subject: [PATCH 188/366] rustdoc: adjust spacing and typography in header --- src/librustdoc/html/render/mod.rs | 4 ++-- src/librustdoc/html/static/css/rustdoc.css | 10 ++++++++-- src/librustdoc/html/templates/print_item.html | 2 +- tests/rustdoc-gui/item-info.goml | 2 +- tests/rustdoc-gui/scrape-examples-layout.goml | 8 ++++---- tests/rustdoc-gui/sidebar-source-code-display.goml | 2 +- tests/rustdoc-gui/source-anchor-scroll.goml | 8 ++++---- tests/rustdoc-gui/source-code-page.goml | 6 +++--- tests/rustdoc/anchors.no_const_anchor.html | 2 +- tests/rustdoc/anchors.no_const_anchor2.html | 2 +- tests/rustdoc/anchors.no_method_anchor.html | 2 +- tests/rustdoc/anchors.no_trait_method_anchor.html | 2 +- tests/rustdoc/anchors.no_tymethod_anchor.html | 2 +- tests/rustdoc/anchors.no_type_anchor.html | 2 +- tests/rustdoc/anchors.no_type_anchor2.html | 2 +- tests/rustdoc/assoc-type-source-link.rs | 4 ++-- tests/rustdoc/ensure-src-link.rs | 2 +- tests/rustdoc/external-macro-src.rs | 4 ++-- tests/rustdoc/source-version-separator.rs | 10 +++++----- tests/rustdoc/src-link-external-macro-26606.rs | 2 +- tests/rustdoc/src-links-auto-impls.rs | 6 +++--- tests/rustdoc/thread-local-src.rs | 4 ++-- tests/rustdoc/trait-src-link.rs | 12 ++++++------ 23 files changed, 53 insertions(+), 47 deletions(-) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 399730a01c82..ce96d1d0a95c 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -2010,9 +2010,9 @@ fn render_rightside(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, render ); if let Some(link) = src_href { if has_stability { - write!(rightside, " · source") + write!(rightside, " · Source") } else { - write!(rightside, "source") + write!(rightside, "Source") } } if has_stability && has_src_ref { diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index df9776ff5f88..db857745295a 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -185,7 +185,7 @@ h1, h2, h3, h4 { grid-template-columns: minmax(105px, 1fr) minmax(0, max-content); grid-template-rows: minmax(25px, min-content) min-content min-content; padding-bottom: 6px; - margin-bottom: 11px; + margin-bottom: 15px; } .rustdoc-breadcrumbs { grid-area: main-heading-breadcrumbs; @@ -1004,6 +1004,7 @@ nav.sub { display: flex; height: 34px; flex-grow: 1; + margin-bottom: 4px; } .src nav.sub { margin: 0 0 -10px 0; @@ -2253,7 +2254,12 @@ in src-script.js and main.js /* We don't display this button on mobile devices. */ #copy-path { - display: none; + /* display: none; avoided as a layout hack. + When there's one line, we get an effective line-height of 34px, + because that's how big the image is, but if the header wraps, + they're packed more tightly than that. */ + width: 0; + visibility: hidden; } /* Text label takes up too much space at this size. */ diff --git a/src/librustdoc/html/templates/print_item.html b/src/librustdoc/html/templates/print_item.html index f60720b67c64..9fd575b2751e 100644 --- a/src/librustdoc/html/templates/print_item.html +++ b/src/librustdoc/html/templates/print_item.html @@ -26,7 +26,7 @@ {% match src_href %} {% when Some with (href) %} {% if !stability_since_raw.is_empty() +%} · {%+ endif %} - source {#+ #} + Source {#+ #} {% else %} {% endmatch %} {# #} diff --git a/tests/rustdoc-gui/item-info.goml b/tests/rustdoc-gui/item-info.goml index c8aa7b31cadc..1636e1496923 100644 --- a/tests/rustdoc-gui/item-info.goml +++ b/tests/rustdoc-gui/item-info.goml @@ -20,7 +20,7 @@ store-position: ( {"x": second_line_x, "y": second_line_y}, ) assert: |first_line_x| != |second_line_x| && |first_line_x| == 516 && |second_line_x| == 272 -assert: |first_line_y| != |second_line_y| && |first_line_y| == 714 && |second_line_y| == 737 +assert: |first_line_y| != |second_line_y| && |first_line_y| == 718 && |second_line_y| == 741 // Now we ensure that they're not rendered on the same line. set-window-size: (1100, 800) diff --git a/tests/rustdoc-gui/scrape-examples-layout.goml b/tests/rustdoc-gui/scrape-examples-layout.goml index 96c78bbfe8b8..5187ac486b08 100644 --- a/tests/rustdoc-gui/scrape-examples-layout.goml +++ b/tests/rustdoc-gui/scrape-examples-layout.goml @@ -80,8 +80,8 @@ click: ".scraped-example .button-holder .expand" store-value: (offset_y, 4) // First with desktop -assert-position: (".scraped-example", {"y": 252}) -assert-position: (".scraped-example .prev", {"y": 252 + |offset_y|}) +assert-position: (".scraped-example", {"y": 256}) +assert-position: (".scraped-example .prev", {"y": 256 + |offset_y|}) // Gradient background should be at the top of the code block. assert-css: (".scraped-example .example-wrap::before", {"top": "0px"}) @@ -90,8 +90,8 @@ assert-css: (".scraped-example .example-wrap::after", {"bottom": "0px"}) // Then with mobile set-window-size: (600, 600) store-size: (".scraped-example .scraped-example-title", {"height": title_height}) -assert-position: (".scraped-example", {"y": 287}) -assert-position: (".scraped-example .prev", {"y": 287 + |offset_y| + |title_height|}) +assert-position: (".scraped-example", {"y": 291}) +assert-position: (".scraped-example .prev", {"y": 291 + |offset_y| + |title_height|}) define-function: ( "check_title_and_code_position", diff --git a/tests/rustdoc-gui/sidebar-source-code-display.goml b/tests/rustdoc-gui/sidebar-source-code-display.goml index 742453c173b9..1e77bcc22731 100644 --- a/tests/rustdoc-gui/sidebar-source-code-display.goml +++ b/tests/rustdoc-gui/sidebar-source-code-display.goml @@ -141,7 +141,7 @@ click: "#sidebar-button" wait-for-css: (".src .sidebar > *", {"visibility": "hidden"}) // We scroll to line 117 to change the scroll position. scroll-to: '//*[@id="117"]' -store-value: (y_offset, "2570") +store-value: (y_offset, "2578") assert-window-property: {"pageYOffset": |y_offset|} // Expanding the sidebar... click: "#sidebar-button" diff --git a/tests/rustdoc-gui/source-anchor-scroll.goml b/tests/rustdoc-gui/source-anchor-scroll.goml index f87946457051..4ad65bbbd61a 100644 --- a/tests/rustdoc-gui/source-anchor-scroll.goml +++ b/tests/rustdoc-gui/source-anchor-scroll.goml @@ -8,13 +8,13 @@ set-window-size: (600, 800) assert-property: ("html", {"scrollTop": "0"}) click: '//a[text() = "barbar" and @href="#5-7"]' -assert-property: ("html", {"scrollTop": "200"}) +assert-property: ("html", {"scrollTop": "208"}) click: '//a[text() = "bar" and @href="#28-36"]' -assert-property: ("html", {"scrollTop": "231"}) +assert-property: ("html", {"scrollTop": "239"}) click: '//a[normalize-space() = "sub_fn" and @href="#2-4"]' -assert-property: ("html", {"scrollTop": "128"}) +assert-property: ("html", {"scrollTop": "136"}) // We now check that clicking on lines doesn't change the scroll // Extra information: the "sub_fn" function header is on line 1. click: '//*[@id="6"]' -assert-property: ("html", {"scrollTop": "128"}) +assert-property: ("html", {"scrollTop": "136"}) diff --git a/tests/rustdoc-gui/source-code-page.goml b/tests/rustdoc-gui/source-code-page.goml index 095354c2f4c1..afb194625210 100644 --- a/tests/rustdoc-gui/source-code-page.goml +++ b/tests/rustdoc-gui/source-code-page.goml @@ -89,7 +89,7 @@ assert-css: (".src-line-numbers", {"text-align": "right"}) // do anything (and certainly not add a `#NaN` to the URL!). go-to: "file://" + |DOC_PATH| + "/src/test_docs/lib.rs.html" // We use this assert-position to know where we will click. -assert-position: ("//*[@id='1']", {"x": 88, "y": 163}) +assert-position: ("//*[@id='1']", {"x": 88, "y": 171}) // We click on the left of the "1" anchor but still in the "src-line-number" `

`.
 click: (163, 77)
 assert-document-property: ({"URL": "/lib.rs.html"}, ENDS_WITH)
@@ -165,7 +165,7 @@ assert-css: ("nav.sub", {"flex-direction": "row"})
 // offsetTop[nav.sub form] = offsetTop[#main-content] - offsetHeight[nav.sub form] - offsetTop[nav.sub form]
 assert-position: ("nav.sub form", {"y": 15})
 assert-property: ("nav.sub form", {"offsetHeight": 34})
-assert-position: ("h1", {"y": 64})
+assert-position: ("h1", {"y": 68})
 // 15 = 64 - 34 - 15
 
 // Now do the same check on moderately-sized, tablet mobile.
@@ -173,7 +173,7 @@ set-window-size: (700, 700)
 assert-css: ("nav.sub", {"flex-direction": "row"})
 assert-position: ("nav.sub form", {"y": 8})
 assert-property: ("nav.sub form", {"offsetHeight": 34})
-assert-position: ("h1", {"y": 50})
+assert-position: ("h1", {"y": 54})
 // 8 = 50 - 34 - 8
 
 // Check the sidebar directory entries have a marker and spacing (tablet).
diff --git a/tests/rustdoc/anchors.no_const_anchor.html b/tests/rustdoc/anchors.no_const_anchor.html
index 06673d87406c..07a7507fa2ea 100644
--- a/tests/rustdoc/anchors.no_const_anchor.html
+++ b/tests/rustdoc/anchors.no_const_anchor.html
@@ -1 +1 @@
-
source

const YOLO: u32

\ No newline at end of file +
Source

const YOLO: u32

\ No newline at end of file diff --git a/tests/rustdoc/anchors.no_const_anchor2.html b/tests/rustdoc/anchors.no_const_anchor2.html index 73c3d0a807b8..091dac3e4b26 100644 --- a/tests/rustdoc/anchors.no_const_anchor2.html +++ b/tests/rustdoc/anchors.no_const_anchor2.html @@ -1 +1 @@ -
source

pub const X: i32 = 0i32

\ No newline at end of file +
Source

pub const X: i32 = 0i32

\ No newline at end of file diff --git a/tests/rustdoc/anchors.no_method_anchor.html b/tests/rustdoc/anchors.no_method_anchor.html index e8b61caa1c13..89f9898624c0 100644 --- a/tests/rustdoc/anchors.no_method_anchor.html +++ b/tests/rustdoc/anchors.no_method_anchor.html @@ -1 +1 @@ -
source

pub fn new() -> Self

\ No newline at end of file +
Source

pub fn new() -> Self

\ No newline at end of file diff --git a/tests/rustdoc/anchors.no_trait_method_anchor.html b/tests/rustdoc/anchors.no_trait_method_anchor.html index abdb17c27dc1..51656a3e58f4 100644 --- a/tests/rustdoc/anchors.no_trait_method_anchor.html +++ b/tests/rustdoc/anchors.no_trait_method_anchor.html @@ -1 +1 @@ -
source

fn bar()

\ No newline at end of file +
Source

fn bar()

\ No newline at end of file diff --git a/tests/rustdoc/anchors.no_tymethod_anchor.html b/tests/rustdoc/anchors.no_tymethod_anchor.html index 23f4277c5b52..49ee624bdbc6 100644 --- a/tests/rustdoc/anchors.no_tymethod_anchor.html +++ b/tests/rustdoc/anchors.no_tymethod_anchor.html @@ -1 +1 @@ -
source

fn foo()

\ No newline at end of file +
Source

fn foo()

\ No newline at end of file diff --git a/tests/rustdoc/anchors.no_type_anchor.html b/tests/rustdoc/anchors.no_type_anchor.html index 62b9295508fb..c5ac3c93818b 100644 --- a/tests/rustdoc/anchors.no_type_anchor.html +++ b/tests/rustdoc/anchors.no_type_anchor.html @@ -1 +1 @@ -
source

type T

\ No newline at end of file +
Source

type T

\ No newline at end of file diff --git a/tests/rustdoc/anchors.no_type_anchor2.html b/tests/rustdoc/anchors.no_type_anchor2.html index 9127104ded4a..14dd31d87b64 100644 --- a/tests/rustdoc/anchors.no_type_anchor2.html +++ b/tests/rustdoc/anchors.no_type_anchor2.html @@ -1 +1 @@ -
source

pub type Y = u32

\ No newline at end of file +
Source

pub type Y = u32

\ No newline at end of file diff --git a/tests/rustdoc/assoc-type-source-link.rs b/tests/rustdoc/assoc-type-source-link.rs index 34b156b96495..a955a67a4579 100644 --- a/tests/rustdoc/assoc-type-source-link.rs +++ b/tests/rustdoc/assoc-type-source-link.rs @@ -8,7 +8,7 @@ pub struct Bar; impl Bar { - //@ has - '//*[@id="implementations-list"]//*[@id="associatedtype.Y"]/a' 'source' + //@ has - '//*[@id="implementations-list"]//*[@id="associatedtype.Y"]/a' 'Source' //@ has - '//*[@id="implementations-list"]//*[@id="associatedtype.Y"]/a/@href' \ // '../src/foo/assoc-type-source-link.rs.html#14' pub type Y = u8; @@ -19,7 +19,7 @@ pub trait Foo { } impl Foo for Bar { - //@ has - '//*[@id="trait-implementations-list"]//*[@id="associatedtype.Z"]/a' 'source' + //@ has - '//*[@id="trait-implementations-list"]//*[@id="associatedtype.Z"]/a' 'Source' //@ has - '//*[@id="trait-implementations-list"]//*[@id="associatedtype.Z"]/a/@href' \ // '../src/foo/assoc-type-source-link.rs.html#25' type Z = u8; diff --git a/tests/rustdoc/ensure-src-link.rs b/tests/rustdoc/ensure-src-link.rs index 4156fdcba593..f70902b1756f 100644 --- a/tests/rustdoc/ensure-src-link.rs +++ b/tests/rustdoc/ensure-src-link.rs @@ -2,5 +2,5 @@ // This test ensures that the [src] link is present on traits items. -//@ has foo/trait.Iterator.html '//*[@id="method.zip"]//a[@class="src"]' "source" +//@ has foo/trait.Iterator.html '//*[@id="method.zip"]//a[@class="src"]' "Source" pub use std::iter::Iterator; diff --git a/tests/rustdoc/external-macro-src.rs b/tests/rustdoc/external-macro-src.rs index f723af57fadb..998687d93bdc 100644 --- a/tests/rustdoc/external-macro-src.rs +++ b/tests/rustdoc/external-macro-src.rs @@ -5,8 +5,8 @@ #[macro_use] extern crate external_macro_src; -//@ has foo/index.html '//a[@href="../src/foo/external-macro-src.rs.html#3-12"]' 'source' +//@ has foo/index.html '//a[@href="../src/foo/external-macro-src.rs.html#3-12"]' 'Source' //@ has foo/struct.Foo.html -//@ has - '//a[@href="../src/foo/external-macro-src.rs.html#12"]' 'source' +//@ has - '//a[@href="../src/foo/external-macro-src.rs.html#12"]' 'Source' make_foo!(); diff --git a/tests/rustdoc/source-version-separator.rs b/tests/rustdoc/source-version-separator.rs index 9709bbe3c718..78b9d364d215 100644 --- a/tests/rustdoc/source-version-separator.rs +++ b/tests/rustdoc/source-version-separator.rs @@ -3,23 +3,23 @@ #![feature(staged_api)] //@ has foo/trait.Bar.html -//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · Source' #[stable(feature = "bar", since = "1.0")] pub trait Bar { - //@ has - '//*[@id="tymethod.foo"]/*[@class="rightside"]' '3.0.0 · source' + //@ has - '//*[@id="tymethod.foo"]/*[@class="rightside"]' '3.0.0 · Source' #[stable(feature = "foobar", since = "3.0")] fn foo(); } -//@ has - '//div[@id="implementors-list"]//*[@class="rightside"]' '4.0.0 · source' +//@ has - '//div[@id="implementors-list"]//*[@class="rightside"]' '4.0.0 · Source' //@ has foo/struct.Foo.html -//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · Source' #[stable(feature = "baz", since = "1.0")] pub struct Foo; impl Foo { - //@ has - '//*[@id="method.foofoo"]/*[@class="rightside"]' '3.0.0 · source' + //@ has - '//*[@id="method.foofoo"]/*[@class="rightside"]' '3.0.0 · Source' #[stable(feature = "foobar", since = "3.0")] pub fn foofoo() {} } diff --git a/tests/rustdoc/src-link-external-macro-26606.rs b/tests/rustdoc/src-link-external-macro-26606.rs index b5662be9b2d5..0ce829f06f52 100644 --- a/tests/rustdoc/src-link-external-macro-26606.rs +++ b/tests/rustdoc/src-link-external-macro-26606.rs @@ -10,5 +10,5 @@ extern crate issue_26606_macro; //@ has issue_26606/constant.FOO.html -//@ has - '//a[@href="../src/issue_26606/src-link-external-macro-26606.rs.html#14"]' 'source' +//@ has - '//a[@href="../src/issue_26606/src-link-external-macro-26606.rs.html#14"]' 'Source' make_item!(FOO); diff --git a/tests/rustdoc/src-links-auto-impls.rs b/tests/rustdoc/src-links-auto-impls.rs index dd07f85eee7d..5a777f59b7e5 100644 --- a/tests/rustdoc/src-links-auto-impls.rs +++ b/tests/rustdoc/src-links-auto-impls.rs @@ -2,11 +2,11 @@ //@ has foo/struct.Unsized.html //@ has - '//*[@id="impl-Sized-for-Unsized"]/h3[@class="code-header"]' 'impl !Sized for Unsized' -//@ !has - '//*[@id="impl-Sized-for-Unsized"]//a[@class="src"]' 'source' +//@ !has - '//*[@id="impl-Sized-for-Unsized"]//a[@class="src"]' 'Source' //@ has - '//*[@id="impl-Sync-for-Unsized"]/h3[@class="code-header"]' 'impl Sync for Unsized' -//@ !has - '//*[@id="impl-Sync-for-Unsized"]//a[@class="src"]' 'source' +//@ !has - '//*[@id="impl-Sync-for-Unsized"]//a[@class="src"]' 'Source' //@ has - '//*[@id="impl-Any-for-T"]/h3[@class="code-header"]' 'impl Any for T' -//@ has - '//*[@id="impl-Any-for-T"]//a[@class="src rightside"]' 'source' +//@ has - '//*[@id="impl-Any-for-T"]//a[@class="src rightside"]' 'Source' pub struct Unsized { data: [u8], } diff --git a/tests/rustdoc/thread-local-src.rs b/tests/rustdoc/thread-local-src.rs index b23a9a48654f..16509e8514d3 100644 --- a/tests/rustdoc/thread-local-src.rs +++ b/tests/rustdoc/thread-local-src.rs @@ -1,6 +1,6 @@ #![crate_name = "foo"] -//@ has foo/index.html '//a[@href="../src/foo/thread-local-src.rs.html#1-6"]' 'source' +//@ has foo/index.html '//a[@href="../src/foo/thread-local-src.rs.html#1-6"]' 'Source' -//@ has foo/constant.FOO.html '//a[@href="../src/foo/thread-local-src.rs.html#6"]' 'source' +//@ has foo/constant.FOO.html '//a[@href="../src/foo/thread-local-src.rs.html#6"]' 'Source' thread_local!(pub static FOO: bool = false); diff --git a/tests/rustdoc/trait-src-link.rs b/tests/rustdoc/trait-src-link.rs index 7c3afb7d7d38..7bf883d52da1 100644 --- a/tests/rustdoc/trait-src-link.rs +++ b/tests/rustdoc/trait-src-link.rs @@ -1,26 +1,26 @@ #![crate_name = "quix"] pub trait Foo { - //@ has quix/trait.Foo.html '//a[@href="../src/quix/trait-src-link.rs.html#4"]' 'source' + //@ has quix/trait.Foo.html '//a[@href="../src/quix/trait-src-link.rs.html#4"]' 'Source' fn required(); - //@ has quix/trait.Foo.html '//a[@href="../src/quix/trait-src-link.rs.html#7"]' 'source' + //@ has quix/trait.Foo.html '//a[@href="../src/quix/trait-src-link.rs.html#7"]' 'Source' fn provided() {} } pub struct Bar; impl Foo for Bar { - //@ has quix/struct.Bar.html '//a[@href="../src/quix/trait-src-link.rs.html#14"]' 'source' + //@ has quix/struct.Bar.html '//a[@href="../src/quix/trait-src-link.rs.html#14"]' 'Source' fn required() {} - //@ has quix/struct.Bar.html '//a[@href="../src/quix/trait-src-link.rs.html#7"]' 'source' + //@ has quix/struct.Bar.html '//a[@href="../src/quix/trait-src-link.rs.html#7"]' 'Source' } pub struct Baz; impl Foo for Baz { - //@ has quix/struct.Baz.html '//a[@href="../src/quix/trait-src-link.rs.html#22"]' 'source' + //@ has quix/struct.Baz.html '//a[@href="../src/quix/trait-src-link.rs.html#22"]' 'Source' fn required() {} - //@ has quix/struct.Baz.html '//a[@href="../src/quix/trait-src-link.rs.html#25"]' 'source' + //@ has quix/struct.Baz.html '//a[@href="../src/quix/trait-src-link.rs.html#25"]' 'Source' fn provided() {} } From c93514b67c51b123abd29d591f57abfdb81f8c03 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Wed, 23 Oct 2024 16:37:42 -0700 Subject: [PATCH 189/366] fix: Add missing cfg flags for `core` crate Some types in `core` are conditionally compiled based on `target_has_atomic` or `target_has_atomic_load_store` without an argument, for example `AtomicU64`. This is less noticeable in Cargo projects, where rust-analyzer adds the output `RUSTC_BOOTSTRAP=1 cargo rustc --print cfg` so it gets the full set of cfg flags. This fixes go-to-definition on `std::sync::atomic::AtomicU64` in non-cargo projects. --- .../rust-analyzer/crates/project-model/src/rustc_cfg.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/crates/project-model/src/rustc_cfg.rs b/src/tools/rust-analyzer/crates/project-model/src/rustc_cfg.rs index aa73ff891004..bc1f0e6fbf26 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/rustc_cfg.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/rustc_cfg.rs @@ -24,14 +24,15 @@ pub(crate) fn get( config: RustcCfgConfig<'_>, ) -> Vec { let _p = tracing::info_span!("rustc_cfg::get").entered(); - let mut res: Vec<_> = Vec::with_capacity(6 * 2 + 1); + let mut res: Vec<_> = Vec::with_capacity(7 * 2 + 1); // Some nightly-only cfgs, which are required for stdlib res.push(CfgAtom::Flag(Symbol::intern("target_thread_local"))); - for ty in ["8", "16", "32", "64", "cas", "ptr"] { - for key in ["target_has_atomic", "target_has_atomic_load_store"] { + for key in ["target_has_atomic", "target_has_atomic_load_store"] { + for ty in ["8", "16", "32", "64", "cas", "ptr"] { res.push(CfgAtom::KeyValue { key: Symbol::intern(key), value: Symbol::intern(ty) }); } + res.push(CfgAtom::Flag(Symbol::intern(key))); } let rustc_cfgs = get_rust_cfgs(target, extra_env, config); From 4e1b3ab0e7965b8cce016f1ca01cd2df37e11635 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 24 Oct 2024 00:41:27 +0000 Subject: [PATCH 190/366] Print safety correctly in extern static items --- compiler/rustc_ast_pretty/src/pprust/state/item.rs | 7 ++++++- tests/ui/unpretty/extern-static.rs | 6 ++++++ tests/ui/unpretty/extern-static.stdout | 6 ++++++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 tests/ui/unpretty/extern-static.rs create mode 100644 tests/ui/unpretty/extern-static.stdout diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 8217b6df5b47..8279c66836c0 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -38,7 +38,6 @@ impl<'a> State<'a> { self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs); } ast::ForeignItemKind::Static(box ast::StaticItem { ty, mutability, expr, safety }) => { - self.print_safety(*safety); self.print_item_const( ident, Some(*mutability), @@ -46,6 +45,7 @@ impl<'a> State<'a> { ty, expr.as_deref(), vis, + *safety, ast::Defaultness::Final, ) } @@ -84,10 +84,12 @@ impl<'a> State<'a> { ty: &ast::Ty, body: Option<&ast::Expr>, vis: &ast::Visibility, + safety: ast::Safety, defaultness: ast::Defaultness, ) { self.head(""); self.print_visibility(vis); + self.print_safety(safety); self.print_defaultness(defaultness); let leading = match mutbl { None => "const", @@ -181,6 +183,7 @@ impl<'a> State<'a> { ty, body.as_deref(), &item.vis, + ast::Safety::Default, ast::Defaultness::Final, ); } @@ -192,6 +195,7 @@ impl<'a> State<'a> { ty, expr.as_deref(), &item.vis, + ast::Safety::Default, *defaultness, ); } @@ -549,6 +553,7 @@ impl<'a> State<'a> { ty, expr.as_deref(), vis, + ast::Safety::Default, *defaultness, ); } diff --git a/tests/ui/unpretty/extern-static.rs b/tests/ui/unpretty/extern-static.rs new file mode 100644 index 000000000000..fbd605b12cae --- /dev/null +++ b/tests/ui/unpretty/extern-static.rs @@ -0,0 +1,6 @@ +//@ compile-flags: -Zunpretty=normal +//@ check-pass + +unsafe extern "C" { + pub unsafe static STATIC: (); +} diff --git a/tests/ui/unpretty/extern-static.stdout b/tests/ui/unpretty/extern-static.stdout new file mode 100644 index 000000000000..fbd605b12cae --- /dev/null +++ b/tests/ui/unpretty/extern-static.stdout @@ -0,0 +1,6 @@ +//@ compile-flags: -Zunpretty=normal +//@ check-pass + +unsafe extern "C" { + pub unsafe static STATIC: (); +} From d8dc31fd3d2a03bc4b01974328c92d2ffb2f4fea Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 23 Oct 2024 23:49:46 +0000 Subject: [PATCH 191/366] Consider param-env candidates even if they have errors --- .../src/traits/select/candidate_assembly.rs | 1 - tests/crashes/110630.rs | 28 ---------------- tests/crashes/115808.rs | 27 ---------------- tests/crashes/121052.rs | 32 ------------------- .../in-trait/unconstrained-impl-region.rs | 1 - .../in-trait/unconstrained-impl-region.stderr | 17 ++-------- .../error-reporting/apit-with-bad-path.rs | 10 ++++++ .../error-reporting/apit-with-bad-path.stderr | 14 ++++++++ .../where-clause-with-bad-path.rs | 10 ++++++ .../where-clause-with-bad-path.stderr | 14 ++++++++ 10 files changed, 50 insertions(+), 104 deletions(-) delete mode 100644 tests/crashes/110630.rs delete mode 100644 tests/crashes/115808.rs delete mode 100644 tests/crashes/121052.rs create mode 100644 tests/ui/traits/error-reporting/apit-with-bad-path.rs create mode 100644 tests/ui/traits/error-reporting/apit-with-bad-path.stderr create mode 100644 tests/ui/traits/error-reporting/where-clause-with-bad-path.rs create mode 100644 tests/ui/traits/error-reporting/where-clause-with-bad-path.stderr 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 eea3867190d3..c0122d3d552d 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -244,7 +244,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .param_env .caller_bounds() .iter() - .filter(|p| !p.references_error()) .filter_map(|p| p.as_trait_clause()) // Micro-optimization: filter out predicates relating to different traits. .filter(|p| p.def_id() == stack.obligation.predicate.def_id()) diff --git a/tests/crashes/110630.rs b/tests/crashes/110630.rs deleted file mode 100644 index f17f6f0781f3..000000000000 --- a/tests/crashes/110630.rs +++ /dev/null @@ -1,28 +0,0 @@ -//@ known-bug: #110630 - -#![feature(generic_const_exprs)] - -use std::ops::Mul; - -pub trait Indices { - const NUM_ELEMS: usize = I::NUM_ELEMS * N; -} - -pub trait Concat { - type Output; -} - -pub struct Tensor, const N: usize> -where - [u8; I::NUM_ELEMS]: Sized, {} - -impl, J: Indices, const N: usize> Mul> for Tensor -where - I: Concat, - >::Output: Indices, - [u8; I::NUM_ELEMS]: Sized, - [u8; J::NUM_ELEMS]: Sized, - [u8; >::Output::NUM_ELEMS]: Sized, -{ - type Output = Tensor<>::Output, N>; -} diff --git a/tests/crashes/115808.rs b/tests/crashes/115808.rs deleted file mode 100644 index 79196ac9c654..000000000000 --- a/tests/crashes/115808.rs +++ /dev/null @@ -1,27 +0,0 @@ -//@ known-bug: #115808 -#![feature(generic_const_exprs)] - -use std::ops::Mul; - -pub trait Indices { - const NUM_ELEMS: usize; -} - -pub trait Concat { - type Output; -} - -pub struct Tensor, const N: usize> -where - [u8; I::NUM_ELEMS]: Sized, {} - -impl, J: Indices, const N: usize> Mul> for Tensor -where - I: Concat, - >::Output: Indices, - [u8; I::NUM_ELEMS]: Sized, - [u8; J::NUM_ELEMS]: Sized, - [u8; >::Output::NUM_ELEMS]: Sized, -{ - type Output = Tensor<>::Output, N>; -} diff --git a/tests/crashes/121052.rs b/tests/crashes/121052.rs deleted file mode 100644 index 5d16b06db237..000000000000 --- a/tests/crashes/121052.rs +++ /dev/null @@ -1,32 +0,0 @@ -//@ known-bug: #121052 -#![feature(generic_const_exprs, with_negative_coherence)] - -use std::ops::Mul; - -pub trait Indices { - const NUM_ELEMS: usize; -} - -impl, J: Indices, const N: usize> Mul for Tensor -where - I: Concat, - >::Output: Indices, - [u8; I::NUM_ELEMS]: Sized, - [u8; J::NUM_ELEMS]: Sized, - [u8; >::Output::NUM_ELEMS]: Sized, -{ -} - -pub trait Concat {} - -pub struct Tensor, const N: usize> {} - -impl, J: Indices, const N: usize> Mul for Tensor -where - I: Concat, - >::Output: Indices, - [u8; I::NUM_ELEMS]: Sized, - [u8; J::NUM_ELEMS]: Sized, - [u8; >::Output::NUM_ELEMS]: Sized, -{ -} diff --git a/tests/ui/async-await/in-trait/unconstrained-impl-region.rs b/tests/ui/async-await/in-trait/unconstrained-impl-region.rs index 95ba1f3f2770..9382c2323643 100644 --- a/tests/ui/async-await/in-trait/unconstrained-impl-region.rs +++ b/tests/ui/async-await/in-trait/unconstrained-impl-region.rs @@ -14,7 +14,6 @@ impl<'a> Actor for () { //~^ ERROR the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates type Message = &'a (); async fn on_mount(self, _: impl Inbox<&'a ()>) {} - //~^ ERROR the trait bound `impl Inbox<&'a ()>: Inbox<&'a ()>` is not satisfied } fn main() {} diff --git a/tests/ui/async-await/in-trait/unconstrained-impl-region.stderr b/tests/ui/async-await/in-trait/unconstrained-impl-region.stderr index 80dc5fdc7470..ef7e4ef0eb85 100644 --- a/tests/ui/async-await/in-trait/unconstrained-impl-region.stderr +++ b/tests/ui/async-await/in-trait/unconstrained-impl-region.stderr @@ -1,22 +1,9 @@ -error[E0277]: the trait bound `impl Inbox<&'a ()>: Inbox<&'a ()>` is not satisfied - --> $DIR/unconstrained-impl-region.rs:16:5 - | -LL | async fn on_mount(self, _: impl Inbox<&'a ()>) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Inbox<&'a ()>` is not implemented for `impl Inbox<&'a ()>` - | -note: required by a bound in `<() as Actor>::on_mount` - --> $DIR/unconstrained-impl-region.rs:16:37 - | -LL | async fn on_mount(self, _: impl Inbox<&'a ()>) {} - | ^^^^^^^^^^^^^ required by this bound in `<() as Actor>::on_mount` - error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates --> $DIR/unconstrained-impl-region.rs:13:6 | LL | impl<'a> Actor for () { | ^^ unconstrained lifetime parameter -error: aborting due to 2 previous errors +error: aborting due to 1 previous error -Some errors have detailed explanations: E0207, E0277. -For more information about an error, try `rustc --explain E0207`. +For more information about this error, try `rustc --explain E0207`. diff --git a/tests/ui/traits/error-reporting/apit-with-bad-path.rs b/tests/ui/traits/error-reporting/apit-with-bad-path.rs new file mode 100644 index 000000000000..57184b9d0a97 --- /dev/null +++ b/tests/ui/traits/error-reporting/apit-with-bad-path.rs @@ -0,0 +1,10 @@ +// Ensure that we don't emit an E0270 for "`impl AsRef: AsRef` not satisfied". + +fn foo(filename: impl AsRef) { + //~^ ERROR cannot find type `Path` in this scope + std::fs::write(filename, "hello").unwrap(); +} + +fn main() { + foo("/tmp/hello"); +} diff --git a/tests/ui/traits/error-reporting/apit-with-bad-path.stderr b/tests/ui/traits/error-reporting/apit-with-bad-path.stderr new file mode 100644 index 000000000000..19bd5e78b47f --- /dev/null +++ b/tests/ui/traits/error-reporting/apit-with-bad-path.stderr @@ -0,0 +1,14 @@ +error[E0412]: cannot find type `Path` in this scope + --> $DIR/apit-with-bad-path.rs:3:29 + | +LL | fn foo(filename: impl AsRef) { + | ^^^^ not found in this scope + | +help: consider importing this struct + | +LL + use std::path::Path; + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0412`. diff --git a/tests/ui/traits/error-reporting/where-clause-with-bad-path.rs b/tests/ui/traits/error-reporting/where-clause-with-bad-path.rs new file mode 100644 index 000000000000..cbe14887de4b --- /dev/null +++ b/tests/ui/traits/error-reporting/where-clause-with-bad-path.rs @@ -0,0 +1,10 @@ +// Ensure that we don't emit an E0270 for "`impl AsRef: AsRef` not satisfied". + +fn foo>(filename: T) { + //~^ ERROR cannot find type `Path` in this scope + std::fs::write(filename, "hello").unwrap(); +} + +fn main() { + foo("/tmp/hello"); +} diff --git a/tests/ui/traits/error-reporting/where-clause-with-bad-path.stderr b/tests/ui/traits/error-reporting/where-clause-with-bad-path.stderr new file mode 100644 index 000000000000..1137178f6114 --- /dev/null +++ b/tests/ui/traits/error-reporting/where-clause-with-bad-path.stderr @@ -0,0 +1,14 @@ +error[E0412]: cannot find type `Path` in this scope + --> $DIR/where-clause-with-bad-path.rs:3:17 + | +LL | fn foo>(filename: T) { + | ^^^^ not found in this scope + | +help: consider importing this struct + | +LL + use std::path::Path; + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0412`. From 1920c66a8d96978e0d0e5db318fa3e0fb2e0f37e Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 15 Oct 2024 15:17:25 -0400 Subject: [PATCH 192/366] Plumb through param_env to note_type_err --- .../src/diagnostics/bound_region_errors.rs | 12 +++---- .../src/region_infer/opaque_types.rs | 1 + .../src/check/compare_impl_item.rs | 15 +++++---- compiler/rustc_hir_analysis/src/check/mod.rs | 4 +-- .../src/coherence/builtin.rs | 1 + compiler/rustc_hir_typeck/src/callee.rs | 4 ++- compiler/rustc_hir_typeck/src/coercion.rs | 6 +++- compiler/rustc_hir_typeck/src/demand.rs | 11 +++++-- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 9 ++++-- .../rustc_hir_typeck/src/method/confirm.rs | 8 ++++- compiler/rustc_passes/src/check_attr.rs | 4 +-- .../src/error_reporting/infer/mod.rs | 31 +++++++++++++++---- .../src/error_reporting/infer/region.rs | 12 +++++-- .../traits/fulfillment_errors.rs | 17 ++++++---- .../src/error_reporting/traits/mod.rs | 2 ++ 15 files changed, 98 insertions(+), 39 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index 2437a43bd5a3..2fa752384a16 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -65,6 +65,7 @@ impl<'tcx> UniverseInfo<'tcx> { UniverseInfoInner::RelateTys { expected, found } => { let err = mbcx.infcx.err_ctxt().report_mismatched_types( &cause, + mbcx.param_env, expected, found, TypeError::RegionsPlaceholderMismatch, @@ -480,12 +481,11 @@ fn try_extract_error_from_region_constraints<'a, 'tcx>( .try_report_from_nll() .or_else(|| { if let SubregionOrigin::Subtype(trace) = cause { - Some( - infcx.err_ctxt().report_and_explain_type_error( - *trace, - TypeError::RegionsPlaceholderMismatch, - ), - ) + Some(infcx.err_ctxt().report_and_explain_type_error( + *trace, + infcx.tcx.param_env(generic_param_scope), + TypeError::RegionsPlaceholderMismatch, + )) } else { None } diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index a16c1931a552..abce98265b3c 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -360,6 +360,7 @@ fn check_opaque_type_well_formed<'tcx>( .err_ctxt() .report_mismatched_types( &ObligationCause::misc(definition_span, def_id), + param_env, opaque_ty, definition_ty, err, diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index fc5ec31cda80..7a56b3784f8b 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -282,6 +282,7 @@ fn compare_method_predicate_entailment<'tcx>( let emitted = report_trait_method_mismatch( infcx, cause, + param_env, terr, (trait_m, trait_sig), (impl_m, impl_sig), @@ -575,10 +576,10 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( hir.get_if_local(impl_m.def_id) .and_then(|node| node.fn_decl()) .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)), - Some(infer::ValuePairs::Terms(ExpectedFound { + Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound { expected: trait_return_ty.into(), found: impl_return_ty.into(), - })), + }))), terr, false, ); @@ -602,6 +603,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let emitted = report_trait_method_mismatch( infcx, cause, + param_env, terr, (trait_m, trait_sig), (impl_m, impl_sig), @@ -915,6 +917,7 @@ impl<'tcx> ty::FallibleTypeFolder> for RemapHiddenTyRegions<'tcx> { fn report_trait_method_mismatch<'tcx>( infcx: &InferCtxt<'tcx>, mut cause: ObligationCause<'tcx>, + param_env: ty::ParamEnv<'tcx>, terr: TypeError<'tcx>, (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>), (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>), @@ -1000,10 +1003,10 @@ fn report_trait_method_mismatch<'tcx>( &mut diag, &cause, trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)), - Some(infer::ValuePairs::PolySigs(ExpectedFound { + Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound { expected: ty::Binder::dummy(trait_sig), found: ty::Binder::dummy(impl_sig), - })), + }))), terr, false, ); @@ -1797,10 +1800,10 @@ fn compare_const_predicate_entailment<'tcx>( &mut diag, &cause, trait_c_span.map(|span| (span, Cow::from("type in trait"), false)), - Some(infer::ValuePairs::Terms(ExpectedFound { + Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound { expected: trait_ty.into(), found: impl_ty.into(), - })), + }))), terr, false, ); diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 959b17b2d407..f2f9c69e49f7 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -646,10 +646,10 @@ pub fn check_function_signature<'tcx>( &mut diag, &cause, None, - Some(infer::ValuePairs::PolySigs(ExpectedFound { + Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound { expected: expected_sig, found: actual_sig, - })), + }))), err, false, ); diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 76c75d976ee0..b4f6b5a9dd24 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -364,6 +364,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( .err_ctxt() .report_mismatched_types( &cause, + param_env, mk_ptr(mt_b.ty), target, ty::error::TypeError::Mutability, diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index fa6a86c69118..06e2a5e34934 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -862,7 +862,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } Err(e) => { // FIXME(effects): better diagnostic - self.err_ctxt().report_mismatched_consts(&cause, effect, param, e).emit(); + self.err_ctxt() + .report_mismatched_consts(&cause, self.param_env, effect, param, e) + .emit(); } } } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index de80ccf790c1..6fa958d94960 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1723,6 +1723,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { }) => { err = fcx.err_ctxt().report_mismatched_types( cause, + fcx.param_env, expected, found, coercion_error, @@ -1752,6 +1753,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { }) => { err = fcx.err_ctxt().report_mismatched_types( cause, + fcx.param_env, expected, found, coercion_error, @@ -1787,6 +1789,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { _ => { err = fcx.err_ctxt().report_mismatched_types( cause, + fcx.param_env, expected, found, coercion_error, @@ -1897,7 +1900,8 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { block_or_return_id: hir::HirId, expression: Option<&'tcx hir::Expr<'tcx>>, ) -> Diag<'infcx> { - let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err); + let mut err = + fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err); let due_to_block = matches!(fcx.tcx.hir_node(block_or_return_id), hir::Node::Block(..)); diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 777248ff873d..3399a9fe8807 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -191,7 +191,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.at(cause, self.param_env) .sup(DefineOpaqueTypes::Yes, expected, actual) .map(|infer_ok| self.register_infer_ok_obligations(infer_ok)) - .map_err(|e| self.err_ctxt().report_mismatched_types(cause, expected, actual, e)) + .map_err(|e| { + self.err_ctxt().report_mismatched_types(cause, self.param_env, expected, actual, e) + }) } pub(crate) fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { @@ -218,7 +220,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.at(cause, self.param_env) .eq(DefineOpaqueTypes::Yes, expected, actual) .map(|infer_ok| self.register_infer_ok_obligations(infer_ok)) - .map_err(|e| self.err_ctxt().report_mismatched_types(cause, expected, actual, e)) + .map_err(|e| { + self.err_ctxt().report_mismatched_types(cause, self.param_env, expected, actual, e) + }) } pub(crate) fn demand_coerce( @@ -271,7 +275,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let expr = expr.peel_drop_temps(); let cause = self.misc(expr.span); let expr_ty = self.resolve_vars_if_possible(checked_ty); - let mut err = self.err_ctxt().report_mismatched_types(&cause, expected, expr_ty, e); + let mut err = + self.err_ctxt().report_mismatched_types(&cause, self.param_env, expected, expr_ty, e); self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected, expected_ty_expr, Some(e)); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index f29d6199a875..a6c249da103f 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -827,6 +827,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { formal_and_expected_inputs[mismatch_idx.into()], provided_arg_tys[mismatch_idx.into()].0, ), + self.param_env, terr, ); err.span_label( @@ -912,7 +913,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let trace = mk_trace(provided_span, formal_and_expected_inputs[*expected_idx], provided_ty); if !matches!(trace.cause.as_failure_code(*e), FailureCode::Error0308) { - let mut err = self.err_ctxt().report_and_explain_type_error(trace, *e); + let mut err = + self.err_ctxt().report_and_explain_type_error(trace, self.param_env, *e); suggest_confusable(&mut err); reported = Some(err.emit()); return false; @@ -940,7 +942,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (formal_ty, expected_ty) = formal_and_expected_inputs[*expected_idx]; let (provided_ty, provided_arg_span) = provided_arg_tys[*provided_idx]; let trace = mk_trace(provided_arg_span, (formal_ty, expected_ty), provided_ty); - let mut err = self.err_ctxt().report_and_explain_type_error(trace, *err); + let mut err = + self.err_ctxt().report_and_explain_type_error(trace, self.param_env, *err); self.emit_coerce_suggestions( &mut err, provided_args[*provided_idx], @@ -1113,7 +1116,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &mut err, &trace.cause, None, - Some(trace.values), + Some(self.param_env.and(trace.values)), e, true, ); diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index f4685725dd30..96784fcb61b2 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -538,7 +538,13 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // to the feature, like the self type can't reference method args. if self.tcx.features().arbitrary_self_types() { self.err_ctxt() - .report_mismatched_types(&cause, method_self_ty, self_ty, terr) + .report_mismatched_types( + &cause, + self.param_env, + method_self_ty, + self_ty, + terr, + ) .emit(); } else { // This has/will have errored in wfcheck, which we cannot depend on from here, as typeck on functions diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 864428448238..61e196bdebe6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -2300,10 +2300,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { &mut diag, &cause, None, - Some(ValuePairs::PolySigs(ExpectedFound { + Some(param_env.and(ValuePairs::PolySigs(ExpectedFound { expected: ty::Binder::dummy(expected_sig), found: ty::Binder::dummy(sig), - })), + }))), terr, false, ); diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index df5800ab58a6..fd991100879b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -75,6 +75,7 @@ use crate::errors::{ObligationCauseFailureCode, TypeErrorAdditionalDiags}; use crate::infer; use crate::infer::relate::{self, RelateResult, TypeRelation}; use crate::infer::{InferCtxt, TypeTrace, ValuePairs}; +use crate::solve::deeply_normalize_for_diagnostics; use crate::traits::{ IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, }; @@ -145,21 +146,31 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub fn report_mismatched_types( &self, cause: &ObligationCause<'tcx>, + param_env: ty::ParamEnv<'tcx>, expected: Ty<'tcx>, actual: Ty<'tcx>, err: TypeError<'tcx>, ) -> Diag<'a> { - self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err) + self.report_and_explain_type_error( + TypeTrace::types(cause, true, expected, actual), + param_env, + err, + ) } pub fn report_mismatched_consts( &self, cause: &ObligationCause<'tcx>, + param_env: ty::ParamEnv<'tcx>, expected: ty::Const<'tcx>, actual: ty::Const<'tcx>, err: TypeError<'tcx>, ) -> Diag<'a> { - self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err) + self.report_and_explain_type_error( + TypeTrace::consts(cause, true, expected, actual), + param_env, + err, + ) } pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option> { @@ -1133,7 +1144,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { diag: &mut Diag<'_>, cause: &ObligationCause<'tcx>, secondary_span: Option<(Span, Cow<'static, str>, bool)>, - mut values: Option>, + mut values: Option>>, terr: TypeError<'tcx>, prefer_label: bool, ) { @@ -1241,8 +1252,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } let (expected_found, exp_found, is_simple_error, values) = match values { None => (None, Mismatch::Fixed("type"), false, None), - Some(values) => { - let values = self.resolve_vars_if_possible(values); + Some(ty::ParamEnvAnd { param_env: _, value: values }) => { + let mut values = self.resolve_vars_if_possible(values); let (is_simple_error, exp_found) = match values { ValuePairs::Terms(ExpectedFound { expected, found }) => { match (expected.unpack(), found.unpack()) { @@ -1773,6 +1784,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub fn report_and_explain_type_error( &self, trace: TypeTrace<'tcx>, + param_env: ty::ParamEnv<'tcx>, terr: TypeError<'tcx>, ) -> Diag<'a> { debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr); @@ -1784,7 +1796,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.type_error_additional_suggestions(&trace, terr), ); let mut diag = self.dcx().create_err(failure_code); - self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false); + self.note_type_err( + &mut diag, + &trace.cause, + None, + Some(param_env.and(trace.values)), + terr, + false, + ); diag } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index 94610a9e0e65..833358b2e14d 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -295,7 +295,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let mut err = match origin { infer::Subtype(box trace) => { let terr = TypeError::RegionsDoesNotOutlive(sup, sub); - let mut err = self.report_and_explain_type_error(trace, terr); + let mut err = self.report_and_explain_type_error( + trace, + self.tcx.param_env(generic_param_scope), + terr, + ); match (*sub, *sup) { (ty::RePlaceholder(_), ty::RePlaceholder(_)) => {} (ty::RePlaceholder(_), _) => { @@ -646,7 +650,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } infer::Subtype(box trace) => { let terr = TypeError::RegionsPlaceholderMismatch; - return self.report_and_explain_type_error(trace, terr); + return self.report_and_explain_type_error( + trace, + self.tcx.param_env(generic_param_scope), + terr, + ); } _ => { return self.report_concrete_failure( diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 9ee4963a3603..6ef64c3ed80a 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -1290,7 +1290,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ( Some(( data.projection_term, - false, self.resolve_vars_if_possible(normalized_term), data.term, )), @@ -1335,7 +1334,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { derive_better_type_error(lhs, rhs) { ( - Some((lhs, true, self.resolve_vars_if_possible(expected_term), rhs)), + Some((lhs, self.resolve_vars_if_possible(expected_term), rhs)), better_type_err, ) } else if let Some(rhs) = rhs.to_alias_term() @@ -1343,7 +1342,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { derive_better_type_error(rhs, lhs) { ( - Some((rhs, true, self.resolve_vars_if_possible(expected_term), lhs)), + Some((rhs, self.resolve_vars_if_possible(expected_term), lhs)), better_type_err, ) } else { @@ -1354,7 +1353,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; let msg = values - .and_then(|(predicate, _, normalized_term, expected_term)| { + .and_then(|(predicate, normalized_term, expected_term)| { self.maybe_detailed_projection_msg(predicate, normalized_term, expected_term) }) .unwrap_or_else(|| { @@ -1431,8 +1430,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &mut diag, &obligation.cause, secondary_span, - values.map(|(_, _, normalized_ty, expected_ty)| { - infer::ValuePairs::Terms(ExpectedFound::new(true, expected_ty, normalized_ty)) + values.map(|(_, normalized_ty, expected_ty)| { + obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new( + true, + expected_ty, + normalized_ty, + ))) }), err, false, @@ -2654,6 +2657,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; self.report_and_explain_type_error( TypeTrace::trait_refs(&cause, true, expected_trait_ref, found_trait_ref), + obligation.param_env, terr, ) } @@ -2744,6 +2748,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { { return Ok(self.report_and_explain_type_error( TypeTrace::trait_refs(&obligation.cause, true, expected_trait_ref, found_trait_ref), + obligation.param_env, ty::error::TypeError::Mismatch, )); } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs index ba57909fc23a..ca23f7765819 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs @@ -287,6 +287,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { FulfillmentErrorCode::Subtype(ref expected_found, ref err) => self .report_mismatched_types( &error.obligation.cause, + error.obligation.param_env, expected_found.expected, expected_found.found, *err, @@ -295,6 +296,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { FulfillmentErrorCode::ConstEquate(ref expected_found, ref err) => { let mut diag = self.report_mismatched_consts( &error.obligation.cause, + error.obligation.param_env, expected_found.expected, expected_found.found, *err, From 4217b8702dcd4e45ea506dd0fc8e1cec6115d52a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 15 Oct 2024 15:24:22 -0400 Subject: [PATCH 193/366] Deeply normalize type trace in type error reporting --- .../src/error_reporting/infer/mod.rs | 5 ++++- .../deeply-normalize-type-expectation.rs | 17 +++++++++++++++++ .../deeply-normalize-type-expectation.stderr | 17 +++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.rs create mode 100644 tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.stderr diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index fd991100879b..b9a569d25e32 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -1252,8 +1252,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } let (expected_found, exp_found, is_simple_error, values) = match values { None => (None, Mismatch::Fixed("type"), false, None), - Some(ty::ParamEnvAnd { param_env: _, value: values }) => { + Some(ty::ParamEnvAnd { param_env, value: values }) => { let mut values = self.resolve_vars_if_possible(values); + if self.next_trait_solver() { + values = deeply_normalize_for_diagnostics(self, param_env, values); + } let (is_simple_error, exp_found) = match values { ValuePairs::Terms(ExpectedFound { expected, found }) => { match (expected.unpack(), found.unpack()) { diff --git a/tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.rs b/tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.rs new file mode 100644 index 000000000000..5c53b745933b --- /dev/null +++ b/tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.rs @@ -0,0 +1,17 @@ +//@ compile-flags: -Znext-solver + +// Make sure we try to mention a deeply normalized type in a type mismatch error. + +trait Mirror { + type Assoc; +} +impl Mirror for T { + type Assoc = T; +} + +fn needs(_: ::Assoc) {} + +fn main() { + needs::(()); + //~^ ERROR mismatched types +} diff --git a/tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.stderr b/tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.stderr new file mode 100644 index 000000000000..88643945863d --- /dev/null +++ b/tests/ui/traits/next-solver/diagnostics/deeply-normalize-type-expectation.stderr @@ -0,0 +1,17 @@ +error[E0308]: mismatched types + --> $DIR/deeply-normalize-type-expectation.rs:15:18 + | +LL | needs::(()); + | ------------ ^^ expected `i32`, found `()` + | | + | arguments to this function are incorrect + | +note: function defined here + --> $DIR/deeply-normalize-type-expectation.rs:12:4 + | +LL | fn needs(_: ::Assoc) {} + | ^^^^^ ----------------------- + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. From 464b2425d810a97450bf2e45f39fc70b5203268c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Thu, 24 Oct 2024 11:03:22 +0800 Subject: [PATCH 194/366] compiletest: suppress Windows Error Reporting (WER) for `run-make` tests --- src/tools/compiletest/src/runtest.rs | 20 +++++++++++++------ src/tools/compiletest/src/runtest/run_make.rs | 6 +++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 7db37af60d2c..74e5ce67f5b3 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -59,7 +59,7 @@ fn disable_error_reporting R, R>(f: F) -> R { use std::sync::Mutex; use windows::Win32::System::Diagnostics::Debug::{ - SEM_NOGPFAULTERRORBOX, SetErrorMode, THREAD_ERROR_MODE, + SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode, THREAD_ERROR_MODE, }; static LOCK: Mutex<()> = Mutex::new(()); @@ -67,13 +67,21 @@ fn disable_error_reporting R, R>(f: F) -> R { // Error mode is a global variable, so lock it so only one thread will change it let _lock = LOCK.lock().unwrap(); - // Tell Windows to not show any UI on errors (such as terminating abnormally). - // This is important for running tests, since some of them use abnormal - // termination by design. This mode is inherited by all child processes. + // Tell Windows to not show any UI on errors (such as terminating abnormally). This is important + // for running tests, since some of them use abnormal termination by design. This mode is + // inherited by all child processes. + // + // Note that `run-make` tests require `SEM_FAILCRITICALERRORS` in addition to suppress Windows + // Error Reporting (WER) error dialogues that come from "critical failures" such as missing + // DLLs. + // + // See and + // . unsafe { - let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags + // read inherited flags + let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); let old_mode = THREAD_ERROR_MODE(old_mode); - SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX); + SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); let r = f(); SetErrorMode(old_mode); r diff --git a/src/tools/compiletest/src/runtest/run_make.rs b/src/tools/compiletest/src/runtest/run_make.rs index f8ffd0fbe3f7..e7ae773ffa1d 100644 --- a/src/tools/compiletest/src/runtest/run_make.rs +++ b/src/tools/compiletest/src/runtest/run_make.rs @@ -2,7 +2,7 @@ use std::path::Path; use std::process::{Command, Output, Stdio}; use std::{env, fs}; -use super::{ProcRes, TestCx}; +use super::{ProcRes, TestCx, disable_error_reporting}; use crate::util::{copy_dir_all, dylib_env_var}; impl TestCx<'_> { @@ -514,8 +514,8 @@ impl TestCx<'_> { } } - let (Output { stdout, stderr, status }, truncated) = - self.read2_abbreviated(cmd.spawn().expect("failed to spawn `rmake`")); + let proc = disable_error_reporting(|| cmd.spawn().expect("failed to spawn `rmake`")); + let (Output { stdout, stderr, status }, truncated) = self.read2_abbreviated(proc); if !status.success() { let res = ProcRes { status, From 7f74c894b0e31f370b5321d94f2ca2830e1d30fd Mon Sep 17 00:00:00 2001 From: Rain Date: Thu, 17 Oct 2024 12:38:32 -0700 Subject: [PATCH 195/366] [musl] use posix_spawn if a directory change was requested Currently, not all libcs have the `posix_spawn_file_actions_addchdir_np` symbol available to them. So we attempt to do a weak symbol lookup for that function. But that only works if libc is a dynamic library -- with statically linked musl binaries the symbol lookup would never work, so we would never be able to use it even if the musl in use supported the symbol. Now that Rust has a minimum musl version of 1.2.3, all supported musl versions now include this symbol, so we can unconditionally expect it to be there. This symbol was added to libc in https://github.com/rust-lang/libc/pull/3949 -- use it here. I couldn't find any tests for whether the posix_spawn path is used, but I've verified with cargo-nextest that this change works. This is a substantial improvement to nextest's performance with musl. On my workstation with a Ryzen 7950x, against https://github.com/clap-rs/clap at 61f5ee514f8f60ed8f04c6494bdf36c19e7a8126: Before: ``` Summary [ 1.071s] 879 tests run: 879 passed, 0 skipped ``` After: ``` Summary [ 0.392s] 879 tests run: 879 passed, 0 skipped ``` Fixes #99740. --- library/std/src/process/tests.rs | 14 +++++ .../src/sys/pal/unix/process/process_unix.rs | 54 +++++++++++++++---- 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index 88cc95caf407..fb0b495961c3 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -96,9 +96,23 @@ fn stdout_works() { #[test] #[cfg_attr(any(windows, target_os = "vxworks"), ignore)] fn set_current_dir_works() { + // On many Unix platforms this will use the posix_spawn path. let mut cmd = shell_cmd(); cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped()); assert_eq!(run_output(cmd), "/\n"); + + // Also test the fork/exec path by setting a pre_exec function. + #[cfg(unix)] + { + use crate::os::unix::process::CommandExt; + + let mut cmd = shell_cmd(); + cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped()); + unsafe { + cmd.pre_exec(|| Ok(())); + } + assert_eq!(run_output(cmd), "/\n"); + } } #[test] diff --git a/library/std/src/sys/pal/unix/process/process_unix.rs b/library/std/src/sys/pal/unix/process/process_unix.rs index 4551d49e841f..8faf1fda5464 100644 --- a/library/std/src/sys/pal/unix/process/process_unix.rs +++ b/library/std/src/sys/pal/unix/process/process_unix.rs @@ -448,7 +448,6 @@ impl Command { use core::sync::atomic::{AtomicU8, Ordering}; use crate::mem::MaybeUninit; - use crate::sys::weak::weak; use crate::sys::{self, cvt_nz, on_broken_pipe_flag_used}; if self.get_gid().is_some() @@ -462,6 +461,8 @@ impl Command { cfg_if::cfg_if! { if #[cfg(target_os = "linux")] { + use crate::sys::weak::weak; + weak! { fn pidfd_spawnp( *mut libc::c_int, @@ -575,16 +576,44 @@ impl Command { } } - // Solaris, glibc 2.29+, and musl 1.24+ can set a new working directory, - // and maybe others will gain this non-POSIX function too. We'll check - // for this weak symbol as soon as it's needed, so we can return early - // otherwise to do a manual chdir before exec. - weak! { - fn posix_spawn_file_actions_addchdir_np( - *mut libc::posix_spawn_file_actions_t, - *const libc::c_char - ) -> libc::c_int + type PosixSpawnAddChdirFn = unsafe extern "C" fn( + *mut libc::posix_spawn_file_actions_t, + *const libc::c_char, + ) -> libc::c_int; + + /// Get the function pointer for adding a chdir action to a + /// `posix_spawn_file_actions_t`, if available, assuming a dynamic libc. + /// + /// Some platforms can set a new working directory for a spawned process in the + /// `posix_spawn` path. This function looks up the function pointer for adding + /// such an action to a `posix_spawn_file_actions_t` struct. + #[cfg(not(all(target_os = "linux", target_env = "musl")))] + fn get_posix_spawn_addchdir() -> Option { + use crate::sys::weak::weak; + + weak! { + fn posix_spawn_file_actions_addchdir_np( + *mut libc::posix_spawn_file_actions_t, + *const libc::c_char + ) -> libc::c_int + } + + posix_spawn_file_actions_addchdir_np.get() } + + /// Get the function pointer for adding a chdir action to a + /// `posix_spawn_file_actions_t`, if available, on platforms where the function + /// is known to exist. + /// + /// Weak symbol lookup doesn't work with statically linked libcs, so in cases + /// where static linking is possible we need to either check for the presence + /// of the symbol at compile time or know about it upfront. + #[cfg(all(target_os = "linux", target_env = "musl"))] + fn get_posix_spawn_addchdir() -> Option { + // Our minimum required musl supports this function, so we can just use it. + Some(libc::posix_spawn_file_actions_addchdir_np) + } + let addchdir = match self.get_cwd() { Some(cwd) => { if cfg!(target_vendor = "apple") { @@ -597,7 +626,10 @@ impl Command { return Ok(None); } } - match posix_spawn_file_actions_addchdir_np.get() { + // Check for the availability of the posix_spawn addchdir + // function now. If it isn't available, bail and use the + // fork/exec path. + match get_posix_spawn_addchdir() { Some(f) => Some((f, cwd)), None => return Ok(None), } From 3dfc35214509e969cfeec76380af427881a36aa9 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 24 Oct 2024 16:59:59 +1100 Subject: [PATCH 196/366] Replace an FTP link in comments with an equivalent HTTPS link --- compiler/rustc_data_structures/src/graph/dominators/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index 85b030c1a485..53ff67f60e37 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -2,7 +2,7 @@ //! //! Algorithm based on Loukas Georgiadis, //! "Linear-Time Algorithms for Dominators and Related Problems", -//! +//! //! //! Additionally useful is the original Lengauer-Tarjan paper on this subject, //! "A Fast Algorithm for Finding Dominators in a Flowgraph" From 33941d3ba5aa2e9beed85130a27833f3de853d9b Mon Sep 17 00:00:00 2001 From: David Date: Thu, 24 Oct 2024 11:42:11 +0530 Subject: [PATCH 197/366] sanitizer.md: LeakSanitizer is not supported on aarch64 macOS --- src/doc/unstable-book/src/compiler-flags/sanitizer.md | 1 - 1 file changed, 1 deletion(-) diff --git a/src/doc/unstable-book/src/compiler-flags/sanitizer.md b/src/doc/unstable-book/src/compiler-flags/sanitizer.md index 24940f0d6fb9..4679acf0a6a1 100644 --- a/src/doc/unstable-book/src/compiler-flags/sanitizer.md +++ b/src/doc/unstable-book/src/compiler-flags/sanitizer.md @@ -690,7 +690,6 @@ LeakSanitizer is run-time memory leak detector. LeakSanitizer is supported on the following targets: -* `aarch64-apple-darwin` * `aarch64-unknown-linux-gnu` * `x86_64-apple-darwin` * `x86_64-unknown-linux-gnu` From 282f291b7de339951f44e4d0ba6d64571876099a Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 24 Oct 2024 08:15:28 +0200 Subject: [PATCH 198/366] rustc_feature::Features: explain what that 'Option' is about --- compiler/rustc_feature/src/unstable.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 8f4c208f1fbb..8182eb1e9735 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -44,6 +44,8 @@ pub struct Features { } impl Features { + /// `since` should be set for stable features that are nevertheless enabled with a `#[feature]` + /// attribute, indicating since when they are stable. pub fn set_enabled_lang_feature(&mut self, name: Symbol, span: Span, since: Option) { self.enabled_lang_features.push((name, span, since)); self.enabled_features.insert(name); @@ -54,6 +56,10 @@ impl Features { self.enabled_features.insert(name); } + /// Returns a list of triples with: + /// - feature gate name + /// - the span of the `#[feature]` attribute + /// - (for already stable features) the version since which it is stable pub fn enabled_lang_features(&self) -> &Vec<(Symbol, Span, Option)> { &self.enabled_lang_features } From f3d97841a399b23af8f226bffd05d1f2ad428dab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Thu, 24 Oct 2024 10:07:54 +0300 Subject: [PATCH 199/366] Hide default config in Debug impl --- .../crates/rust-analyzer/src/config.rs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs index 518b588cb7d4..f5b0fcecf390 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs @@ -727,7 +727,7 @@ enum RatomlFile { Crate(LocalConfigInput), } -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct Config { /// Projects that have a Cargo.toml or a rust-project.json in a /// parent directory, so we can discover them by walking the @@ -765,6 +765,26 @@ pub struct Config { detached_files: Vec, } +impl fmt::Debug for Config { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Config") + .field("discovered_projects_from_filesystem", &self.discovered_projects_from_filesystem) + .field("discovered_projects_from_command", &self.discovered_projects_from_command) + .field("workspace_roots", &self.workspace_roots) + .field("caps", &self.caps) + .field("root_path", &self.root_path) + .field("snippets", &self.snippets) + .field("visual_studio_code_version", &self.visual_studio_code_version) + .field("client_config", &self.client_config) + .field("user_config", &self.user_config) + .field("ratoml_file", &self.ratoml_file) + .field("source_root_parent_map", &self.source_root_parent_map) + .field("validation_errors", &self.validation_errors) + .field("detached_files", &self.detached_files) + .finish() + } +} + // Delegate capability fetching methods impl std::ops::Deref for Config { type Target = ClientCapabilities; From 97eb4c7135647a4532478af8d81c90b40575c6a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Thu, 24 Oct 2024 10:08:31 +0300 Subject: [PATCH 200/366] Bump smol_str --- src/tools/rust-analyzer/Cargo.lock | 4 ++-- src/tools/rust-analyzer/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index 368e1828953b..8bbccc82aee2 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -1885,9 +1885,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "smol_str" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66eaf762c5af19db3108300515c8aa7a50efc90ff745f4c62288052ebf9fdd25" +checksum = "9676b89cd56310a87b93dec47b11af744f34d5fc9f367b829474eec0a891350d" dependencies = [ "borsh", "serde", diff --git a/src/tools/rust-analyzer/Cargo.toml b/src/tools/rust-analyzer/Cargo.toml index 9db62de9abfc..3c2d3a13b191 100644 --- a/src/tools/rust-analyzer/Cargo.toml +++ b/src/tools/rust-analyzer/Cargo.toml @@ -145,7 +145,7 @@ smallvec = { version = "1.10.0", features = [ "union", "const_generics", ] } -smol_str = "0.3.1" +smol_str = "0.3.2" snap = "1.1.0" text-size = "1.1.1" tracing = "0.1.40" From a16d491054a339c2ad9ee56d8295311eb31b1d42 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 20 Oct 2024 20:22:11 +0000 Subject: [PATCH 201/366] Remove associated type based effects logic --- compiler/rustc_ast_lowering/src/item.rs | 205 ++---------------- compiler/rustc_ast_lowering/src/lib.rs | 20 +- compiler/rustc_feature/src/builtin_attrs.rs | 4 - compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir/src/intravisit.rs | 2 +- compiler/rustc_hir/src/lang_items.rs | 8 - compiler/rustc_hir_analysis/src/bounds.rs | 139 ------------ .../rustc_hir_analysis/src/check/intrinsic.rs | 8 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 7 +- .../src/collect/generics_of.rs | 33 +-- .../src/collect/predicates_of.rs | 21 -- compiler/rustc_hir_analysis/src/delegation.rs | 5 - .../src/hir_ty_lowering/mod.rs | 10 +- compiler/rustc_hir_pretty/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/callee.rs | 35 +-- compiler/rustc_hir_typeck/src/fallback.rs | 29 +-- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 26 +-- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 6 - compiler/rustc_hir_typeck/src/method/mod.rs | 11 - .../src/infer/canonical/canonicalizer.rs | 14 +- .../rustc_infer/src/infer/canonical/mod.rs | 10 - compiler/rustc_infer/src/infer/context.rs | 21 -- compiler/rustc_infer/src/infer/freshen.rs | 9 - compiler/rustc_infer/src/infer/mod.rs | 74 +------ .../src/infer/relate/generalize.rs | 1 - compiler/rustc_infer/src/infer/resolve.rs | 3 - .../rustc_infer/src/infer/snapshot/fudge.rs | 27 +-- .../rustc_infer/src/infer/snapshot/mod.rs | 2 - .../src/infer/snapshot/undo_log.rs | 5 +- compiler/rustc_lint/src/nonstandard_style.rs | 6 +- .../src/rmeta/decoder/cstore_impl.rs | 1 - compiler/rustc_metadata/src/rmeta/encoder.rs | 3 - compiler/rustc_metadata/src/rmeta/mod.rs | 1 - compiler/rustc_middle/src/infer/unify_key.rs | 67 ------ compiler/rustc_middle/src/query/mod.rs | 6 - compiler/rustc_middle/src/ty/context.rs | 7 - compiler/rustc_middle/src/ty/diagnostics.rs | 3 - compiler/rustc_middle/src/ty/flags.rs | 4 +- compiler/rustc_middle/src/ty/generic_args.rs | 9 +- compiler/rustc_middle/src/ty/generics.rs | 19 +- compiler/rustc_middle/src/ty/instance.rs | 1 - compiler/rustc_middle/src/ty/util.rs | 46 +--- compiler/rustc_monomorphize/src/collector.rs | 1 - .../src/canonicalizer.rs | 1 - .../rustc_next_trait_solver/src/resolve.rs | 3 - .../src/solve/assembly/mod.rs | 8 - .../rustc_next_trait_solver/src/solve/mod.rs | 6 - .../src/solve/normalizes_to/mod.rs | 62 ------ .../src/solve/trait_goals.rs | 41 ---- .../rustc_smir/src/rustc_smir/convert/ty.rs | 3 +- compiler/rustc_span/src/symbol.rs | 9 - .../traits/fulfillment_errors.rs | 44 +--- .../src/traits/fulfill.rs | 1 - .../src/traits/select/candidate_assembly.rs | 2 +- .../src/traits/select/mod.rs | 3 +- compiler/rustc_ty_utils/src/assoc.rs | 139 +----------- compiler/rustc_type_ir/src/canonical.rs | 22 +- compiler/rustc_type_ir/src/const_kind.rs | 23 +- compiler/rustc_type_ir/src/effects.rs | 59 ----- compiler/rustc_type_ir/src/elaborate.rs | 65 ------ compiler/rustc_type_ir/src/infer_ctxt.rs | 10 - compiler/rustc_type_ir/src/lang_items.rs | 7 - compiler/rustc_type_ir/src/lib.rs | 2 - compiler/rustc_type_ir/src/relate/combine.rs | 28 +-- compiler/stable_mir/src/ty.rs | 1 - library/core/src/marker.rs | 44 ---- src/librustdoc/clean/auto_trait.rs | 2 +- src/librustdoc/clean/mod.rs | 6 +- src/librustdoc/clean/types.rs | 3 +- src/librustdoc/clean/utils.rs | 4 - .../clippy_utils/src/ty/type_certainty/mod.rs | 14 +- .../const-traits/const-fns-are-early-bound.rs | 48 ---- .../traits/const-traits/effects/minicore.rs | 32 --- 73 files changed, 85 insertions(+), 1519 deletions(-) delete mode 100644 compiler/rustc_type_ir/src/effects.rs diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index c43106c6e5f6..97fa90d340ea 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -57,7 +57,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { owner: NodeId, f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>, ) { - let mut lctx = LoweringContext::new(self.tcx, self.resolver, self.ast_index); + let mut lctx = LoweringContext::new(self.tcx, self.resolver); lctx.with_hir_id_owner(owner, |lctx| f(lctx)); for (def_id, info) in lctx.children { @@ -193,8 +193,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::Const(box ast::ConstItem { generics, ty, expr, .. }) => { let (generics, (ty, body_id)) = self.lower_generics( generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -225,16 +223,9 @@ impl<'hir> LoweringContext<'_, 'hir> { ); let itctx = ImplTraitContext::Universal; - let (generics, decl) = - this.lower_generics(generics, header.constness, false, id, itctx, |this| { - this.lower_fn_decl( - decl, - id, - *fn_sig_span, - FnDeclKind::Fn, - coroutine_kind, - ) - }); + let (generics, decl) = this.lower_generics(generics, id, itctx, |this| { + this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_kind) + }); let sig = hir::FnSig { decl, header: this.lower_fn_header(*header, hir::Safety::Safe), @@ -269,8 +260,6 @@ impl<'hir> LoweringContext<'_, 'hir> { add_ty_alias_where_clause(&mut generics, *where_clauses, true); let (generics, ty) = self.lower_generics( &generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| match ty { @@ -294,8 +283,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::Enum(enum_definition, generics) => { let (generics, variants) = self.lower_generics( generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -309,8 +296,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::Struct(struct_def, generics) => { let (generics, struct_def) = self.lower_generics( generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| this.lower_variant_data(hir_id, struct_def), @@ -320,8 +305,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::Union(vdata, generics) => { let (generics, vdata) = self.lower_generics( generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| this.lower_variant_data(hir_id, vdata), @@ -353,7 +336,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // parent lifetime. let itctx = ImplTraitContext::Universal; let (generics, (trait_ref, lowered_ty)) = - self.lower_generics(ast_generics, Const::No, false, id, itctx, |this| { + self.lower_generics(ast_generics, id, itctx, |this| { let modifiers = TraitBoundModifiers { constness: BoundConstness::Never, asyncness: BoundAsyncness::Normal, @@ -405,8 +388,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::Trait(box Trait { is_auto, safety, generics, bounds, items }) => { let (generics, (safety, items, bounds)) = self.lower_generics( generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -426,8 +407,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::TraitAlias(generics, bounds) => { let (generics, bounds) = self.lower_generics( generics, - Const::No, - false, id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -604,50 +583,23 @@ impl<'hir> LoweringContext<'_, 'hir> { ctxt: AssocCtxt, parent_hir: &'hir hir::OwnerInfo<'hir>, ) -> hir::OwnerNode<'hir> { - // Evaluate with the lifetimes in `params` in-scope. - // This is used to track which lifetimes have already been defined, - // and which need to be replicated when lowering an async fn. - let parent_item = parent_hir.node().expect_item(); - let constness = match parent_item.kind { + match parent_item.kind { hir::ItemKind::Impl(impl_) => { self.is_in_trait_impl = impl_.of_trait.is_some(); - // N.B. the impl should always lower to methods that have `const host: bool` params if the trait - // is const. It doesn't matter whether the `impl` itself is const. Disallowing const fn from - // calling non-const impls are done through associated types. - if let Some(def_id) = impl_.of_trait.and_then(|tr| tr.trait_def_id()) { - if let Some(local_def) = def_id.as_local() { - match &self.ast_index[local_def] { - AstOwner::Item(ast::Item { attrs, .. }) => attrs - .iter() - .find(|attr| attr.has_name(sym::const_trait)) - .map_or(Const::No, |attr| Const::Yes(attr.span)), - _ => Const::No, - } - } else if self.tcx.is_const_trait(def_id) { - // FIXME(effects) span - Const::Yes(self.tcx.def_ident_span(def_id).unwrap()) - } else { - Const::No - } - } else { - Const::No - } } - hir::ItemKind::Trait(_, _, _, _, _) => parent_hir - .attrs - .get(parent_item.hir_id().local_id) - .iter() - .find(|attr| attr.has_name(sym::const_trait)) - .map_or(Const::No, |attr| Const::Yes(attr.span)), + hir::ItemKind::Trait(_, _, _, _, _) => {} kind => { span_bug!(item.span, "assoc item has unexpected kind of parent: {}", kind.descr()) } - }; + } + // Evaluate with the lifetimes in `params` in-scope. + // This is used to track which lifetimes have already been defined, + // and which need to be replicated when lowering an async fn. match ctxt { - AssocCtxt::Trait => hir::OwnerNode::TraitItem(self.lower_trait_item(item, constness)), - AssocCtxt::Impl => hir::OwnerNode::ImplItem(self.lower_impl_item(item, constness)), + AssocCtxt::Trait => hir::OwnerNode::TraitItem(self.lower_trait_item(item)), + AssocCtxt::Impl => hir::OwnerNode::ImplItem(self.lower_impl_item(item)), } } @@ -663,7 +615,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let fdec = &sig.decl; let itctx = ImplTraitContext::Universal; let (generics, (decl, fn_args)) = - self.lower_generics(generics, Const::No, false, i.id, itctx, |this| { + self.lower_generics(generics, i.id, itctx, |this| { ( // Disallow `impl Trait` in foreign items. this.lower_fn_decl( @@ -775,11 +727,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } } - fn lower_trait_item( - &mut self, - i: &AssocItem, - trait_constness: Const, - ) -> &'hir hir::TraitItem<'hir> { + fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> { let hir_id = self.lower_node_id(i.id); self.lower_attrs(hir_id, &i.attrs); let trait_item_def_id = hir_id.expect_owner(); @@ -788,8 +736,6 @@ impl<'hir> LoweringContext<'_, 'hir> { AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => { let (generics, kind) = self.lower_generics( generics, - Const::No, - false, i.id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -810,7 +756,6 @@ impl<'hir> LoweringContext<'_, 'hir> { i.id, FnDeclKind::Trait, sig.header.coroutine_kind, - trait_constness, ); (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false) } @@ -829,7 +774,6 @@ impl<'hir> LoweringContext<'_, 'hir> { i.id, FnDeclKind::Trait, sig.header.coroutine_kind, - trait_constness, ); (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true) } @@ -838,8 +782,6 @@ impl<'hir> LoweringContext<'_, 'hir> { add_ty_alias_where_clause(&mut generics, *where_clauses, false); let (generics, kind) = self.lower_generics( &generics, - Const::No, - false, i.id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -912,11 +854,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.expr(span, hir::ExprKind::Err(guar)) } - fn lower_impl_item( - &mut self, - i: &AssocItem, - constness_of_trait: Const, - ) -> &'hir hir::ImplItem<'hir> { + fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> { // Since `default impl` is not yet implemented, this is always true in impls. let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); @@ -926,8 +864,6 @@ impl<'hir> LoweringContext<'_, 'hir> { let (generics, kind) = match &i.kind { AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => self.lower_generics( generics, - Const::No, - false, i.id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| { @@ -953,7 +889,6 @@ impl<'hir> LoweringContext<'_, 'hir> { i.id, if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent }, sig.header.coroutine_kind, - constness_of_trait, ); (generics, hir::ImplItemKind::Fn(sig, body_id)) @@ -963,8 +898,6 @@ impl<'hir> LoweringContext<'_, 'hir> { add_ty_alias_where_clause(&mut generics, *where_clauses, false); self.lower_generics( &generics, - Const::No, - false, i.id, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), |this| match ty { @@ -1370,18 +1303,12 @@ impl<'hir> LoweringContext<'_, 'hir> { id: NodeId, kind: FnDeclKind, coroutine_kind: Option, - parent_constness: Const, ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) { let header = self.lower_fn_header(sig.header, hir::Safety::Safe); - // Don't pass along the user-provided constness of trait associated functions; we don't want to - // synthesize a host effect param for them. We reject `const` on them during AST validation. - let constness = - if kind == FnDeclKind::Inherent { sig.header.constness } else { parent_constness }; let itctx = ImplTraitContext::Universal; - let (generics, decl) = - self.lower_generics(generics, constness, kind == FnDeclKind::Impl, id, itctx, |this| { - this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind) - }); + let (generics, decl) = self.lower_generics(generics, id, itctx, |this| { + this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind) + }); (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) }) } @@ -1460,8 +1387,6 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_generics( &mut self, generics: &Generics, - constness: Const, - force_append_constness: bool, parent_node_id: NodeId, itctx: ImplTraitContext, f: impl FnOnce(&mut Self) -> T, @@ -1524,30 +1449,6 @@ impl<'hir> LoweringContext<'_, 'hir> { } } - // Desugar `~const` bound in generics into an additional `const host: bool` param - // if the effects feature is enabled. This needs to be done before we lower where - // clauses since where clauses need to bind to the DefId of the host param - let host_param_parts = if let Const::Yes(span) = constness - // if this comes from implementing a `const` trait, we must force constness to be appended - // to the impl item, no matter whether effects is enabled. - && (self.tcx.features().effects() || force_append_constness) - { - let span = self.lower_span(span); - let param_node_id = self.next_node_id(); - let hir_id = self.next_id(); - let def_id = self.create_def( - self.local_def_id(parent_node_id), - param_node_id, - sym::host, - DefKind::ConstParam, - span, - ); - self.host_param_id = Some(def_id); - Some((span, hir_id, def_id)) - } else { - None - }; - let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new(); predicates.extend(generics.params.iter().filter_map(|param| { self.lower_generic_bound_predicate( @@ -1595,74 +1496,6 @@ impl<'hir> LoweringContext<'_, 'hir> { let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds); predicates.extend(impl_trait_bounds.into_iter()); - if let Some((span, hir_id, def_id)) = host_param_parts { - let const_node_id = self.next_node_id(); - let anon_const_did = - self.create_def(def_id, const_node_id, kw::Empty, DefKind::AnonConst, span); - - let const_id = self.next_id(); - let const_expr_id = self.next_id(); - let bool_id = self.next_id(); - - self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id))); - self.children.push((anon_const_did, hir::MaybeOwner::NonOwner(const_id))); - - let const_body = self.lower_body(|this| { - (&[], hir::Expr { - hir_id: const_expr_id, - kind: hir::ExprKind::Lit( - this.arena.alloc(hir::Lit { node: LitKind::Bool(true), span }), - ), - span, - }) - }); - - let default_ac = self.arena.alloc(hir::AnonConst { - def_id: anon_const_did, - hir_id: const_id, - body: const_body, - span, - }); - let default_ct = self.arena.alloc(hir::ConstArg { - hir_id: self.next_id(), - kind: hir::ConstArgKind::Anon(default_ac), - is_desugared_from_effects: false, - }); - let param = hir::GenericParam { - def_id, - hir_id, - name: hir::ParamName::Plain(Ident { name: sym::host, span }), - span, - kind: hir::GenericParamKind::Const { - ty: self.arena.alloc(self.ty( - span, - hir::TyKind::Path(hir::QPath::Resolved( - None, - self.arena.alloc(hir::Path { - res: Res::PrimTy(hir::PrimTy::Bool), - span, - segments: self.arena.alloc_from_iter([hir::PathSegment { - ident: Ident { name: sym::bool, span }, - hir_id: bool_id, - res: Res::PrimTy(hir::PrimTy::Bool), - args: None, - infer_args: false, - }]), - }), - )), - )), - default: Some(default_ct), - is_host_effect: true, - synthetic: true, - }, - colon_span: None, - pure_wrt_drop: false, - source: hir::GenericParamSource::Generics, - }; - - params.push(param); - } - let lowered_generics = self.arena.alloc(hir::Generics { params: self.arena.alloc_from_iter(params), predicates: self.arena.alloc_from_iter(predicates), diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 7cd0cd1ebcdc..34b8137aea8e 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -154,17 +154,10 @@ struct LoweringContext<'a, 'hir> { /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this /// field from the original parameter 'a to the new parameter 'a1. generics_def_id_map: Vec>, - - host_param_id: Option, - ast_index: &'a IndexSlice>, } impl<'a, 'hir> LoweringContext<'a, 'hir> { - fn new( - tcx: TyCtxt<'hir>, - resolver: &'a mut ResolverAstLowering, - ast_index: &'a IndexSlice>, - ) -> Self { + fn new(tcx: TyCtxt<'hir>, resolver: &'a mut ResolverAstLowering) -> Self { Self { // Pseudo-globals. tcx, @@ -204,8 +197,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // interact with `gen`/`async gen` blocks allow_async_iterator: [sym::gen_future, sym::async_iterator].into(), generics_def_id_map: Default::default(), - host_param_id: None, - ast_index, } } @@ -2054,11 +2045,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { param: &GenericParam, source: hir::GenericParamSource, ) -> hir::GenericParam<'hir> { - let (name, kind) = self.lower_generic_param_kind( - param, - source, - attr::contains_name(¶m.attrs, sym::rustc_runtime), - ); + let (name, kind) = self.lower_generic_param_kind(param, source); let hir_id = self.lower_node_id(param.id); self.lower_attrs(hir_id, ¶m.attrs); @@ -2078,7 +2065,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &mut self, param: &GenericParam, source: hir::GenericParamSource, - is_host_effect: bool, ) -> (hir::ParamName, hir::GenericParamKind<'hir>) { match ¶m.kind { GenericParamKind::Lifetime => { @@ -2144,7 +2130,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ( hir::ParamName::Plain(self.lower_ident(param.ident)), - hir::GenericParamKind::Const { ty, default, is_host_effect, synthetic: false }, + hir::GenericParamKind::Const { ty, default, synthetic: false }, ) } } diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 753195bf691c..5921fbc0fd71 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -838,10 +838,6 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ rustc_const_panic_str, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, INTERNAL_UNSTABLE ), - rustc_attr!( - rustc_runtime, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, INTERNAL_UNSTABLE - ), // ========================================================================== // Internal attributes, Layout related: diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 45be04c6db9c..1c268c8bbe06 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -580,7 +580,6 @@ pub enum GenericParamKind<'hir> { ty: &'hir Ty<'hir>, /// Optional default value for the const generic param default: Option<&'hir ConstArg<'hir>>, - is_host_effect: bool, synthetic: bool, }, } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index ffe519b0e7dd..322f8e2a517c 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -935,7 +935,7 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>( match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { ref default, .. } => visit_opt!(visitor, visit_ty, default), - GenericParamKind::Const { ref ty, ref default, is_host_effect: _, synthetic: _ } => { + GenericParamKind::Const { ref ty, ref default, synthetic: _ } => { try_visit!(visitor.visit_ty(ty)); if let Some(ref default) = default { try_visit!(visitor.visit_const_param_default(param.hir_id, default)); diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index ae046c09ebea..7d81f977c22e 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -415,14 +415,6 @@ language_item_table! { String, sym::String, string, Target::Struct, GenericRequirement::None; CStr, sym::CStr, c_str, Target::Struct, GenericRequirement::None; - - EffectsRuntime, sym::EffectsRuntime, effects_runtime, Target::Struct, GenericRequirement::None; - EffectsNoRuntime, sym::EffectsNoRuntime, effects_no_runtime, Target::Struct, GenericRequirement::None; - EffectsMaybe, sym::EffectsMaybe, effects_maybe, Target::Struct, GenericRequirement::None; - EffectsIntersection, sym::EffectsIntersection, effects_intersection, Target::Trait, GenericRequirement::None; - EffectsIntersectionOutput, sym::EffectsIntersectionOutput, effects_intersection_output, Target::AssocTy, GenericRequirement::None; - EffectsCompat, sym::EffectsCompat, effects_compat, Target::Trait, GenericRequirement::Exact(1); - EffectsTyCompat, sym::EffectsTyCompat, effects_ty_compat, Target::Trait, GenericRequirement::Exact(1); } pub enum GenericRequirement { diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index 77df0cb7ef90..d0c45a7c04c7 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -3,13 +3,8 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_hir::LangItem; -use rustc_hir::def::DefKind; -use rustc_middle::ty::fold::FnMutDelegate; use rustc_middle::ty::{self, Ty, TyCtxt, Upcast}; use rustc_span::Span; -use rustc_span::def_id::DefId; - -use crate::hir_ty_lowering::PredicateFilter; /// Collects together a list of type bounds. These lists of bounds occur in many places /// in Rust's syntax: @@ -47,12 +42,9 @@ impl<'tcx> Bounds<'tcx> { pub(crate) fn push_trait_bound( &mut self, tcx: TyCtxt<'tcx>, - defining_def_id: DefId, bound_trait_ref: ty::PolyTraitRef<'tcx>, span: Span, polarity: ty::PredicatePolarity, - constness: Option, - predicate_filter: PredicateFilter, ) { let clause = ( bound_trait_ref @@ -68,137 +60,6 @@ impl<'tcx> Bounds<'tcx> { } else { self.clauses.push(clause); } - - // FIXME(effects): Lift this out of `push_trait_bound`, and move it somewhere else. - // Perhaps moving this into `lower_poly_trait_ref`, just like we lower associated - // type bounds. - if !tcx.features().effects() { - return; - } - match predicate_filter { - PredicateFilter::SelfOnly | PredicateFilter::SelfThatDefines(_) => { - return; - } - PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => { - // Ok. - } - } - - // For `T: ~const Tr` or `T: const Tr`, we need to add an additional bound on the - // associated type of `` and make sure that the effect is compatible. - let compat_val = match (tcx.def_kind(defining_def_id), constness) { - // FIXME(effects): revisit the correctness of this - (_, Some(ty::BoundConstness::Const)) => tcx.consts.false_, - // body owners that can have trait bounds - ( - DefKind::Const | DefKind::Fn | DefKind::AssocFn, - Some(ty::BoundConstness::ConstIfConst), - ) => tcx.expected_host_effect_param_for_body(defining_def_id), - - (_, None) => { - if !tcx.is_const_trait(bound_trait_ref.def_id()) { - return; - } - tcx.consts.true_ - } - (DefKind::Trait, Some(ty::BoundConstness::ConstIfConst)) => { - // we are in a trait, where `bound_trait_ref` could be: - // (1) a super trait `trait Foo: ~const Bar`. - // - This generates `::Effects: TyCompat<::Effects>` - // - // (2) a where clause `where for<..> Something: ~const Bar`. - // - This generates `for<..> ::Effects: TyCompat<::Effects>` - let Some(own_fx) = tcx.associated_type_for_effects(defining_def_id) else { - tcx.dcx().span_delayed_bug(span, "should not have allowed `~const` on a trait that doesn't have `#[const_trait]`"); - return; - }; - let own_fx_ty = Ty::new_projection( - tcx, - own_fx, - ty::GenericArgs::identity_for_item(tcx, own_fx), - ); - let Some(their_fx) = tcx.associated_type_for_effects(bound_trait_ref.def_id()) - else { - tcx.dcx().span_delayed_bug(span, "`~const` on trait without Effects assoc"); - return; - }; - let their_fx_ty = - Ty::new_projection(tcx, their_fx, bound_trait_ref.skip_binder().args); - let compat = tcx.require_lang_item(LangItem::EffectsTyCompat, Some(span)); - let clause = bound_trait_ref - .map_bound(|_| { - let trait_ref = ty::TraitRef::new(tcx, compat, [own_fx_ty, their_fx_ty]); - ty::ClauseKind::Trait(ty::TraitPredicate { - trait_ref, - polarity: ty::PredicatePolarity::Positive, - }) - }) - .upcast(tcx); - - self.clauses.push((clause, span)); - return; - } - - (DefKind::Impl { of_trait: true }, Some(ty::BoundConstness::ConstIfConst)) => { - // this is a where clause on an impl header. - // push `::Effects` into the set for the `Min` bound. - let Some(assoc) = tcx.associated_type_for_effects(bound_trait_ref.def_id()) else { - tcx.dcx().span_delayed_bug(span, "`~const` on trait without Effects assoc"); - return; - }; - - let ty = bound_trait_ref - .map_bound(|trait_ref| Ty::new_projection(tcx, assoc, trait_ref.args)); - - // When the user has written `for<'a, T> X<'a, T>: ~const Foo`, replace the - // binders to dummy ones i.e. `X<'static, ()>` so they can be referenced in - // the `Min` associated type properly (which doesn't allow using `for<>`) - // This should work for any bound variables as long as they don't have any - // bounds e.g. `for`. - // FIXME(effects) reconsider this approach to allow compatibility with `for` - let ty = tcx.replace_bound_vars_uncached(ty, FnMutDelegate { - regions: &mut |_| tcx.lifetimes.re_static, - types: &mut |_| tcx.types.unit, - consts: &mut |_| unimplemented!("`~const` does not support const binders"), - }); - - self.effects_min_tys.insert(ty, span); - return; - } - // for - // ``` - // trait Foo { type Bar: ~const Trait } - // ``` - // ensure that `::Effects: TyCompat`. - // - // FIXME(effects) this is equality for now, which wouldn't be helpful for a non-const implementor - // that uses a `Bar` that implements `Trait` with `Maybe` effects. - (DefKind::AssocTy, Some(ty::BoundConstness::ConstIfConst)) => { - // FIXME(effects): implement this - return; - } - // probably illegal in this position. - (_, Some(ty::BoundConstness::ConstIfConst)) => { - tcx.dcx().span_delayed_bug(span, "invalid `~const` encountered"); - return; - } - }; - // create a new projection type `::Effects` - let Some(assoc) = tcx.associated_type_for_effects(bound_trait_ref.def_id()) else { - tcx.dcx().span_delayed_bug( - span, - "`~const` trait bound has no effect assoc yet no errors encountered?", - ); - return; - }; - let self_ty = Ty::new_projection(tcx, assoc, bound_trait_ref.skip_binder().args); - // make `::Effects: Compat` - let new_trait_ref = - ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::EffectsCompat, Some(span)), [ - ty::GenericArg::from(self_ty), - compat_val.into(), - ]); - self.clauses.push((bound_trait_ref.rebind(new_trait_ref).upcast(tcx), span)); } pub(crate) fn push_projection_bound( diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 06317a3b3049..c75bdcec3880 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -58,15 +58,9 @@ fn equate_intrinsic_type<'tcx>( // the host effect param should be invisible as it shouldn't matter // whether effects is enabled for the intrinsic provider crate. - let consts_count = if generics.host_effect_index.is_some() { - own_counts.consts - 1 - } else { - own_counts.consts - }; - if gen_count_ok(own_counts.lifetimes, n_lts, "lifetime") && gen_count_ok(own_counts.types, n_tps, "type") - && gen_count_ok(consts_count, n_cts, "const") + && gen_count_ok(own_counts.consts, n_cts, "const") { let _ = check_function_signature( tcx, diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index d70e8673c520..79e579841746 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -913,12 +913,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(), hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => Ok(()), // Const parameters are well formed if their type is structural match. - hir::GenericParamKind::Const { - ty: hir_ty, - default: _, - is_host_effect: _, - synthetic: _, - } => { + hir::GenericParamKind::Const { ty: hir_ty, default: _, synthetic: _ } => { let ty = tcx.type_of(param.def_id).instantiate_identity(); if tcx.features().unsized_const_params() { diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 348b2260d260..3eec0e126657 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -53,7 +53,6 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { param_def_id_to_index, has_self: opaque_ty_generics.has_self, has_late_bound_regions: opaque_ty_generics.has_late_bound_regions, - host_effect_index: parent_generics.host_effect_index, }; } @@ -161,7 +160,6 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { param_def_id_to_index, has_self: generics.has_self, has_late_bound_regions: generics.has_late_bound_regions, - host_effect_index: None, }; } else { // HACK(eddyb) this provides the correct generics when @@ -292,12 +290,10 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { let has_self = opt_self.is_some(); let mut parent_has_self = false; let mut own_start = has_self as u32; - let mut host_effect_index = None; let parent_count = parent_def_id.map_or(0, |def_id| { let generics = tcx.generics_of(def_id); assert!(!has_self); parent_has_self = generics.has_self; - host_effect_index = generics.host_effect_index; own_start = generics.count() as u32; generics.parent_count + generics.own_params.len() }); @@ -361,12 +357,8 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { kind, }) } - GenericParamKind::Const { ty: _, default, is_host_effect, synthetic } => { - if !matches!(allow_defaults, Defaults::Allowed) - && default.is_some() - // `host` effect params are allowed to have defaults. - && !is_host_effect - { + GenericParamKind::Const { ty: _, default, synthetic } => { + if !matches!(allow_defaults, Defaults::Allowed) && default.is_some() { tcx.dcx().span_err( param.span, "defaults for const parameters are only allowed in \ @@ -376,27 +368,12 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { let index = next_index(); - if is_host_effect { - if let Some(idx) = host_effect_index { - tcx.dcx().span_delayed_bug( - param.span, - format!("parent also has host effect param? index: {idx}, def: {def_id:?}"), - ); - } - - host_effect_index = Some(index as usize); - } - Some(ty::GenericParamDef { index, name: param.name.ident().name, def_id: param.def_id.to_def_id(), pure_wrt_drop: param.pure_wrt_drop, - kind: ty::GenericParamDefKind::Const { - has_default: default.is_some(), - is_host_effect, - synthetic, - }, + kind: ty::GenericParamDefKind::Const { has_default: default.is_some(), synthetic }, }) } })); @@ -459,7 +436,6 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { param_def_id_to_index, has_self: has_self || parent_has_self, has_late_bound_regions: has_late_bound_regions(tcx, node), - host_effect_index, } } @@ -540,8 +516,7 @@ impl<'v> Visitor<'v> for AnonConstInParamTyDetector { type Result = ControlFlow<()>; fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) -> Self::Result { - if let GenericParamKind::Const { ty, default: _, is_host_effect: _, synthetic: _ } = p.kind - { + if let GenericParamKind::Const { ty, default: _, synthetic: _ } = p.kind { let prev = self.in_param_ty; self.in_param_ty = true; let res = self.visit_ty(ty); diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 097a1fbc3936..f9460ed5b473 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -78,7 +78,6 @@ pub(super) fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredic #[instrument(level = "trace", skip(tcx), ret)] fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::GenericPredicates<'_> { use rustc_hir::*; - use rustc_middle::ty::Ty; match tcx.opt_rpitit_info(def_id.to_def_id()) { Some(ImplTraitInTraitData::Trait { fn_def_id, .. }) => { @@ -345,26 +344,6 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen debug!(?predicates); } - // add `Self::Effects: Compat` to ensure non-const impls don't get called - // in const contexts. - if let Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. }) = node - && let Some(host_effect_index) = generics.host_effect_index - { - let parent = generics.parent.unwrap(); - let Some(assoc_def_id) = tcx.associated_type_for_effects(parent) else { - bug!("associated_type_for_effects returned None when there is host effect in generics"); - }; - let effects = - Ty::new_projection(tcx, assoc_def_id, ty::GenericArgs::identity_for_item(tcx, parent)); - let param = generics.param_at(host_effect_index, tcx); - let span = tcx.def_span(param.def_id); - let host = ty::Const::new_param(tcx, ty::ParamConst::for_def(param)); - let compat = tcx.require_lang_item(LangItem::EffectsCompat, Some(span)); - let trait_ref = - ty::TraitRef::new(tcx, compat, [ty::GenericArg::from(effects), host.into()]); - predicates.push((ty::Binder::dummy(trait_ref).upcast(tcx), span)); - } - ty::GenericPredicates { parent: generics.parent, predicates: tcx.arena.alloc_from_iter(predicates), diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index 1ccb7faaf305..4d3595965c91 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -186,7 +186,6 @@ impl<'tcx> GenericsBuilder<'tcx> { param_def_id_to_index, has_self, has_late_bound_regions: sig_generics.has_late_bound_regions, - host_effect_index: sig_generics.host_effect_index, } } } @@ -472,10 +471,6 @@ fn check_constraints<'tcx>( })); }; - if tcx.has_host_param(sig_id) { - emit("delegation to a function with effect parameter is not supported yet"); - } - if let Some(local_sig_id) = sig_id.as_local() && tcx.hir().opt_delegation_sig_id(local_sig_id).is_some() { diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index a73a2f925cd3..d2636c1573e0 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -694,15 +694,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); debug!(?poly_trait_ref); - bounds.push_trait_bound( - tcx, - self.item_def_id().to_def_id(), - poly_trait_ref, - span, - polarity, - constness, - predicate_filter, - ); + bounds.push_trait_bound(tcx, poly_trait_ref, span, polarity); let mut dup_constraints = FxIndexMap::default(); for constraint in trait_segment.args().constraints { diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 3ba9c76bcee3..61214b992153 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -2134,7 +2134,7 @@ impl<'a> State<'a> { self.print_type(default); } } - GenericParamKind::Const { ty, ref default, is_host_effect: _, synthetic: _ } => { + GenericParamKind::Const { ty, ref default, synthetic: _ } => { self.word_space(":"); self.print_type(ty); if let Some(default) = default { diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 06e2a5e34934..b642ba03aee2 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -20,7 +20,7 @@ use rustc_target::spec::abi; use rustc_trait_selection::error_reporting::traits::DefIdOrName; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; -use tracing::{debug, instrument, trace}; +use tracing::{debug, instrument}; use super::method::MethodCallee; use super::method::probe::ProbeScope; @@ -836,37 +836,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn_sig.output() } - #[tracing::instrument(level = "debug", skip(self, span))] + #[tracing::instrument(level = "debug", skip(self, _span))] pub(super) fn enforce_context_effects( &self, - span: Span, - callee_did: DefId, - callee_args: GenericArgsRef<'tcx>, + _span: Span, + _callee_did: DefId, + _callee_args: GenericArgsRef<'tcx>, ) { - let tcx = self.tcx; - - // fast-reject if callee doesn't have the host effect param (non-const) - let generics = tcx.generics_of(callee_did); - let Some(host_effect_index) = generics.host_effect_index else { return }; - - let effect = tcx.expected_host_effect_param_for_body(self.body_id); - - trace!(?effect, ?generics, ?callee_args); - - let param = callee_args.const_at(host_effect_index); - let cause = self.misc(span); - // We know the type of `effect` to be `bool`, there will be no opaque type inference. - match self.at(&cause, self.param_env).eq(infer::DefineOpaqueTypes::Yes, effect, param) { - Ok(infer::InferOk { obligations, value: () }) => { - self.register_predicates(obligations); - } - Err(e) => { - // FIXME(effects): better diagnostic - self.err_ctxt() - .report_mismatched_consts(&cause, self.param_env, effect, param, e) - .emit(); - } - } + todo!() } fn confirm_overloaded_call( diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 4fd508ab896e..68776c525551 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -7,8 +7,6 @@ use rustc_data_structures::unord::{UnordBag, UnordMap, UnordSet}; use rustc_hir as hir; use rustc_hir::HirId; use rustc_hir::intravisit::Visitor; -use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; -use rustc_middle::bug; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable}; use rustc_session::lint; use rustc_span::def_id::LocalDefId; @@ -48,7 +46,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { self.fulfillment_cx.borrow_mut().pending_obligations() ); - let fallback_occurred = self.fallback_types() | self.fallback_effects(); + let fallback_occurred = self.fallback_types(); if !fallback_occurred { return; @@ -103,31 +101,6 @@ impl<'tcx> FnCtxt<'_, 'tcx> { fallback_occurred } - fn fallback_effects(&self) -> bool { - let unsolved_effects = self.unsolved_effects(); - - if unsolved_effects.is_empty() { - return false; - } - - // not setting the `fallback_has_occurred` field here because - // that field is only used for type fallback diagnostics. - for effect in unsolved_effects { - let expected = self.tcx.consts.true_; - let cause = self.misc(DUMMY_SP); - match self.at(&cause, self.param_env).eq(DefineOpaqueTypes::Yes, expected, effect) { - Ok(InferOk { obligations, value: () }) => { - self.register_predicates(obligations); - } - Err(e) => { - bug!("cannot eq unsolved effect: {e:?}") - } - } - } - - true - } - // Tries to apply a fallback to `ty` if it is an unsolved variable. // // - Unconstrained ints are replaced with `i32`. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index d2d311ef5654..0fc566c58f72 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1262,15 +1262,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => { self.fcx.ty_infer(Some(param), inf.span).into() } - ( - &GenericParamDefKind::Const { has_default, is_host_effect, .. }, - GenericArg::Infer(inf), - ) => { - if has_default && is_host_effect { - self.fcx.var_for_effect(param) - } else { - self.fcx.ct_infer(Some(param), inf.span).into() - } + (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => { + self.fcx.ct_infer(Some(param), inf.span).into() } _ => unreachable!(), } @@ -1305,20 +1298,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.fcx.var_for_def(self.span, param) } } - GenericParamDefKind::Const { has_default, is_host_effect, .. } => { + GenericParamDefKind::Const { has_default, .. } => { if has_default { - // N.B. this is a bit of a hack. `infer_args` is passed depending on - // whether the user has provided generic args. E.g. for `Vec::new` - // we would have to infer the generic types. However, for `Vec::::new` - // where the allocator param `A` has a default we will *not* infer. But - // for effect params this is a different story: if the user has not written - // anything explicit for the effect param, we always need to try to infer - // it before falling back to default, such that a `const fn` such as - // `needs_drop::<()>` can still be called in const contexts. (if we defaulted - // instead of inferred, typeck would error) - if is_host_effect { - return self.fcx.var_for_effect(param); - } else if !infer_args { + if !infer_args { return tcx .const_param_default(param.def_id) .instantiate(tcx, preceding_args) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 4123feebb407..3940d138deb0 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -247,12 +247,6 @@ impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> { fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> { // FIXME ideally this shouldn't use unwrap match param { - Some( - param @ ty::GenericParamDef { - kind: ty::GenericParamDefKind::Const { is_host_effect: true, .. }, - .. - }, - ) => self.var_for_effect(param).as_const().unwrap(), Some(param) => self.var_for_def(span, param).as_const().unwrap(), None => self.next_const_var(span), } diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index 69b9be002768..e20a0cb67c35 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -369,17 +369,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Option>> { let (obligation, args) = self.obligation_for_method(cause, trait_def_id, self_ty, opt_input_types); - // FIXME(effects) find a better way to do this - // Operators don't have generic methods, but making them `#[const_trait]` gives them - // `const host: bool`. - let args = if self.tcx.is_const_trait(trait_def_id) { - self.tcx.mk_args_from_iter( - args.iter() - .chain([self.tcx.expected_host_effect_param_for_body(self.body_id).into()]), - ) - } else { - args - }; self.construct_obligation_for_trait(m_name, trait_def_id, obligation, args) } diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index e3519dfb0285..90d07964fdac 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -489,17 +489,6 @@ impl<'cx, 'tcx> TypeFolder> for Canonicalizer<'cx, 'tcx> { } } } - ty::ConstKind::Infer(InferConst::EffectVar(vid)) => { - match self.infcx.unwrap().probe_effect_var(vid) { - Some(value) => return self.fold_const(value), - None => { - return self.canonicalize_const_var( - CanonicalVarInfo { kind: CanonicalVarKind::Effect }, - ct, - ); - } - } - } ty::ConstKind::Infer(InferConst::Fresh(_)) => { bug!("encountered a fresh const during canonicalization") } @@ -700,8 +689,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { .iter() .map(|v| CanonicalVarInfo { kind: match v.kind { - CanonicalVarKind::Ty(CanonicalTyVarKind::Int | CanonicalTyVarKind::Float) - | CanonicalVarKind::Effect => { + CanonicalVarKind::Ty(CanonicalTyVarKind::Int | CanonicalTyVarKind::Float) => { return *v; } CanonicalVarKind::Ty(CanonicalTyVarKind::General(u)) => { diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index 8caedcd4053b..fb5fc3a53fe6 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -24,7 +24,6 @@ pub use instantiate::CanonicalExt; use rustc_index::IndexVec; pub use rustc_middle::infer::canonical::*; -use rustc_middle::infer::unify_key::EffectVarValue; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, GenericArg, List, Ty, TyCtxt}; use rustc_span::Span; @@ -145,15 +144,6 @@ impl<'tcx> InferCtxt<'tcx> { CanonicalVarKind::Const(ui) => { self.next_const_var_in_universe(span, universe_map(ui)).into() } - CanonicalVarKind::Effect => { - let vid = self - .inner - .borrow_mut() - .effect_unification_table() - .new_key(EffectVarValue::Unknown) - .vid; - ty::Const::new_infer(self.tcx, ty::InferConst::EffectVar(vid)).into() - } CanonicalVarKind::PlaceholderConst(ty::PlaceholderConst { universe, bound }) => { let universe_mapped = universe_map(universe); let placeholder_mapped = ty::PlaceholderConst { universe: universe_mapped, bound }; diff --git a/compiler/rustc_infer/src/infer/context.rs b/compiler/rustc_infer/src/infer/context.rs index 57007752cade..0c151a11ad4e 100644 --- a/compiler/rustc_infer/src/infer/context.rs +++ b/compiler/rustc_infer/src/infer/context.rs @@ -1,6 +1,5 @@ ///! Definition of `InferCtxtLike` from the librarified type layer. use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_middle::infer::unify_key::EffectVarValue; use rustc_middle::traits::ObligationCause; use rustc_middle::traits::solve::SolverMode; use rustc_middle::ty::fold::TypeFoldable; @@ -88,15 +87,6 @@ impl<'tcx> rustc_type_ir::InferCtxtLike for InferCtxt<'tcx> { } } - fn opportunistic_resolve_effect_var(&self, vid: ty::EffectVid) -> ty::Const<'tcx> { - match self.probe_effect_var(vid) { - Some(ct) => ct, - None => { - ty::Const::new_infer(self.tcx, ty::InferConst::EffectVar(self.root_effect_var(vid))) - } - } - } - fn opportunistic_resolve_lt_var(&self, vid: ty::RegionVid) -> ty::Region<'tcx> { self.inner.borrow_mut().unwrap_region_constraints().opportunistic_resolve_var(self.tcx, vid) } @@ -152,10 +142,6 @@ impl<'tcx> rustc_type_ir::InferCtxtLike for InferCtxt<'tcx> { self.inner.borrow_mut().const_unification_table().union(a, b); } - fn equate_effect_vids_raw(&self, a: rustc_type_ir::EffectVid, b: rustc_type_ir::EffectVid) { - self.inner.borrow_mut().effect_unification_table().union(a, b); - } - fn instantiate_ty_var_raw>( &self, relation: &mut R, @@ -189,13 +175,6 @@ impl<'tcx> rustc_type_ir::InferCtxtLike for InferCtxt<'tcx> { self.inner.borrow_mut().float_unification_table().union_value(vid, value); } - fn instantiate_effect_var_raw(&self, vid: rustc_type_ir::EffectVid, value: ty::Const<'tcx>) { - self.inner - .borrow_mut() - .effect_unification_table() - .union_value(vid, EffectVarValue::Known(value)); - } - fn instantiate_const_var_raw>( &self, relation: &mut R, diff --git a/compiler/rustc_infer/src/infer/freshen.rs b/compiler/rustc_infer/src/infer/freshen.rs index c4294111ebe8..28eac5b7496d 100644 --- a/compiler/rustc_infer/src/infer/freshen.rs +++ b/compiler/rustc_infer/src/infer/freshen.rs @@ -153,15 +153,6 @@ impl<'a, 'tcx> TypeFolder> for TypeFreshener<'a, 'tcx> { drop(inner); self.freshen_const(input, ty::InferConst::Fresh) } - ty::ConstKind::Infer(ty::InferConst::EffectVar(v)) => { - let mut inner = self.infcx.inner.borrow_mut(); - let input = - inner.effect_unification_table().probe_value(v).known().ok_or_else(|| { - ty::InferConst::EffectVar(inner.effect_unification_table().find(v).vid) - }); - drop(inner); - self.freshen_const(input, ty::InferConst::Fresh) - } ty::ConstKind::Infer(ty::InferConst::Fresh(i)) => { if i >= self.const_freshen_count { bug!( diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 5afdf3c24540..be43cba97f08 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -26,9 +26,7 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_macros::extension; pub use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues}; -use rustc_middle::infer::unify_key::{ - ConstVariableOrigin, ConstVariableValue, ConstVidKey, EffectVarValue, EffectVidKey, -}; +use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult}; use rustc_middle::traits::select; @@ -39,7 +37,7 @@ use rustc_middle::ty::fold::{ }; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{ - self, ConstVid, EffectVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, GenericArgsRef, + self, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, GenericArgsRef, GenericParamDefKind, InferConst, IntVid, Ty, TyCtxt, TyVid, }; use rustc_middle::{bug, span_bug}; @@ -117,9 +115,6 @@ pub struct InferCtxtInner<'tcx> { /// Map from floating variable to the kind of float it represents. float_unification_storage: ut::UnificationTableStorage, - /// Map from effect variable to the effect param it represents. - effect_unification_storage: ut::UnificationTableStorage>, - /// Tracks the set of region variables and the constraints between them. /// /// This is initially `Some(_)` but when @@ -176,7 +171,6 @@ impl<'tcx> InferCtxtInner<'tcx> { const_unification_storage: Default::default(), int_unification_storage: Default::default(), float_unification_storage: Default::default(), - effect_unification_storage: Default::default(), region_constraint_storage: Some(Default::default()), region_obligations: vec![], opaque_type_storage: Default::default(), @@ -228,10 +222,6 @@ impl<'tcx> InferCtxtInner<'tcx> { self.const_unification_storage.with_log(&mut self.undo_log) } - fn effect_unification_table(&mut self) -> UnificationTable<'_, 'tcx, EffectVidKey<'tcx>> { - self.effect_unification_storage.with_log(&mut self.undo_log) - } - #[inline] pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { self.region_constraint_storage @@ -524,7 +514,6 @@ impl fmt::Display for FixupError { ), Ty(_) => write!(f, "unconstrained type"), Const(_) => write!(f, "unconstrained const value"), - Effect(_) => write!(f, "unconstrained effect value"), } } } @@ -726,17 +715,6 @@ impl<'tcx> InferCtxt<'tcx> { vars } - pub fn unsolved_effects(&self) -> Vec> { - let mut inner = self.inner.borrow_mut(); - let mut table = inner.effect_unification_table(); - - (0..table.len()) - .map(|i| ty::EffectVid::from_usize(i)) - .filter(|&vid| table.probe_value(vid).is_unknown()) - .map(|v| ty::Const::new_infer(self.tcx, ty::InferConst::EffectVar(v))) - .collect() - } - #[instrument(skip(self), level = "debug")] pub fn sub_regions( &self, @@ -899,13 +877,6 @@ impl<'tcx> InferCtxt<'tcx> { ty::Const::new_var(self.tcx, vid) } - fn next_effect_var(&self) -> ty::Const<'tcx> { - let effect_vid = - self.inner.borrow_mut().effect_unification_table().new_key(EffectVarValue::Unknown).vid; - - ty::Const::new_infer(self.tcx, ty::InferConst::EffectVar(effect_vid)) - } - pub fn next_int_var(&self) -> Ty<'tcx> { let next_int_var_id = self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown); @@ -991,10 +962,7 @@ impl<'tcx> InferCtxt<'tcx> { Ty::new_var(self.tcx, ty_var_id).into() } - GenericParamDefKind::Const { is_host_effect, .. } => { - if is_host_effect { - return self.var_for_effect(param); - } + GenericParamDefKind::Const { .. } => { let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span }; let const_var_id = self .inner @@ -1007,16 +975,6 @@ impl<'tcx> InferCtxt<'tcx> { } } - pub fn var_for_effect(&self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { - let ty = self - .tcx - .type_of(param.def_id) - .no_bound_vars() - .expect("const parameter types cannot be generic"); - debug_assert_eq!(self.tcx.types.bool, ty); - self.next_effect_var().into() - } - /// Given a set of generics defined on a type or impl, returns the generic parameters mapping /// each type/region parameter to a fresh inference variable. pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> { @@ -1142,13 +1100,6 @@ impl<'tcx> InferCtxt<'tcx> { .probe_value(vid) .known() .unwrap_or(ct), - InferConst::EffectVar(vid) => self - .inner - .borrow_mut() - .effect_unification_table() - .probe_value(vid) - .known() - .unwrap_or(ct), InferConst::Fresh(_) => ct, }, ty::ConstKind::Param(_) @@ -1169,10 +1120,6 @@ impl<'tcx> InferCtxt<'tcx> { self.inner.borrow_mut().const_unification_table().find(var).vid } - pub fn root_effect_var(&self, var: ty::EffectVid) -> ty::EffectVid { - self.inner.borrow_mut().effect_unification_table().find(var).vid - } - /// Resolves an int var to a rigid int type, if it was constrained to one, /// or else the root int var in the unification table. pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> { @@ -1238,10 +1185,6 @@ impl<'tcx> InferCtxt<'tcx> { } } - pub fn probe_effect_var(&self, vid: EffectVid) -> Option> { - self.inner.borrow_mut().effect_unification_table().probe_value(vid).known() - } - /// Attempts to resolve all type/region/const variables in /// `value`. Region inference must have been run already (e.g., /// by calling `resolve_regions_and_report_errors`). If some @@ -1511,14 +1454,6 @@ impl<'tcx> InferCtxt<'tcx> { ConstVariableValue::Known { .. } => true, } } - - TyOrConstInferVar::Effect(v) => { - // If `probe_value` returns `Some`, it never equals - // `ty::ConstKind::Infer(ty::InferConst::Effect(v))`. - // - // Not `inlined_probe_value(v)` because this call site is colder. - self.probe_effect_var(v).is_some() - } } } @@ -1545,8 +1480,6 @@ pub enum TyOrConstInferVar { /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. Const(ConstVid), - /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::EffectVar(_))`. - Effect(EffectVid), } impl<'tcx> TyOrConstInferVar { @@ -1577,7 +1510,6 @@ impl<'tcx> TyOrConstInferVar { fn maybe_from_const(ct: ty::Const<'tcx>) -> Option { match ct.kind() { ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), - ty::ConstKind::Infer(InferConst::EffectVar(v)) => Some(TyOrConstInferVar::Effect(v)), _ => None, } } diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index 7049444db9b5..32817dbcb214 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -660,7 +660,6 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { } } } - ty::ConstKind::Infer(InferConst::EffectVar(_)) => Ok(c), // FIXME: Unevaluated constants are also not rigid, so the current // approach of always relating them structurally is incomplete. // diff --git a/compiler/rustc_infer/src/infer/resolve.rs b/compiler/rustc_infer/src/infer/resolve.rs index 64cc76f827eb..6ec2e0152f0d 100644 --- a/compiler/rustc_infer/src/infer/resolve.rs +++ b/compiler/rustc_infer/src/infer/resolve.rs @@ -176,9 +176,6 @@ impl<'a, 'tcx> FallibleTypeFolder> for FullTypeResolver<'a, 'tcx> { ty::ConstKind::Infer(InferConst::Fresh(_)) => { bug!("Unexpected const in full const resolver: {:?}", c); } - ty::ConstKind::Infer(InferConst::EffectVar(evid)) => { - return Err(FixupError { unresolved: super::TyOrConstInferVar::Effect(evid) }); - } _ => {} } c.try_super_fold_with(self) diff --git a/compiler/rustc_infer/src/infer/snapshot/fudge.rs b/compiler/rustc_infer/src/infer/snapshot/fudge.rs index 613cebc266dd..394e07a81e7d 100644 --- a/compiler/rustc_infer/src/infer/snapshot/fudge.rs +++ b/compiler/rustc_infer/src/infer/snapshot/fudge.rs @@ -4,7 +4,6 @@ use rustc_data_structures::{snapshot_vec as sv, unify as ut}; use rustc_middle::infer::unify_key::{ConstVariableValue, ConstVidKey}; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::{self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid}; -use rustc_type_ir::EffectVid; use rustc_type_ir::visit::TypeVisitableExt; use tracing::instrument; use ut::UnifyKey; @@ -129,7 +128,6 @@ struct SnapshotVarData { int_vars: Range, float_vars: Range, const_vars: (Range, Vec), - effect_vars: Range, } impl SnapshotVarData { @@ -148,30 +146,16 @@ impl SnapshotVarData { &mut inner.const_unification_table(), vars_pre_snapshot.const_var_len, ); - let effect_vars = vars_since_snapshot( - &inner.effect_unification_table(), - vars_pre_snapshot.effect_var_len, - ); - let effect_vars = effect_vars.start.vid..effect_vars.end.vid; - - SnapshotVarData { region_vars, type_vars, int_vars, float_vars, const_vars, effect_vars } + SnapshotVarData { region_vars, type_vars, int_vars, float_vars, const_vars } } fn is_empty(&self) -> bool { - let SnapshotVarData { - region_vars, - type_vars, - int_vars, - float_vars, - const_vars, - effect_vars, - } = self; + let SnapshotVarData { region_vars, type_vars, int_vars, float_vars, const_vars } = self; region_vars.0.is_empty() && type_vars.0.is_empty() && int_vars.is_empty() && float_vars.is_empty() && const_vars.0.is_empty() - && effect_vars.is_empty() } } @@ -258,13 +242,6 @@ impl<'a, 'tcx> TypeFolder> for InferenceFudger<'a, 'tcx> { ct } } - ty::InferConst::EffectVar(vid) => { - if self.snapshot_vars.effect_vars.contains(&vid) { - self.infcx.next_effect_var() - } else { - ct - } - } ty::InferConst::Fresh(_) => { unreachable!("unexpected fresh infcx var") } diff --git a/compiler/rustc_infer/src/infer/snapshot/mod.rs b/compiler/rustc_infer/src/infer/snapshot/mod.rs index fa813500c544..b16c80cf2014 100644 --- a/compiler/rustc_infer/src/infer/snapshot/mod.rs +++ b/compiler/rustc_infer/src/infer/snapshot/mod.rs @@ -23,7 +23,6 @@ struct VariableLengths { int_var_len: usize, float_var_len: usize, const_var_len: usize, - effect_var_len: usize, } impl<'tcx> InferCtxt<'tcx> { @@ -35,7 +34,6 @@ impl<'tcx> InferCtxt<'tcx> { int_var_len: inner.int_unification_table().len(), float_var_len: inner.float_unification_table().len(), const_var_len: inner.const_unification_table().len(), - effect_var_len: inner.effect_unification_table().len(), } } diff --git a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs index 79ea0915c9c0..713389f46183 100644 --- a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs +++ b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; use rustc_data_structures::undo_log::{Rollback, UndoLogs}; use rustc_data_structures::{snapshot_vec as sv, unify as ut}; -use rustc_middle::infer::unify_key::{ConstVidKey, EffectVidKey, RegionVidKey}; +use rustc_middle::infer::unify_key::{ConstVidKey, RegionVidKey}; use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey}; use tracing::debug; @@ -22,7 +22,6 @@ pub(crate) enum UndoLog<'tcx> { ConstUnificationTable(sv::UndoLog>>), IntUnificationTable(sv::UndoLog>), FloatUnificationTable(sv::UndoLog>), - EffectUnificationTable(sv::UndoLog>>), RegionConstraintCollector(region_constraints::UndoLog<'tcx>), RegionUnificationTable(sv::UndoLog>>), ProjectionCache(traits::UndoLog<'tcx>), @@ -50,7 +49,6 @@ impl_from! { FloatUnificationTable(sv::UndoLog>), ConstUnificationTable(sv::UndoLog>>), - EffectUnificationTable(sv::UndoLog>>), RegionUnificationTable(sv::UndoLog>>), ProjectionCache(traits::UndoLog<'tcx>), @@ -65,7 +63,6 @@ impl<'tcx> Rollback> for InferCtxtInner<'tcx> { UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo), UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo), UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo), - UndoLog::EffectUnificationTable(undo) => self.effect_unification_storage.reverse(undo), UndoLog::RegionConstraintCollector(undo) => { self.region_constraint_storage.as_mut().unwrap().reverse(undo) } diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 83a8ca4307e0..1c27e1daa906 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -542,11 +542,7 @@ impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals { } fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) { - if let GenericParamKind::Const { is_host_effect, .. } = param.kind { - // `host` params are explicitly allowed to be lowercase. - if is_host_effect { - return; - } + if let GenericParamKind::Const { .. } = param.kind { NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident()); } } diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 7bb40996d58f..d4cbf6e13afb 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -330,7 +330,6 @@ provide! { tcx, def_id, other, cdata, .process_decoded(tcx, || panic!("{def_id:?} does not have trait_impl_trait_tys"))) } - associated_type_for_effects => { table } associated_types_for_impl_traits_in_associated_fn => { table_defaulted_array } visibility => { cdata.get_visibility(def_id.index) } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index ec678c7515b0..80b979fe088f 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1479,9 +1479,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { for &def_id in associated_item_def_ids { self.encode_info_for_assoc_item(def_id); } - if let Some(assoc_def_id) = self.tcx.associated_type_for_effects(def_id) { - record!(self.tables.associated_type_for_effects[def_id] <- assoc_def_id); - } } if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id) diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 79bd1c13b121..8da1be805446 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -394,7 +394,6 @@ define_tables! { explicit_implied_predicates_of: Table, Span)>>, inherent_impls: Table>, associated_types_for_impl_traits_in_associated_fn: Table>, - associated_type_for_effects: Table>>, opt_rpitit_info: Table>>, is_effects_desugaring: Table, unused_generic_params: Table, diff --git a/compiler/rustc_middle/src/infer/unify_key.rs b/compiler/rustc_middle/src/infer/unify_key.rs index cf692b145b8d..7f9211043d69 100644 --- a/compiler/rustc_middle/src/infer/unify_key.rs +++ b/compiler/rustc_middle/src/infer/unify_key.rs @@ -172,70 +172,3 @@ impl<'tcx> UnifyValue for ConstVariableValue<'tcx> { } } } - -/// values for the effect inference variable -#[derive(Clone, Copy, Debug)] -pub enum EffectVarValue<'tcx> { - Unknown, - Known(ty::Const<'tcx>), -} - -impl<'tcx> EffectVarValue<'tcx> { - pub fn known(self) -> Option> { - match self { - EffectVarValue::Unknown => None, - EffectVarValue::Known(value) => Some(value), - } - } - - pub fn is_unknown(self) -> bool { - match self { - EffectVarValue::Unknown => true, - EffectVarValue::Known(_) => false, - } - } -} - -impl<'tcx> UnifyValue for EffectVarValue<'tcx> { - type Error = NoError; - - fn unify_values(value1: &Self, value2: &Self) -> Result { - match (*value1, *value2) { - (EffectVarValue::Unknown, EffectVarValue::Unknown) => Ok(EffectVarValue::Unknown), - (EffectVarValue::Unknown, EffectVarValue::Known(val)) - | (EffectVarValue::Known(val), EffectVarValue::Unknown) => { - Ok(EffectVarValue::Known(val)) - } - (EffectVarValue::Known(_), EffectVarValue::Known(_)) => { - bug!("equating known inference variables: {value1:?} {value2:?}") - } - } - } -} - -#[derive(PartialEq, Copy, Clone, Debug)] -pub struct EffectVidKey<'tcx> { - pub vid: ty::EffectVid, - pub phantom: PhantomData>, -} - -impl<'tcx> From for EffectVidKey<'tcx> { - fn from(vid: ty::EffectVid) -> Self { - EffectVidKey { vid, phantom: PhantomData } - } -} - -impl<'tcx> UnifyKey for EffectVidKey<'tcx> { - type Value = EffectVarValue<'tcx>; - #[inline] - fn index(&self) -> u32 { - self.vid.as_u32() - } - #[inline] - fn from_index(i: u32) -> Self { - EffectVidKey::from(ty::EffectVid::from_u32(i)) - } - fn tag() -> &'static str { - "EffectVidKey" - } -} diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index f8ba606e087c..0b751779501d 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -854,12 +854,6 @@ rustc_queries! { separate_provide_extern } - query associated_type_for_effects(def_id: DefId) -> Option { - desc { |tcx| "creating associated items for effects in `{}`", tcx.def_path_str(def_id) } - cache_on_disk_if { def_id.is_local() } - separate_provide_extern - } - /// Given an impl trait in trait `opaque_ty_def_id`, create and return the corresponding /// associated item. query associated_type_for_impl_trait_in_trait(opaque_ty_def_id: LocalDefId) -> LocalDefId { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index b682524ae39f..281899647efb 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -646,13 +646,6 @@ bidirectional_lang_item_map! { Destruct, DiscriminantKind, DynMetadata, - EffectsCompat, - EffectsIntersection, - EffectsIntersectionOutput, - EffectsMaybe, - EffectsNoRuntime, - EffectsRuntime, - EffectsTyCompat, Fn, FnMut, FnOnce, diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 8bd2ae9128f7..64405d18c7d2 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -592,9 +592,6 @@ impl<'tcx> TypeVisitor> for IsSuggestableVisitor<'tcx> { match c.kind() { ConstKind::Infer(InferConst::Var(_)) if self.infer_suggestable => {} - // effect variables are always suggestable, because they are not visible - ConstKind::Infer(InferConst::EffectVar(_)) => {} - ConstKind::Infer(..) | ConstKind::Bound(..) | ConstKind::Placeholder(..) diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 92a975c028e5..39899f1d32be 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -354,9 +354,7 @@ impl FlagComputation { self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); match infer { InferConst::Fresh(_) => self.add_flags(TypeFlags::HAS_CT_FRESH), - InferConst::Var(_) | InferConst::EffectVar(_) => { - self.add_flags(TypeFlags::HAS_CT_INFER) - } + InferConst::Var(_) => self.add_flags(TypeFlags::HAS_CT_INFER), } } ty::ConstKind::Bound(debruijn, _) => { diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index daf1362e25c1..56111ee063eb 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -501,12 +501,11 @@ impl<'tcx> GenericArgs<'tcx> { #[inline] pub fn non_erasable_generics( &'tcx self, - tcx: TyCtxt<'tcx>, - def_id: DefId, + // FIXME(effects): Remove these + _tcx: TyCtxt<'tcx>, + _def_id: DefId, ) -> impl DoubleEndedIterator> + 'tcx { - let generics = tcx.generics_of(def_id); - self.iter().enumerate().filter_map(|(i, k)| match k.unpack() { - _ if Some(i) == generics.host_effect_index => None, + self.iter().filter_map(|k| match k.unpack() { ty::GenericArgKind::Lifetime(_) => None, generic => Some(generic), }) diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index 63534a3d0174..e24a3f281fc5 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -14,7 +14,7 @@ use crate::ty::{EarlyBinder, GenericArgsRef}; pub enum GenericParamDefKind { Lifetime, Type { has_default: bool, synthetic: bool }, - Const { has_default: bool, is_host_effect: bool, synthetic: bool }, + Const { has_default: bool, synthetic: bool }, } impl GenericParamDefKind { @@ -81,10 +81,6 @@ impl GenericParamDef { } } - pub fn is_host_effect(&self) -> bool { - matches!(self.kind, GenericParamDefKind::Const { is_host_effect: true, .. }) - } - pub fn default_value<'tcx>( &self, tcx: TyCtxt<'tcx>, @@ -133,9 +129,6 @@ pub struct Generics { pub has_self: bool, pub has_late_bound_regions: Option, - - // The index of the host effect when instantiated. (i.e. might be index to parent args) - pub host_effect_index: Option, } impl<'tcx> rustc_type_ir::inherent::GenericsOf> for &'tcx Generics { @@ -216,12 +209,10 @@ impl<'tcx> Generics { pub fn own_requires_monomorphization(&self) -> bool { for param in &self.own_params { match param.kind { - GenericParamDefKind::Type { .. } - | GenericParamDefKind::Const { is_host_effect: false, .. } => { + GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { return true; } - GenericParamDefKind::Lifetime - | GenericParamDefKind::Const { is_host_effect: true, .. } => {} + GenericParamDefKind::Lifetime => {} } } false @@ -300,8 +291,6 @@ impl<'tcx> Generics { own_params.start = 1; } - let verbose = tcx.sess.verbose_internals(); - // Filter the default arguments. // // This currently uses structural equality instead @@ -316,8 +305,6 @@ impl<'tcx> Generics { param.default_value(tcx).is_some_and(|default| { default.instantiate(tcx, args) == args[param.index as usize] }) - // filter out trailing effect params, if we're not in `-Zverbose-internals`. - || (!verbose && matches!(param.kind, GenericParamDefKind::Const { is_host_effect: true, .. })) }) .count(); diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index b1c5ff50fdc8..61cb43225015 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -476,7 +476,6 @@ impl<'tcx> Instance<'tcx> { pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> { let args = GenericArgs::for_item(tcx, def_id, |param, _| match param.kind { ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), - ty::GenericParamDefKind::Const { is_host_effect: true, .. } => tcx.consts.true_.into(), ty::GenericParamDefKind::Type { .. } => { bug!("Instance::mono: {:?} has type parameters", def_id) } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 06cbb6c9f1d8..7fd7e463acf8 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -17,10 +17,10 @@ use rustc_span::sym; use rustc_target::abi::{Float, Integer, IntegerType, Size}; use rustc_target::spec::abi::Abi; use smallvec::{SmallVec, smallvec}; -use tracing::{debug, instrument, trace}; +use tracing::{debug, instrument}; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use crate::query::{IntoQueryParam, Providers}; +use crate::query::Providers; use crate::ty::layout::{FloatExt, IntegerExt}; use crate::ty::{ self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable, @@ -865,48 +865,6 @@ impl<'tcx> TyCtxt<'tcx> { || self.extern_crate(key).is_some_and(|e| e.is_direct()) } - /// Whether the item has a host effect param. This is different from `TyCtxt::is_const`, - /// because the item must also be "maybe const", and the crate where the item is - /// defined must also have the effects feature enabled. - pub fn has_host_param(self, def_id: impl IntoQueryParam) -> bool { - self.generics_of(def_id).host_effect_index.is_some() - } - - pub fn expected_host_effect_param_for_body(self, def_id: impl Into) -> ty::Const<'tcx> { - let def_id = def_id.into(); - // FIXME(effects): This is suspicious and should probably not be done, - // especially now that we enforce host effects and then properly handle - // effect vars during fallback. - let mut host_always_on = !self.features().effects() - || self.sess.opts.unstable_opts.unleash_the_miri_inside_of_you; - - // Compute the constness required by the context. - let const_context = self.hir().body_const_context(def_id); - - let kind = self.def_kind(def_id); - debug_assert_ne!(kind, DefKind::ConstParam); - - if self.has_attr(def_id, sym::rustc_do_not_const_check) { - trace!("do not const check this context"); - host_always_on = true; - } - - match const_context { - _ if host_always_on => self.consts.true_, - Some(hir::ConstContext::Static(_) | hir::ConstContext::Const { .. }) => { - self.consts.false_ - } - Some(hir::ConstContext::ConstFn) => { - let host_idx = self - .generics_of(def_id) - .host_effect_index - .expect("ConstContext::Maybe must have host effect param"); - ty::GenericArgs::identity_for_item(self, def_id).const_at(host_idx) - } - None => self.consts.true_, - } - } - /// Expand any [weak alias types][weak] contained within the given `value`. /// /// This should be used over other normalization routines in situations where diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index b4d084d4dffc..e5c59d608221 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1522,7 +1522,6 @@ fn create_mono_items_for_default_impls<'tcx>( // it, to validate whether or not the impl is legal to instantiate at all. let only_region_params = |param: &ty::GenericParamDef, _: &_| match param.kind { GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), - GenericParamDefKind::Const { is_host_effect: true, .. } => tcx.consts.true_.into(), GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { unreachable!( "`own_requires_monomorphization` check means that \ diff --git a/compiler/rustc_next_trait_solver/src/canonicalizer.rs b/compiler/rustc_next_trait_solver/src/canonicalizer.rs index 23634d35c07f..63608f9e8561 100644 --- a/compiler/rustc_next_trait_solver/src/canonicalizer.rs +++ b/compiler/rustc_next_trait_solver/src/canonicalizer.rs @@ -431,7 +431,6 @@ impl, I: Interner> TypeFolder for Canonicaliz ); CanonicalVarKind::Const(self.delegate.universe_of_ct(vid).unwrap()) } - ty::InferConst::EffectVar(_) => CanonicalVarKind::Effect, ty::InferConst::Fresh(_) => todo!(), }, ty::ConstKind::Placeholder(placeholder) => match self.canonicalize_mode { diff --git a/compiler/rustc_next_trait_solver/src/resolve.rs b/compiler/rustc_next_trait_solver/src/resolve.rs index f2654f7534e1..71c87714745e 100644 --- a/compiler/rustc_next_trait_solver/src/resolve.rs +++ b/compiler/rustc_next_trait_solver/src/resolve.rs @@ -76,9 +76,6 @@ impl, I: Interner> TypeFolder for EagerResolv resolved } } - ty::ConstKind::Infer(ty::InferConst::EffectVar(vid)) => { - self.delegate.opportunistic_resolve_effect_var(vid) - } _ => { if c.has_infer() { c.super_fold_with(self) diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index c9c0d6391fc8..5e604a5d74f5 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -270,11 +270,6 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Vec>; - - fn consider_builtin_effects_intersection_candidate( - ecx: &mut EvalCtxt<'_, D>, - goal: Goal, - ) -> Result, NoSolution>; } impl EvalCtxt<'_, D> @@ -481,9 +476,6 @@ where Some(TraitSolverLangItem::TransmuteTrait) => { G::consider_builtin_transmute_candidate(self, goal) } - Some(TraitSolverLangItem::EffectsIntersection) => { - G::consider_builtin_effects_intersection_candidate(self, goal) - } _ => Err(NoSolution), } }; diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index a475a58e483b..b7fdc339be5c 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -182,12 +182,6 @@ where let (ct, ty) = goal.predicate; let ct_ty = match ct.kind() { - // FIXME: Ignore effect vars because canonicalization doesn't handle them correctly - // and if we stall on the var then we wind up creating ambiguity errors in a probe - // for this goal which contains an effect var. Which then ends up ICEing. - ty::ConstKind::Infer(ty::InferConst::EffectVar(_)) => { - return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes); - } ty::ConstKind::Infer(_) => { return self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); } diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index 4d8b193ee491..c98fd8535514 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -911,68 +911,6 @@ where ) -> Result, NoSolution> { panic!("`TransmuteFrom` does not have an associated type: {:?}", goal) } - - fn consider_builtin_effects_intersection_candidate( - ecx: &mut EvalCtxt<'_, D>, - goal: Goal, - ) -> Result, NoSolution> { - let ty::Tuple(types) = goal.predicate.self_ty().kind() else { - return Err(NoSolution); - }; - - let cx = ecx.cx(); - - let mut first_non_maybe = None; - let mut non_maybe_count = 0; - for ty in types.iter() { - if !matches!(ty::EffectKind::try_from_ty(cx, ty), Some(ty::EffectKind::Maybe)) { - first_non_maybe.get_or_insert(ty); - non_maybe_count += 1; - } - } - - match non_maybe_count { - 0 => { - let ty = ty::EffectKind::Maybe.to_ty(cx); - ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { - ecx.instantiate_normalizes_to_term(goal, ty.into()); - ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) - }) - } - 1 => { - let ty = first_non_maybe.unwrap(); - ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { - ecx.instantiate_normalizes_to_term(goal, ty.into()); - ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) - }) - } - _ => { - let mut min = ty::EffectKind::Maybe; - - for ty in types.iter() { - // We can't find the intersection if the types used are generic. - // - // FIXME(effects): do we want to look at where clauses to get some - // clue for the case where generic types are being used? - let Some(kind) = ty::EffectKind::try_from_ty(cx, ty) else { - return Err(NoSolution); - }; - - let Some(result) = ty::EffectKind::intersection(min, kind) else { - return Err(NoSolution); - }; - - min = result; - } - - let ty = min.to_ty(cx); - ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { - ecx.instantiate_normalizes_to_term(goal, ty.into()); - ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) - }) - } - } - } } impl EvalCtxt<'_, D> diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index a8d6536baadd..6b26f960286f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -719,47 +719,6 @@ where } }) } - - fn consider_builtin_effects_intersection_candidate( - ecx: &mut EvalCtxt<'_, D>, - goal: Goal, - ) -> Result, NoSolution> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { - return Err(NoSolution); - } - - let ty::Tuple(types) = goal.predicate.self_ty().kind() else { - return Err(NoSolution); - }; - - let cx = ecx.cx(); - let maybe_count = types - .iter() - .filter_map(|ty| ty::EffectKind::try_from_ty(cx, ty)) - .filter(|&ty| ty == ty::EffectKind::Maybe) - .count(); - - // Don't do concrete type check unless there are more than one type that will influence the result. - // This would allow `(Maybe, T): Min` pass even if we know nothing about `T`. - if types.len() - maybe_count > 1 { - let mut min = ty::EffectKind::Maybe; - - for ty in types.iter() { - let Some(kind) = ty::EffectKind::try_from_ty(ecx.cx(), ty) else { - return Err(NoSolution); - }; - - let Some(result) = ty::EffectKind::intersection(min, kind) else { - return Err(NoSolution); - }; - - min = result; - } - } - - ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc) - .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)) - } } impl EvalCtxt<'_, D> diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index ef2ee9a166af..0abc89ddb81a 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -588,7 +588,6 @@ impl<'tcx> Stable<'tcx> for ty::Generics { .has_late_bound_regions .as_ref() .map(|late_bound_regions| late_bound_regions.stable(tables)), - host_effect_index: self.host_effect_index, } } } @@ -603,7 +602,7 @@ impl<'tcx> Stable<'tcx> for rustc_middle::ty::GenericParamDefKind { ty::GenericParamDefKind::Type { has_default, synthetic } => { GenericParamDefKind::Type { has_default: *has_default, synthetic: *synthetic } } - ty::GenericParamDefKind::Const { has_default, is_host_effect: _, synthetic: _ } => { + ty::GenericParamDefKind::Const { has_default, synthetic: _ } => { GenericParamDefKind::Const { has_default: *has_default } } } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index aa05b88ea0c4..bf5f948fe919 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -195,14 +195,6 @@ symbols! { Display, DoubleEndedIterator, Duration, - EffectsCompat, - EffectsIntersection, - EffectsIntersectionOutput, - EffectsMaybe, - EffectsNoRuntime, - EffectsRuntime, - EffectsTyCompat, - Effects__, Encodable, Encoder, Enumerate, @@ -1737,7 +1729,6 @@ symbols! { rustc_reallocator, rustc_regions, rustc_reservation_impl, - rustc_runtime, rustc_safe_intrinsic, rustc_serialize, rustc_skip_during_method_dispatch, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 6ef64c3ed80a..b0175fff8a7f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -2374,50 +2374,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }) } - /// For effects predicates such as `::Effects: Compat`, pretend that the - /// predicate that failed was `u32: Add`. Return the constness of such predicate to later - /// print as `u32: ~const Add`. + // FIXME(effects): Remove this. fn get_effects_trait_pred_override( &self, p: ty::PolyTraitPredicate<'tcx>, leaf: ty::PolyTraitPredicate<'tcx>, - span: Span, - ) -> (ty::PolyTraitPredicate<'tcx>, ty::PolyTraitPredicate<'tcx>, Option) - { - let trait_ref = p.to_poly_trait_ref(); - if !self.tcx.is_lang_item(trait_ref.def_id(), LangItem::EffectsCompat) { - return (p, leaf, None); - } - - let Some(ty::Alias(ty::AliasTyKind::Projection, projection)) = - trait_ref.self_ty().no_bound_vars().map(Ty::kind) - else { - return (p, leaf, None); - }; - - let constness = trait_ref.skip_binder().args.const_at(1); - - let constness = if constness == self.tcx.consts.true_ || constness.is_ct_infer() { - None - } else if constness == self.tcx.consts.false_ { - Some(ty::BoundConstness::Const) - } else if matches!(constness.kind(), ty::ConstKind::Param(_)) { - Some(ty::BoundConstness::ConstIfConst) - } else { - self.dcx().span_bug(span, format!("Unknown constness argument: {constness:?}")); - }; - - let new_pred = p.map_bound(|mut trait_pred| { - trait_pred.trait_ref = projection.trait_ref(self.tcx); - trait_pred - }); - - let new_leaf = leaf.map_bound(|mut trait_pred| { - trait_pred.trait_ref = projection.trait_ref(self.tcx); - trait_pred - }); - - (new_pred, new_leaf, constness) + _span: Span, + ) -> (ty::PolyTraitPredicate<'tcx>, ty::PolyTraitPredicate<'tcx>, ty::BoundConstness) { + (p, leaf, ty::BoundConstness::NotConst) } fn add_tuple_trait_message( diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 2bdeb00bdacb..ca9e6cd662d9 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -450,7 +450,6 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { ty::ConstKind::Infer(var) => { let var = match var { ty::InferConst::Var(vid) => TyOrConstInferVar::Const(vid), - ty::InferConst::EffectVar(vid) => TyOrConstInferVar::Effect(vid), ty::InferConst::Fresh(_) => { bug!("encountered fresh const in fulfill") } 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 eea3867190d3..dac007663162 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -547,7 +547,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396). - ty::FnDef(def_id, _args) => { + ty::FnDef(def_id, _) => { let tcx = self.tcx(); if tcx.fn_sig(def_id).skip_binder().is_fn_trait_compatible() && tcx.codegen_fn_attrs(def_id).target_features.is_empty() diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index d5b1c5a97daa..4d7e2769af5f 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1821,8 +1821,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { |cand: ty::PolyTraitPredicate<'tcx>| cand.is_global() && !cand.has_bound_vars(); // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`, - // `DiscriminantKindCandidate`, `ConstDestructCandidate` - // to anything else. + // or `DiscriminantKindCandidate` to anything else. // // This is a fix for #53123 and prevents winnowing from accidentally extending the // lifetime of a variable. diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index a3210dd80d77..16fd28201c22 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -4,9 +4,8 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, ImplTraitInTraitData, Ty, TyCtxt}; +use rustc_middle::ty::{self, ImplTraitInTraitData, TyCtxt}; use rustc_middle::{bug, span_bug}; -use rustc_span::sym; use rustc_span::symbol::kw; pub(crate) fn provide(providers: &mut Providers) { @@ -15,7 +14,6 @@ pub(crate) fn provide(providers: &mut Providers) { associated_item_def_ids, associated_items, associated_types_for_impl_traits_in_associated_fn, - associated_type_for_effects, associated_type_for_impl_trait_in_trait, impl_item_implementor_ids, ..*providers @@ -46,8 +44,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { ) }) .copied(), - ) - .chain(tcx.associated_type_for_effects(def_id)), + ), ) } hir::ItemKind::Impl(impl_) => { @@ -73,8 +70,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { ) }) .copied() - })) - .chain(tcx.associated_type_for_effects(def_id)), + })), ) } _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"), @@ -171,134 +167,6 @@ fn associated_item_from_impl_item_ref(impl_item_ref: &hir::ImplItemRef) -> ty::A } } -/// Given an `def_id` of a trait or a trait impl: -/// -/// If `def_id` is a trait that has `#[const_trait]`, then it synthesizes -/// a new def id corresponding to a new associated type for the effects. -/// -/// If `def_id` is an impl, then synthesize the associated type according -/// to the constness of the impl. -fn associated_type_for_effects(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - // don't synthesize the associated type even if the user has written `const_trait` - // if the effects feature is disabled. - if !tcx.features().effects() { - return None; - } - let (feed, parent_did) = match tcx.def_kind(def_id) { - DefKind::Trait => { - let trait_def_id = def_id; - let attr = tcx.get_attr(def_id, sym::const_trait)?; - - let span = attr.span; - let trait_assoc_ty = tcx.at(span).create_def(trait_def_id, kw::Empty, DefKind::AssocTy); - - let local_def_id = trait_assoc_ty.def_id(); - let def_id = local_def_id.to_def_id(); - - // Copy span of the attribute. - trait_assoc_ty.def_ident_span(Some(span)); - - trait_assoc_ty.associated_item(ty::AssocItem { - name: kw::Empty, - kind: ty::AssocKind::Type, - def_id, - trait_item_def_id: None, - container: ty::TraitContainer, - fn_has_self_parameter: false, - opt_rpitit_info: None, - is_effects_desugaring: true, - }); - - // No default type - trait_assoc_ty.defaultness(hir::Defaultness::Default { has_value: false }); - - trait_assoc_ty.is_type_alias_impl_trait(false); - - (trait_assoc_ty, trait_def_id) - } - DefKind::Impl { .. } => { - let impl_def_id = def_id; - let trait_id = tcx.trait_id_of_impl(def_id.to_def_id())?; - - // first get the DefId of the assoc type on the trait, if there is not, - // then we don't need to generate it on the impl. - let trait_assoc_id = tcx.associated_type_for_effects(trait_id)?; - - // FIXME(effects): span - let span = tcx.def_ident_span(def_id).unwrap(); - - let impl_assoc_ty = tcx.at(span).create_def(def_id, kw::Empty, DefKind::AssocTy); - - let local_def_id = impl_assoc_ty.def_id(); - let def_id = local_def_id.to_def_id(); - - impl_assoc_ty.def_ident_span(Some(span)); - - impl_assoc_ty.associated_item(ty::AssocItem { - name: kw::Empty, - kind: ty::AssocKind::Type, - def_id, - trait_item_def_id: Some(trait_assoc_id), - container: ty::ImplContainer, - fn_has_self_parameter: false, - opt_rpitit_info: None, - is_effects_desugaring: true, - }); - - // no default value. - impl_assoc_ty.defaultness(hir::Defaultness::Final); - - // set the type of the associated type! If this is a const impl, - // we set to Maybe, otherwise we set to `Runtime`. - let type_def_id = if tcx.is_const_trait_impl_raw(impl_def_id.to_def_id()) { - tcx.require_lang_item(hir::LangItem::EffectsMaybe, Some(span)) - } else { - tcx.require_lang_item(hir::LangItem::EffectsRuntime, Some(span)) - }; - // FIXME(effects): make impls use `Min` for their effect types - impl_assoc_ty.type_of(ty::EarlyBinder::bind(Ty::new_adt( - tcx, - tcx.adt_def(type_def_id), - ty::GenericArgs::empty(), - ))); - - (impl_assoc_ty, impl_def_id) - } - def_kind => bug!( - "associated_type_for_effects: {:?} should be Trait or Impl but is {:?}", - def_id, - def_kind - ), - }; - - feed.feed_hir(); - - // visibility is public. - feed.visibility(ty::Visibility::Public); - - // Copy generics_of of the trait/impl, making the trait/impl as parent. - feed.generics_of({ - let parent_generics = tcx.generics_of(parent_did); - let parent_count = parent_generics.parent_count + parent_generics.own_params.len(); - - ty::Generics { - parent: Some(parent_did.to_def_id()), - parent_count, - own_params: vec![], - param_def_id_to_index: parent_generics.param_def_id_to_index.clone(), - has_self: false, - has_late_bound_regions: None, - host_effect_index: parent_generics.host_effect_index, - } - }); - feed.explicit_item_super_predicates(ty::EarlyBinder::bind(&[])); - - // There are no inferred outlives for the synthesized associated type. - feed.inferred_outlives_of(&[]); - - Some(feed.def_id().to_def_id()) -} - /// Given an `fn_def_id` of a trait or a trait implementation: /// /// if `fn_def_id` is a function defined inside a trait, then it synthesizes @@ -494,7 +362,6 @@ fn associated_type_for_impl_trait_in_impl( param_def_id_to_index, has_self: false, has_late_bound_regions: trait_assoc_generics.has_late_bound_regions, - host_effect_index: parent_generics.host_effect_index, } }); diff --git a/compiler/rustc_type_ir/src/canonical.rs b/compiler/rustc_type_ir/src/canonical.rs index 07cb8b037ecf..3fb7d87bcc4b 100644 --- a/compiler/rustc_type_ir/src/canonical.rs +++ b/compiler/rustc_type_ir/src/canonical.rs @@ -108,7 +108,6 @@ impl CanonicalVarInfo { CanonicalVarKind::PlaceholderRegion(..) => false, CanonicalVarKind::Const(_) => true, CanonicalVarKind::PlaceholderConst(_) => false, - CanonicalVarKind::Effect => true, } } @@ -118,17 +117,15 @@ impl CanonicalVarInfo { CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) | CanonicalVarKind::Const(_) - | CanonicalVarKind::PlaceholderConst(_) - | CanonicalVarKind::Effect => false, + | CanonicalVarKind::PlaceholderConst(_) => false, } } pub fn expect_placeholder_index(self) -> usize { match self.kind { - CanonicalVarKind::Ty(_) - | CanonicalVarKind::Region(_) - | CanonicalVarKind::Const(_) - | CanonicalVarKind::Effect => panic!("expected placeholder: {self:?}"), + CanonicalVarKind::Ty(_) | CanonicalVarKind::Region(_) | CanonicalVarKind::Const(_) => { + panic!("expected placeholder: {self:?}") + } CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.var().as_usize(), CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.var().as_usize(), @@ -161,9 +158,6 @@ pub enum CanonicalVarKind { /// Some kind of const inference variable. Const(UniverseIndex), - /// Effect variable `'?E`. - Effect, - /// A "placeholder" that represents "any const". PlaceholderConst(I::PlaceholderConst), } @@ -180,7 +174,6 @@ impl CanonicalVarKind { CanonicalVarKind::Ty(CanonicalTyVarKind::Float | CanonicalTyVarKind::Int) => { UniverseIndex::ROOT } - CanonicalVarKind::Effect => UniverseIndex::ROOT, } } @@ -205,8 +198,7 @@ impl CanonicalVarKind { CanonicalVarKind::PlaceholderConst(placeholder) => { CanonicalVarKind::PlaceholderConst(placeholder.with_updated_universe(ui)) } - CanonicalVarKind::Ty(CanonicalTyVarKind::Int | CanonicalTyVarKind::Float) - | CanonicalVarKind::Effect => { + CanonicalVarKind::Ty(CanonicalTyVarKind::Int | CanonicalTyVarKind::Float) => { assert_eq!(ui, UniverseIndex::ROOT); self } @@ -311,10 +303,6 @@ impl CanonicalVarValues { Region::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) .into() } - CanonicalVarKind::Effect => { - Const::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) - .into() - } CanonicalVarKind::Const(_) | CanonicalVarKind::PlaceholderConst(_) => { Const::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) .into() diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index 7a8c612057fa..03dfe547cedd 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -84,32 +84,12 @@ rustc_index::newtype_index! { pub struct ConstVid {} } -rustc_index::newtype_index! { - /// An **effect** **v**ariable **ID**. - /// - /// Handling effect infer variables happens separately from const infer variables - /// because we do not want to reuse any of the const infer machinery. If we try to - /// relate an effect variable with a normal one, we would ICE, which can catch bugs - /// where we are not correctly using the effect var for an effect param. Fallback - /// is also implemented on top of having separate effect and normal const variables. - #[encodable] - #[orderable] - #[debug_format = "?{}e"] - #[gate_rustc_only] - pub struct EffectVid {} -} - /// An inference variable for a const, for use in const generics. #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable))] pub enum InferConst { /// Infer the value of the const. Var(ConstVid), - /// Infer the value of the effect. - /// - /// For why this is separate from the `Var` variant above, see the - /// documentation on `EffectVid`. - EffectVar(EffectVid), /// A fresh const variable. See `infer::freshen` for more details. Fresh(u32), } @@ -118,7 +98,6 @@ impl fmt::Debug for InferConst { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { InferConst::Var(var) => write!(f, "{var:?}"), - InferConst::EffectVar(var) => write!(f, "{var:?}"), InferConst::Fresh(var) => write!(f, "Fresh({var:?})"), } } @@ -128,7 +107,7 @@ impl fmt::Debug for InferConst { impl HashStable for InferConst { fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { match self { - InferConst::Var(_) | InferConst::EffectVar(_) => { + InferConst::Var(_) => { panic!("const variables should not be hashed: {self:?}") } InferConst::Fresh(i) => i.hash_stable(hcx, hasher), diff --git a/compiler/rustc_type_ir/src/effects.rs b/compiler/rustc_type_ir/src/effects.rs deleted file mode 100644 index ab43533dd869..000000000000 --- a/compiler/rustc_type_ir/src/effects.rs +++ /dev/null @@ -1,59 +0,0 @@ -use crate::Interner; -use crate::inherent::*; -use crate::lang_items::TraitSolverLangItem::{EffectsMaybe, EffectsNoRuntime, EffectsRuntime}; - -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum EffectKind { - Maybe, - Runtime, - NoRuntime, -} - -impl EffectKind { - pub fn try_from_def_id(cx: I, def_id: I::DefId) -> Option { - if cx.is_lang_item(def_id, EffectsMaybe) { - Some(EffectKind::Maybe) - } else if cx.is_lang_item(def_id, EffectsRuntime) { - Some(EffectKind::Runtime) - } else if cx.is_lang_item(def_id, EffectsNoRuntime) { - Some(EffectKind::NoRuntime) - } else { - None - } - } - - pub fn to_def_id(self, cx: I) -> I::DefId { - let lang_item = match self { - EffectKind::Maybe => EffectsMaybe, - EffectKind::NoRuntime => EffectsNoRuntime, - EffectKind::Runtime => EffectsRuntime, - }; - - cx.require_lang_item(lang_item) - } - - pub fn try_from_ty(cx: I, ty: I::Ty) -> Option { - if let crate::Adt(def, _) = ty.kind() { - Self::try_from_def_id(cx, def.def_id()) - } else { - None - } - } - - pub fn to_ty(self, cx: I) -> I::Ty { - I::Ty::new_adt(cx, cx.adt_def(self.to_def_id(cx)), Default::default()) - } - - /// Returns an intersection between two effect kinds. If one effect kind - /// is more permissive than the other (e.g. `Maybe` vs `Runtime`), this - /// returns the less permissive effect kind (`Runtime`). - pub fn intersection(a: Self, b: Self) -> Option { - use EffectKind::*; - match (a, b) { - (Maybe, x) | (x, Maybe) => Some(x), - (Runtime, Runtime) => Some(Runtime), - (NoRuntime, NoRuntime) => Some(NoRuntime), - (Runtime, NoRuntime) | (NoRuntime, Runtime) => None, - } - } -} diff --git a/compiler/rustc_type_ir/src/elaborate.rs b/compiler/rustc_type_ir/src/elaborate.rs index dac45ff2aba3..56a72f943ab4 100644 --- a/compiler/rustc_type_ir/src/elaborate.rs +++ b/compiler/rustc_type_ir/src/elaborate.rs @@ -4,7 +4,6 @@ use smallvec::smallvec; use crate::data_structures::HashSet; use crate::inherent::*; -use crate::lang_items::TraitSolverLangItem; use crate::outlives::{Component, push_outlives_components}; use crate::{self as ty, Interner, Upcast as _}; @@ -130,70 +129,6 @@ impl> Elaborator { return; } - // HACK(effects): The following code is required to get implied bounds for effects associated - // types to work with super traits. - // - // Suppose `data` is a trait predicate with the form `::Fx: EffectsCompat` - // and we know that `trait Tr: ~const SuperTr`, we need to elaborate this predicate into - // `::Fx: EffectsCompat`. - // - // Since the semantics for elaborating bounds about effects is equivalent to elaborating - // bounds about super traits (elaborate `T: Tr` into `T: SuperTr`), we place effects elaboration - // next to super trait elaboration. - if cx.is_lang_item(data.def_id(), TraitSolverLangItem::EffectsCompat) - && matches!(self.mode, Filter::All) - { - // first, ensure that the predicate we've got looks like a `::Fx: EffectsCompat`. - if let ty::Alias(ty::AliasTyKind::Projection, alias_ty) = data.self_ty().kind() - { - // look for effects-level bounds that look like `::Fx: TyCompat<::Fx>` - // on the trait, which is proof to us that `Tr: ~const SuperTr`. We're looking for bounds on the - // associated trait, so we use `explicit_implied_predicates_of` since it gives us more than just - // `Self: SuperTr` bounds. - let bounds = cx.explicit_implied_predicates_of(cx.parent(alias_ty.def_id)); - - // instantiate the implied bounds, so we get `::Fx` and not `::Fx`. - let elaborated = bounds.iter_instantiated(cx, alias_ty.args).filter_map( - |(clause, _)| { - let ty::ClauseKind::Trait(tycompat_bound) = - clause.kind().skip_binder() - else { - return None; - }; - if !cx.is_lang_item( - tycompat_bound.def_id(), - TraitSolverLangItem::EffectsTyCompat, - ) { - return None; - } - - // extract `::Fx` from the `TyCompat` bound. - let supertrait_effects_ty = - tycompat_bound.trait_ref.args.type_at(1); - let ty::Alias(ty::AliasTyKind::Projection, supertrait_alias_ty) = - supertrait_effects_ty.kind() - else { - return None; - }; - - // The self types (`T`) must be equal for `::Fx` and `::Fx`. - if supertrait_alias_ty.self_ty() != alias_ty.self_ty() { - return None; - }; - - // replace the self type in the original bound `::Fx: EffectsCompat` - // to the effects type of the super trait. (`::Fx`) - let elaborated_bound = data.with_self_ty(cx, supertrait_effects_ty); - Some( - elaboratable - .child(bound_clause.rebind(elaborated_bound).upcast(cx)), - ) - }, - ); - self.extend_deduped(elaborated); - } - } - let map_to_child_clause = |(index, (clause, span)): (usize, (I::Clause, I::Span))| { elaboratable.child_with_derived_cause( diff --git a/compiler/rustc_type_ir/src/infer_ctxt.rs b/compiler/rustc_type_ir/src/infer_ctxt.rs index b9f5cde653ea..7c6a3c65ebfb 100644 --- a/compiler/rustc_type_ir/src/infer_ctxt.rs +++ b/compiler/rustc_type_ir/src/infer_ctxt.rs @@ -38,10 +38,6 @@ pub trait InferCtxtLike: Sized { &self, vid: ty::ConstVid, ) -> ::Const; - fn opportunistic_resolve_effect_var( - &self, - vid: ty::EffectVid, - ) -> ::Const; fn opportunistic_resolve_lt_var( &self, vid: ty::RegionVid, @@ -71,7 +67,6 @@ pub trait InferCtxtLike: Sized { fn equate_int_vids_raw(&self, a: ty::IntVid, b: ty::IntVid); fn equate_float_vids_raw(&self, a: ty::FloatVid, b: ty::FloatVid); fn equate_const_vids_raw(&self, a: ty::ConstVid, b: ty::ConstVid); - fn equate_effect_vids_raw(&self, a: ty::EffectVid, b: ty::EffectVid); fn instantiate_ty_var_raw>( &self, @@ -83,11 +78,6 @@ pub trait InferCtxtLike: Sized { ) -> RelateResult; fn instantiate_int_var_raw(&self, vid: ty::IntVid, value: ty::IntVarValue); fn instantiate_float_var_raw(&self, vid: ty::FloatVid, value: ty::FloatVarValue); - fn instantiate_effect_var_raw( - &self, - vid: ty::EffectVid, - value: ::Const, - ); fn instantiate_const_var_raw>( &self, relation: &mut R, diff --git a/compiler/rustc_type_ir/src/lang_items.rs b/compiler/rustc_type_ir/src/lang_items.rs index c680c8447460..d6ca22a90a4d 100644 --- a/compiler/rustc_type_ir/src/lang_items.rs +++ b/compiler/rustc_type_ir/src/lang_items.rs @@ -20,13 +20,6 @@ pub enum TraitSolverLangItem { Destruct, DiscriminantKind, DynMetadata, - EffectsCompat, - EffectsIntersection, - EffectsIntersectionOutput, - EffectsMaybe, - EffectsNoRuntime, - EffectsRuntime, - EffectsTyCompat, Fn, FnMut, FnOnce, diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 9e6d1f424ba4..e7ca24178cbf 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -43,7 +43,6 @@ mod macros; mod binder; mod canonical; mod const_kind; -mod effects; mod flags; mod generic_arg; mod infer_ctxt; @@ -67,7 +66,6 @@ pub use canonical::*; #[cfg(feature = "nightly")] pub use codec::*; pub use const_kind::*; -pub use effects::*; pub use flags::*; pub use generic_arg::*; pub use infer_ctxt::*; diff --git a/compiler/rustc_type_ir/src/relate/combine.rs b/compiler/rustc_type_ir/src/relate/combine.rs index 60a953801a47..17a3912730f5 100644 --- a/compiler/rustc_type_ir/src/relate/combine.rs +++ b/compiler/rustc_type_ir/src/relate/combine.rs @@ -179,23 +179,9 @@ where Ok(a) } - ( - ty::ConstKind::Infer(ty::InferConst::EffectVar(a_vid)), - ty::ConstKind::Infer(ty::InferConst::EffectVar(b_vid)), - ) => { - infcx.equate_effect_vids_raw(a_vid, b_vid); - Ok(a) - } - // All other cases of inference with other variables are errors. - ( - ty::ConstKind::Infer(ty::InferConst::Var(_) | ty::InferConst::EffectVar(_)), - ty::ConstKind::Infer(_), - ) - | ( - ty::ConstKind::Infer(_), - ty::ConstKind::Infer(ty::InferConst::Var(_) | ty::InferConst::EffectVar(_)), - ) => { + (ty::ConstKind::Infer(ty::InferConst::Var(_)), ty::ConstKind::Infer(_)) + | (ty::ConstKind::Infer(_), ty::ConstKind::Infer(ty::InferConst::Var(_))) => { panic!( "tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var): {a:?} and {b:?}" ) @@ -211,16 +197,6 @@ where Ok(a) } - (ty::ConstKind::Infer(ty::InferConst::EffectVar(vid)), _) => { - infcx.instantiate_effect_var_raw(vid, b); - Ok(b) - } - - (_, ty::ConstKind::Infer(ty::InferConst::EffectVar(vid))) => { - infcx.instantiate_effect_var_raw(vid, a); - Ok(a) - } - (ty::ConstKind::Unevaluated(..), _) | (_, ty::ConstKind::Unevaluated(..)) if infcx.cx().features().generic_const_exprs() || infcx.next_trait_solver() => { diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index 9e6fbc8ea0c1..8db1258b65f7 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -1393,7 +1393,6 @@ pub struct Generics { pub param_def_id_to_index: Vec<(GenericDef, u32)>, pub has_self: bool, pub has_late_bound_regions: Option, - pub host_effect_index: Option, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index aed6be4c6277..1237fc82a171 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -1069,47 +1069,3 @@ pub trait FnPtr: Copy + Clone { pub macro SmartPointer($item:item) { /* compiler built-in */ } - -// Support traits and types for the desugaring of const traits and -// `~const` bounds. Not supposed to be used by anything other than -// the compiler. -#[doc(hidden)] -#[unstable( - feature = "effect_types", - issue = "none", - reason = "internal module for implementing effects" -)] -#[allow(missing_debug_implementations)] // these unit structs don't need `Debug` impls. -pub mod effects { - #[lang = "EffectsNoRuntime"] - pub struct NoRuntime; - #[lang = "EffectsMaybe"] - pub struct Maybe; - #[lang = "EffectsRuntime"] - pub struct Runtime; - - #[lang = "EffectsCompat"] - pub trait Compat<#[rustc_runtime] const RUNTIME: bool> {} - - impl Compat for NoRuntime {} - impl Compat for Runtime {} - impl<#[rustc_runtime] const RUNTIME: bool> Compat for Maybe {} - - #[lang = "EffectsTyCompat"] - #[marker] - pub trait TyCompat {} - - impl TyCompat for T {} - impl TyCompat for T {} - - #[lang = "EffectsIntersection"] - pub trait Intersection { - #[lang = "EffectsIntersectionOutput"] - type Output: ?Sized; - } - - // FIXME(effects): remove this after next trait solver lands - impl Intersection for () { - type Output = Maybe; - } -} diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index d966f9931045..31e4e79c00a7 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -156,7 +156,7 @@ fn clean_param_env<'tcx>( .iter() .inspect(|param| { if cfg!(debug_assertions) { - debug_assert!(!param.is_anonymous_lifetime() && !param.is_host_effect()); + debug_assert!(!param.is_anonymous_lifetime()); if let ty::GenericParamDefKind::Type { synthetic, .. } = param.kind { debug_assert!(!synthetic && param.name != kw::SelfUpper); } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index bf168809e28c..861ca70cd83d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -542,7 +542,7 @@ fn clean_generic_param_def( synthetic, }) } - ty::GenericParamDefKind::Const { has_default, synthetic, is_host_effect: _ } => { + ty::GenericParamDefKind::Const { has_default, synthetic } => { (def.name, GenericParamDefKind::Const { ty: Box::new(clean_middle_ty( ty::Binder::dummy( @@ -617,7 +617,7 @@ fn clean_generic_param<'tcx>( synthetic, }) } - hir::GenericParamKind::Const { ty, default, synthetic, is_host_effect: _ } => { + hir::GenericParamKind::Const { ty, default, synthetic } => { (param.name.ident().name, GenericParamDefKind::Const { ty: Box::new(clean_ty(ty, cx)), default: default.map(|ct| { @@ -797,7 +797,7 @@ fn clean_ty_generics<'tcx>( } true } - ty::GenericParamDefKind::Const { is_host_effect, .. } => !is_host_effect, + ty::GenericParamDefKind::Const { .. } => true, }) .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx)) .collect(); diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 6090de16d55b..c8cb9267eb26 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1366,8 +1366,7 @@ impl GenericParamDef { pub(crate) fn is_synthetic_param(&self) -> bool { match self.kind { - GenericParamDefKind::Lifetime { .. } => false, - GenericParamDefKind::Const { synthetic: is_host_effect, .. } => is_host_effect, + GenericParamDefKind::Lifetime { .. } | GenericParamDefKind::Const { .. } => false, GenericParamDefKind::Type { synthetic, .. } => synthetic, } } diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index fdf628b50fbe..d3a545fe0b61 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -114,10 +114,6 @@ pub(crate) fn clean_middle_generic_args<'tcx>( // Elide internal host effect args. let param = generics.param_at(index, cx.tcx); - if param.is_host_effect() { - return None; - } - let arg = ty::Binder::bind_with_vars(arg, bound_vars); // Elide arguments that coincide with their default. diff --git a/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs index 91ec120adbf6..3021f21df121 100644 --- a/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs @@ -207,16 +207,7 @@ fn path_segment_certainty( if cx.tcx.res_generics_def_id(path_segment.res).is_some() { let generics = cx.tcx.generics_of(def_id); - let own_count = generics.own_params.len() - - usize::from(generics.host_effect_index.is_some_and(|index| { - // Check that the host index actually belongs to this resolution. - // E.g. for `Add::add`, host_effect_index is `Some(2)`, but it's part of the parent `Add` - // trait's generics. - // Add params: [Self#0, Rhs#1, host#2] parent_count=0, count=3 - // Add::add params: [] parent_count=3, count=3 - // (3..3).contains(&host_effect_index) => false - (generics.parent_count..generics.count()).contains(&index) - })); + let own_count = generics.own_params.len(); let lhs = if (parent_certainty.is_certain() || generics.parent_count == 0) && own_count == 0 { Certainty::Certain(None) } else { @@ -310,8 +301,7 @@ fn type_is_inferable_from_arguments(cx: &LateContext<'_>, expr: &Expr<'_>) -> bo // Check that all type parameters appear in the functions input types. (0..(generics.parent_count + generics.own_params.len()) as u32).all(|index| { - Some(index as usize) == generics.host_effect_index - || fn_sig + fn_sig .inputs() .iter() .any(|input_ty| contains_param(*input_ty.skip_binder(), index)) diff --git a/tests/ui/traits/const-traits/const-fns-are-early-bound.rs b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs index b87387f4d5de..59a61e4f954d 100644 --- a/tests/ui/traits/const-traits/const-fns-are-early-bound.rs +++ b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs @@ -86,51 +86,3 @@ trait Tuple {} trait LegacyReceiver {} impl LegacyReceiver for &T {} - -impl LegacyReceiver for &mut T {} - -#[stable(feature = "minicore", since = "1.0.0")] -pub mod effects { - use super::Sized; - - #[lang = "EffectsNoRuntime"] - #[stable(feature = "minicore", since = "1.0.0")] - pub struct NoRuntime; - #[lang = "EffectsMaybe"] - #[stable(feature = "minicore", since = "1.0.0")] - pub struct Maybe; - #[lang = "EffectsRuntime"] - #[stable(feature = "minicore", since = "1.0.0")] - pub struct Runtime; - - #[lang = "EffectsCompat"] - #[stable(feature = "minicore", since = "1.0.0")] - pub trait Compat<#[rustc_runtime] const RUNTIME: bool> {} - - #[stable(feature = "minicore", since = "1.0.0")] - impl Compat for NoRuntime {} - #[stable(feature = "minicore", since = "1.0.0")] - impl Compat for Runtime {} - #[stable(feature = "minicore", since = "1.0.0")] - impl<#[rustc_runtime] const RUNTIME: bool> Compat for Maybe {} - - #[lang = "EffectsTyCompat"] - #[marker] - #[stable(feature = "minicore", since = "1.0.0")] - pub trait TyCompat {} - - #[stable(feature = "minicore", since = "1.0.0")] - impl TyCompat for T {} - #[stable(feature = "minicore", since = "1.0.0")] - impl TyCompat for Maybe {} - #[stable(feature = "minicore", since = "1.0.0")] - impl TyCompat for T {} - - #[lang = "EffectsIntersection"] - #[stable(feature = "minicore", since = "1.0.0")] - pub trait Intersection { - #[lang = "EffectsIntersectionOutput"] - #[stable(feature = "minicore", since = "1.0.0")] - type Output: ?Sized; - } -} diff --git a/tests/ui/traits/const-traits/effects/minicore.rs b/tests/ui/traits/const-traits/effects/minicore.rs index 9b615450c68f..a756f4d9f6c5 100644 --- a/tests/ui/traits/const-traits/effects/minicore.rs +++ b/tests/ui/traits/const-traits/effects/minicore.rs @@ -536,35 +536,3 @@ fn test_const_eval_select() { const_eval_select((), const_fn, rt_fn); } - -mod effects { - use super::Sized; - - #[lang = "EffectsNoRuntime"] - pub struct NoRuntime; - #[lang = "EffectsMaybe"] - pub struct Maybe; - #[lang = "EffectsRuntime"] - pub struct Runtime; - - #[lang = "EffectsCompat"] - pub trait Compat<#[rustc_runtime] const RUNTIME: bool> {} - - impl Compat for NoRuntime {} - impl Compat for Runtime {} - impl<#[rustc_runtime] const RUNTIME: bool> Compat for Maybe {} - - #[lang = "EffectsTyCompat"] - #[marker] - pub trait TyCompat {} - - impl TyCompat for T {} - impl TyCompat for Maybe {} - impl TyCompat for T {} - - #[lang = "EffectsIntersection"] - pub trait Intersection { - #[lang = "EffectsIntersectionOutput"] - type Output: ?Sized; - } -} From cde29b9ec9c49dfdebe06f7e97df4a322f27bd6a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 20 Oct 2024 19:49:11 +0000 Subject: [PATCH 202/366] Implement const effect predicate in new solver --- compiler/rustc_hir_analysis/src/bounds.rs | 11 + .../src/check/compare_impl_item.rs | 110 ++++++- .../rustc_hir_analysis/src/check/wfcheck.rs | 37 ++- compiler/rustc_hir_analysis/src/collect.rs | 2 + .../src/collect/item_bounds.rs | 36 ++- .../src/collect/predicates_of.rs | 239 +++++++++++++- .../src/hir_ty_lowering/bounds.rs | 42 ++- .../src/hir_ty_lowering/dyn_compatibility.rs | 3 +- .../src/hir_ty_lowering/mod.rs | 51 ++- .../src/impl_wf_check/min_specialization.rs | 3 +- .../src/outlives/explicit.rs | 3 +- compiler/rustc_hir_typeck/src/callee.rs | 47 ++- .../src/fn_ctxt/inspect_obligations.rs | 1 + compiler/rustc_hir_typeck/src/method/probe.rs | 3 +- .../rustc_infer/src/infer/outlives/mod.rs | 14 +- compiler/rustc_lint/src/builtin.rs | 4 +- .../src/rmeta/decoder/cstore_impl.rs | 2 + compiler/rustc_metadata/src/rmeta/encoder.rs | 8 +- compiler/rustc_metadata/src/rmeta/mod.rs | 2 + compiler/rustc_middle/src/query/erase.rs | 1 + compiler/rustc_middle/src/query/mod.rs | 18 ++ compiler/rustc_middle/src/ty/codec.rs | 11 + compiler/rustc_middle/src/ty/context.rs | 32 +- compiler/rustc_middle/src/ty/flags.rs | 6 + compiler/rustc_middle/src/ty/generics.rs | 70 +++++ compiler/rustc_middle/src/ty/mod.rs | 13 +- compiler/rustc_middle/src/ty/parameterized.rs | 1 + compiler/rustc_middle/src/ty/predicate.rs | 4 + compiler/rustc_middle/src/ty/print/pretty.rs | 10 + .../src/solve/effect_goals.rs | 296 ++++++++++++++++++ .../src/solve/eval_ctxt/mod.rs | 3 + .../rustc_next_trait_solver/src/solve/mod.rs | 1 + compiler/rustc_privacy/src/lib.rs | 4 + .../rustc_smir/src/rustc_smir/convert/ty.rs | 3 + .../traits/fulfillment_errors.rs | 44 +-- .../src/traits/auto_trait.rs | 3 +- .../src/traits/dyn_compatibility.rs | 4 +- .../src/traits/fulfill.rs | 10 +- .../query/type_op/implied_outlives_bounds.rs | 2 + .../src/traits/select/mod.rs | 7 + .../rustc_trait_selection/src/traits/wf.rs | 5 + .../src/normalize_erasing_regions.rs | 1 + compiler/rustc_ty_utils/src/ty.rs | 9 + compiler/rustc_type_ir/src/elaborate.rs | 10 + compiler/rustc_type_ir/src/inherent.rs | 8 + compiler/rustc_type_ir/src/interner.rs | 11 + compiler/rustc_type_ir/src/ir_print.rs | 5 +- compiler/rustc_type_ir/src/predicate.rs | 65 ++++ compiler/rustc_type_ir/src/predicate_kind.rs | 7 + src/librustdoc/clean/mod.rs | 4 +- tests/crashes/118320.rs | 14 - tests/crashes/119924-6.rs | 15 - .../const-generics/issues/issue-88119.stderr | 18 -- .../ui/consts/const-block-const-bound.stderr | 10 +- ...constifconst-call-in-const-position.stderr | 20 +- tests/ui/consts/fn_trait_refs.stderr | 74 ++++- .../unstable-const-fn-in-libcore.stderr | 10 +- tests/ui/delegation/ice-issue-124347.rs | 2 +- tests/ui/delegation/ice-issue-124347.stderr | 12 +- tests/ui/delegation/unsupported.rs | 2 +- tests/ui/delegation/unsupported.stderr | 12 +- .../impl-trait/normalize-tait-in-const.stderr | 18 +- .../ui/specialization/const_trait_impl.stderr | 64 ++-- .../assoc-type-const-bound-usage-0.stderr | 41 +-- .../assoc-type-const-bound-usage-1.stderr | 41 +-- .../call-const-trait-method-fail.stderr | 15 +- .../call-const-trait-method-pass.stderr | 14 +- .../const-traits/call-generic-in-impl.stderr | 16 +- .../call-generic-method-chain.stderr | 18 +- .../call-generic-method-dup-bound.stderr | 18 +- .../call-generic-method-nonconst.stderr | 16 +- .../call-generic-method-pass.stderr | 10 +- .../const-bounds-non-const-trait.rs | 1 + .../const-bounds-non-const-trait.stderr | 12 +- .../const-closure-trait-method-fail.stderr | 16 +- .../const-closure-trait-method.stderr | 16 +- .../traits/const-traits/const-closures.stderr | 34 +- .../const-default-method-bodies.stderr | 17 +- .../const-traits/const-drop-bound.stderr | 26 +- .../const-traits/const-drop-fail-2.stderr | 10 +- .../const-drop-fail.precise.stderr | 10 +- .../const-traits/const-drop-fail.stock.stderr | 10 +- .../const-traits/const-drop.precise.stderr | 24 +- .../const-traits/const-drop.stock.stderr | 24 +- .../const-traits/const-fns-are-early-bound.rs | 2 + .../const-fns-are-early-bound.stderr | 20 -- .../const-traits/const-impl-trait.stderr | 249 --------------- .../derive-const-with-params.stderr | 11 +- .../const-traits/cross-crate.gatednc.stderr | 17 +- ...-method-body-is-const-same-trait-ck.stderr | 17 +- .../const-traits/effects/minicore.stderr | 8 +- ...o-explicit-const-params-cross-crate.stderr | 16 +- .../effects/no-explicit-const-params.rs | 1 - .../effects/no-explicit-const-params.stderr | 30 +- .../effects/spec-effectvar-ice.rs | 3 +- .../effects/spec-effectvar-ice.stderr | 32 +- .../ice-123664-unexpected-bound-var.rs | 1 + .../ice-123664-unexpected-bound-var.stderr | 10 +- .../ui/traits/const-traits/issue-92111.stderr | 10 +- .../non-const-op-in-closure-in-const.stderr | 16 +- ...t-bound-non-const-specialized-bound.stderr | 32 +- .../const-default-const-specialized.stderr | 25 +- .../specialization/default-keyword.rs | 3 +- .../specialization/default-keyword.stderr | 12 - .../issue-95186-specialize-on-tilde-const.rs | 3 +- ...sue-95186-specialize-on-tilde-const.stderr | 43 --- ...87-same-trait-bound-different-constness.rs | 3 +- ...ame-trait-bound-different-constness.stderr | 43 --- ...non-const-default-const-specialized.stderr | 25 +- .../specializing-constness-2.stderr | 25 +- .../const-traits/specializing-constness.rs | 2 - .../specializing-constness.stderr | 14 +- .../super-traits-fail-2.ny.stderr | 18 +- .../const-traits/super-traits-fail-2.rs | 4 +- .../super-traits-fail-2.yn.stderr | 17 +- .../super-traits-fail-2.yy.stderr | 17 +- .../super-traits-fail-3.nn.stderr | 12 +- .../super-traits-fail-3.ny.stderr | 18 +- .../const-traits/super-traits-fail-3.rs | 5 +- .../super-traits-fail-3.yn.stderr | 29 +- .../traits/const-traits/super-traits-fail.rs | 1 - .../const-traits/super-traits-fail.stderr | 23 +- .../tilde-const-and-const-params.rs | 2 - .../tilde-const-and-const-params.stderr | 25 +- .../const-traits/trait-where-clause-const.rs | 6 +- .../trait-where-clause-const.stderr | 51 +-- .../unsatisfied-const-trait-bound.stderr | 25 +- 127 files changed, 1702 insertions(+), 1170 deletions(-) create mode 100644 compiler/rustc_next_trait_solver/src/solve/effect_goals.rs delete mode 100644 tests/crashes/118320.rs delete mode 100644 tests/crashes/119924-6.rs delete mode 100644 tests/ui/traits/const-traits/const-fns-are-early-bound.stderr delete mode 100644 tests/ui/traits/const-traits/const-impl-trait.stderr delete mode 100644 tests/ui/traits/const-traits/specialization/default-keyword.stderr delete mode 100644 tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.stderr delete mode 100644 tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.stderr diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index d0c45a7c04c7..7a919bb25005 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -81,6 +81,17 @@ impl<'tcx> Bounds<'tcx> { self.clauses.insert(0, (trait_ref.upcast(tcx), span)); } + /// Push a `const` or `~const` bound as a `HostEffect` predicate. + pub(crate) fn push_const_bound( + &mut self, + tcx: TyCtxt<'tcx>, + bound_trait_ref: ty::PolyTraitRef<'tcx>, + host: ty::HostPolarity, + span: Span, + ) { + self.clauses.push((bound_trait_ref.to_host_effect_clause(tcx, host), span)); + } + pub(crate) fn clauses( &self, // FIXME(effects): remove tcx diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 7a56b3784f8b..439e6d784283 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -181,6 +181,7 @@ fn compare_method_predicate_entailment<'tcx>( }); // Create mapping from trait method to impl method. + let impl_def_id = impl_m.container_id(tcx); let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto( tcx, impl_m.container_id(tcx), @@ -204,6 +205,24 @@ fn compare_method_predicate_entailment<'tcx>( trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate), ); + // FIXME(effects): This should be replaced with a more dedicated method. + let check_const_if_const = tcx.constness(impl_def_id) == hir::Constness::Const; + if check_const_if_const { + // Augment the hybrid param-env with the const conditions + // of the impl header and the trait method. + hybrid_preds.extend( + tcx.const_conditions(impl_def_id) + .instantiate_identity(tcx) + .into_iter() + .chain( + tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args), + ) + .map(|(trait_ref, _)| { + trait_ref.to_host_effect_clause(tcx, ty::HostPolarity::Maybe) + }), + ); + } + let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id); let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause); @@ -230,6 +249,34 @@ fn compare_method_predicate_entailment<'tcx>( ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate)); } + // If we're within a const implementation, we need to make sure that the method + // does not assume stronger `~const` bounds than the trait definition. + // + // This registers the `~const` bounds of the impl method, which we will prove + // using the hybrid param-env that we earlier augmented with the const conditions + // from the impl header and trait method declaration. + if check_const_if_const { + for (const_condition, span) in + tcx.const_conditions(impl_m.def_id).instantiate_own_identity() + { + let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); + let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition); + + let cause = + ObligationCause::new(span, impl_m_def_id, ObligationCauseCode::CompareImplItem { + impl_item_def_id: impl_m_def_id, + trait_item_def_id: trait_m.def_id, + kind: impl_m.kind, + }); + ocx.register_obligation(traits::Obligation::new( + tcx, + cause, + param_env, + const_condition.to_host_effect_clause(tcx, ty::HostPolarity::Maybe), + )); + } + } + // We now need to check that the signature of the impl method is // compatible with that of the trait method. We do this by // checking that `impl_fty <: trait_fty`. @@ -1846,9 +1893,10 @@ fn compare_type_predicate_entailment<'tcx>( trait_ty: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { + let impl_def_id = impl_ty.container_id(tcx); let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto( tcx, - impl_ty.container_id(tcx), + impl_def_id, impl_trait_ref.args, ); @@ -1856,7 +1904,9 @@ fn compare_type_predicate_entailment<'tcx>( let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id); let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity(); - if impl_ty_own_bounds.len() == 0 { + let impl_ty_own_const_conditions = + tcx.const_conditions(impl_ty.def_id).instantiate_own_identity(); + if impl_ty_own_bounds.len() == 0 && impl_ty_own_const_conditions.len() == 0 { // Nothing to check. return Ok(()); } @@ -1881,6 +1931,23 @@ fn compare_type_predicate_entailment<'tcx>( let impl_ty_span = tcx.def_span(impl_ty_def_id); let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id); + let check_const_if_const = tcx.constness(impl_def_id) == hir::Constness::Const; + if check_const_if_const { + // Augment the hybrid param-env with the const conditions + // of the impl header and the trait assoc type. + hybrid_preds.extend( + tcx.const_conditions(impl_ty_predicates.parent.unwrap()) + .instantiate_identity(tcx) + .into_iter() + .chain( + tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args), + ) + .map(|(trait_ref, _)| { + trait_ref.to_host_effect_clause(tcx, ty::HostPolarity::Maybe) + }), + ); + } + let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause); debug!(caller_bounds=?param_env.caller_bounds()); @@ -1901,6 +1968,27 @@ fn compare_type_predicate_entailment<'tcx>( ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate)); } + if check_const_if_const { + // Validate the const conditions of the impl associated type. + for (const_condition, span) in impl_ty_own_const_conditions { + let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id); + let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition); + + let cause = + ObligationCause::new(span, impl_ty_def_id, ObligationCauseCode::CompareImplItem { + impl_item_def_id: impl_ty_def_id, + trait_item_def_id: trait_ty.def_id, + kind: impl_ty.kind, + }); + ocx.register_obligation(traits::Obligation::new( + tcx, + cause, + param_env, + const_condition.to_host_effect_clause(tcx, ty::HostPolarity::Maybe), + )); + } + } + // Check that all obligations are satisfied by the implementation's // version. let errors = ocx.select_all_or_error(); @@ -1983,7 +2071,7 @@ pub(super) fn check_type_bounds<'tcx>( ObligationCause::new(impl_ty_span, impl_ty_def_id, code) }; - let obligations: Vec<_> = tcx + let mut obligations: Vec<_> = tcx .explicit_item_bounds(trait_ty.def_id) .iter_instantiated_copied(tcx, rebased_args) .map(|(concrete_ty_bound, span)| { @@ -1991,6 +2079,22 @@ pub(super) fn check_type_bounds<'tcx>( traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound) }) .collect(); + + // Only in a const implementation do we need to check that the `~const` item bounds hold. + if tcx.constness(container_id) == hir::Constness::Const { + obligations.extend( + tcx.implied_const_bounds(trait_ty.def_id) + .iter_instantiated_copied(tcx, rebased_args) + .map(|(c, span)| { + traits::Obligation::new( + tcx, + mk_cause(span), + param_env, + c.to_host_effect_clause(tcx, ty::HostPolarity::Maybe), + ) + }), + ); + } debug!(item_bounds=?obligations); // Normalize predicates with the assumption that the GAT may always normalize diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 79e579841746..f0041a577424 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -32,7 +32,8 @@ use rustc_trait_selection::traits::misc::{ use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; use rustc_trait_selection::traits::{ - self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc, + self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt, + WellFormedLoc, }; use rustc_type_ir::TypeFlags; use rustc_type_ir::solve::NoSolution; @@ -86,7 +87,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { self.body_def_id, ObligationCauseCode::WellFormed(loc), ); - self.ocx.register_obligation(traits::Obligation::new( + self.ocx.register_obligation(Obligation::new( self.tcx(), cause, self.param_env, @@ -1173,7 +1174,7 @@ fn check_type_defn<'tcx>( wfcx.body_def_id, ObligationCauseCode::Misc, ); - wfcx.register_obligation(traits::Obligation::new( + wfcx.register_obligation(Obligation::new( tcx, cause, wfcx.param_env, @@ -1369,6 +1370,30 @@ fn check_impl<'tcx>( obligation.cause.span = hir_self_ty.span; } } + + // Ensure that the `~const` where clauses of the trait hold for the impl. + if tcx.constness(item.owner_id.def_id) == hir::Constness::Const { + for (bound, _) in + tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args) + { + let bound = wfcx.normalize( + item.span, + Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), + bound, + ); + wfcx.register_obligation(Obligation::new( + tcx, + ObligationCause::new( + hir_self_ty.span, + wfcx.body_def_id, + ObligationCauseCode::WellFormed(None), + ), + wfcx.param_env, + bound.to_host_effect_clause(tcx, ty::HostPolarity::Maybe), + )) + } + } + debug!(?obligations); wfcx.register_obligations(obligations); } @@ -1561,7 +1586,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id wfcx.body_def_id, ObligationCauseCode::WhereClause(def_id.to_def_id(), DUMMY_SP), ); - traits::Obligation::new(tcx, cause, wfcx.param_env, pred) + Obligation::new(tcx, cause, wfcx.param_env, pred) }); let predicates = predicates.instantiate_identity(tcx); @@ -1852,7 +1877,7 @@ fn receiver_is_implemented<'tcx>( let tcx = wfcx.tcx(); let trait_ref = ty::TraitRef::new(tcx, receiver_trait_def_id, [receiver_ty]); - let obligation = traits::Obligation::new(tcx, cause, wfcx.param_env, trait_ref); + let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref); if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) { true @@ -2188,7 +2213,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { .unwrap_or(obligation_span); } - let obligation = traits::Obligation::new( + let obligation = Obligation::new( tcx, traits::ObligationCause::new( span, diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index acc21d0994bf..f46b7a8bc9cc 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -77,6 +77,8 @@ pub fn provide(providers: &mut Providers) { explicit_supertraits_containing_assoc_item: predicates_of::explicit_supertraits_containing_assoc_item, trait_explicit_predicates_and_bounds: predicates_of::trait_explicit_predicates_and_bounds, + const_conditions: predicates_of::const_conditions, + implied_const_bounds: predicates_of::implied_const_bounds, type_param_predicates: predicates_of::type_param_predicates, trait_def, adt_def, diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 69ebd3a928a3..075faea3d2aa 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -40,7 +40,16 @@ fn associated_type_bounds<'tcx>( let mut bounds = Bounds::default(); icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds, ty::List::empty(), filter); // Associated types are implicitly sized unless a `?Sized` bound is found - icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span); + match filter { + PredicateFilter::All + | PredicateFilter::SelfOnly + | PredicateFilter::SelfThatDefines(_) + | PredicateFilter::SelfAndAssociatedTypeBounds => { + icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span); + } + // `ConstIfConst` is only interested in `~const` bounds. + PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {} + } let trait_def_id = tcx.local_parent(assoc_item_def_id); let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id); @@ -109,10 +118,19 @@ fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>( } else { // Only collect *self* type bounds if the filter is for self. match filter { - PredicateFilter::SelfOnly | PredicateFilter::SelfThatDefines(_) => { + PredicateFilter::All => {} + PredicateFilter::SelfOnly => { return None; } - PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {} + PredicateFilter::SelfThatDefines(_) + | PredicateFilter::SelfConstIfConst + | PredicateFilter::SelfAndAssociatedTypeBounds + | PredicateFilter::ConstIfConst => { + unreachable!( + "invalid predicate filter for \ + `remap_gat_vars_and_recurse_into_nested_projections`" + ) + } } clause_ty = alias_ty.self_ty(); @@ -308,7 +326,17 @@ fn opaque_type_bounds<'tcx>( let mut bounds = Bounds::default(); icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds, ty::List::empty(), filter); // Opaque types are implicitly sized unless a `?Sized` bound is found - icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span); + match filter { + PredicateFilter::All + | PredicateFilter::SelfOnly + | PredicateFilter::SelfThatDefines(_) + | PredicateFilter::SelfAndAssociatedTypeBounds => { + // Associated types are implicitly sized unless a `?Sized` bound is found + icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span); + } + //`ConstIfConst` is only interested in `~const` bounds. + PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {} + } debug!(?bounds); tcx.arena.alloc_from_iter(bounds.clauses(tcx)) diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index f9460ed5b473..ec5773d174f8 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -12,6 +12,7 @@ use rustc_span::symbol::Ident; use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument, trace}; +use super::item_bounds::explicit_item_bounds_with_filter; use crate::bounds::Bounds; use crate::collect::ItemCtxt; use crate::constrained_generic_params as cgp; @@ -685,29 +686,76 @@ pub(super) fn assert_only_contains_predicates_from<'tcx>( assert_eq!( trait_predicate.self_ty(), ty, - "expected `Self` predicate when computing `{filter:?}` implied bounds: {clause:?}" + "expected `Self` predicate when computing \ + `{filter:?}` implied bounds: {clause:?}" ); } ty::ClauseKind::Projection(projection_predicate) => { assert_eq!( projection_predicate.self_ty(), ty, - "expected `Self` predicate when computing `{filter:?}` implied bounds: {clause:?}" + "expected `Self` predicate when computing \ + `{filter:?}` implied bounds: {clause:?}" ); } ty::ClauseKind::TypeOutlives(outlives_predicate) => { assert_eq!( outlives_predicate.0, ty, - "expected `Self` predicate when computing `{filter:?}` implied bounds: {clause:?}" + "expected `Self` predicate when computing \ + `{filter:?}` implied bounds: {clause:?}" ); } ty::ClauseKind::RegionOutlives(_) | ty::ClauseKind::ConstArgHasType(_, _) | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(_) => { + | ty::ClauseKind::ConstEvaluatable(_) + | ty::ClauseKind::HostEffect(..) => { bug!( - "unexpected non-`Self` predicate when computing `{filter:?}` implied bounds: {clause:?}" + "unexpected non-`Self` predicate when computing \ + `{filter:?}` implied bounds: {clause:?}" + ); + } + } + } + } + PredicateFilter::ConstIfConst => { + for (clause, _) in bounds { + match clause.kind().skip_binder() { + ty::ClauseKind::HostEffect(ty::HostEffectPredicate { + trait_ref: _, + host: ty::HostPolarity::Maybe, + }) => {} + _ => { + bug!( + "unexpected non-`HostEffect` predicate when computing \ + `{filter:?}` implied bounds: {clause:?}" + ); + } + } + } + } + PredicateFilter::SelfConstIfConst => { + for (clause, _) in bounds { + match clause.kind().skip_binder() { + ty::ClauseKind::HostEffect(pred) => { + assert_eq!( + pred.host, + ty::HostPolarity::Maybe, + "expected `~const` predicate when computing `{filter:?}` \ + implied bounds: {clause:?}", + ); + assert_eq!( + pred.trait_ref.self_ty(), + ty, + "expected `Self` predicate when computing `{filter:?}` \ + implied bounds: {clause:?}" + ); + } + _ => { + bug!( + "unexpected non-`HostEffect` predicate when computing \ + `{filter:?}` implied bounds: {clause:?}" ); } } @@ -829,3 +877,184 @@ impl<'tcx> ItemCtxt<'tcx> { bounds.clauses(self.tcx).collect() } } + +/// Compute the conditions that need to hold for a conditionally-const item to be const. +/// That is, compute the set of `~const` where clauses for a given item. +/// +/// This query also computes the `~const` where clauses for associated types, which are +/// not "const", but which have item bounds which may be `~const`. These must hold for +/// the `~const` item bound to hold. +pub(super) fn const_conditions<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, +) -> ty::ConstConditions<'tcx> { + // This logic is spaghetti, and should be cleaned up. The current methods that are + // defined to deal with constness are very unintuitive. + if tcx.is_const_fn_raw(def_id.to_def_id()) { + // Ok, const fn or method in const trait. + } else { + match tcx.def_kind(def_id) { + DefKind::Trait => { + if !tcx.is_const_trait(def_id.to_def_id()) { + return Default::default(); + } + } + DefKind::Impl { .. } => { + // FIXME(effects): Should be using a dedicated function to + // test if this is a const trait impl. + if tcx.constness(def_id) != hir::Constness::Const { + return Default::default(); + } + } + DefKind::AssocTy | DefKind::AssocFn => { + let parent_def_id = tcx.local_parent(def_id).to_def_id(); + match tcx.associated_item(def_id).container { + ty::AssocItemContainer::TraitContainer => { + if !tcx.is_const_trait(parent_def_id) { + return Default::default(); + } + } + ty::AssocItemContainer::ImplContainer => { + // FIXME(effects): Should be using a dedicated function to + // test if this is a const trait impl. + if tcx.constness(parent_def_id) != hir::Constness::Const { + return Default::default(); + } + } + } + } + DefKind::Closure | DefKind::OpaqueTy => { + // Closures and RPITs will eventually have const conditions + // for `~const` bounds. + return Default::default(); + } + _ => return Default::default(), + } + } + + let (generics, trait_def_id_and_supertraits, has_parent) = match tcx.hir_node_by_def_id(def_id) + { + Node::Item(item) => match item.kind { + hir::ItemKind::Impl(impl_) => (impl_.generics, None, false), + hir::ItemKind::Fn(_, generics, _) => (generics, None, false), + hir::ItemKind::Trait(_, _, generics, supertraits, _) => { + (generics, Some((item.owner_id.def_id, supertraits)), false) + } + _ => return Default::default(), + }, + // While associated types are not really const, we do allow them to have `~const` + // bounds and where clauses. `const_conditions` is responsible for gathering + // these up so we can check them in `compare_type_predicate_entailment`, and + // in `HostEffect` goal computation. + Node::TraitItem(item) => match item.kind { + hir::TraitItemKind::Fn(_, _) | hir::TraitItemKind::Type(_, _) => { + (item.generics, None, true) + } + _ => return Default::default(), + }, + Node::ImplItem(item) => match item.kind { + hir::ImplItemKind::Fn(_, _) | hir::ImplItemKind::Type(_) => (item.generics, None, true), + _ => return Default::default(), + }, + _ => return Default::default(), + }; + + let icx = ItemCtxt::new(tcx, def_id); + let mut bounds = Bounds::default(); + + for pred in generics.predicates { + match pred { + hir::WherePredicate::BoundPredicate(bound_pred) => { + let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty); + let bound_vars = tcx.late_bound_vars(bound_pred.hir_id); + icx.lowerer().lower_bounds( + ty, + bound_pred.bounds.iter(), + &mut bounds, + bound_vars, + PredicateFilter::ConstIfConst, + ); + } + _ => {} + } + } + + if let Some((def_id, supertraits)) = trait_def_id_and_supertraits { + bounds.push_const_bound( + tcx, + ty::Binder::dummy(ty::TraitRef::identity(tcx, def_id.to_def_id())), + ty::HostPolarity::Maybe, + DUMMY_SP, + ); + + icx.lowerer().lower_bounds( + tcx.types.self_param, + supertraits.into_iter(), + &mut bounds, + ty::List::empty(), + PredicateFilter::ConstIfConst, + ); + } + + ty::ConstConditions { + parent: has_parent.then(|| tcx.local_parent(def_id).to_def_id()), + predicates: tcx.arena.alloc_from_iter(bounds.clauses(tcx).map(|(clause, span)| { + ( + clause.kind().map_bound(|clause| match clause { + ty::ClauseKind::HostEffect(ty::HostEffectPredicate { + trait_ref, + host: ty::HostPolarity::Maybe, + }) => trait_ref, + _ => bug!("converted {clause:?}"), + }), + span, + ) + })), + } +} + +pub(super) fn implied_const_bounds<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, +) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> { + let bounds = match tcx.hir_node_by_def_id(def_id) { + Node::Item(hir::Item { kind: hir::ItemKind::Trait(..), .. }) => { + if !tcx.is_const_trait(def_id.to_def_id()) { + return ty::EarlyBinder::bind(&[]); + } + + implied_predicates_with_filter( + tcx, + def_id.to_def_id(), + PredicateFilter::SelfConstIfConst, + ) + } + Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(..), .. }) => { + if !tcx.is_const_trait(tcx.local_parent(def_id).to_def_id()) { + return ty::EarlyBinder::bind(&[]); + } + + explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst) + } + Node::OpaqueTy(..) => { + // We should eventually collect the `~const` bounds on opaques. + return ty::EarlyBinder::bind(&[]); + } + _ => return ty::EarlyBinder::bind(&[]), + }; + + bounds.map_bound(|bounds| { + &*tcx.arena.alloc_from_iter(bounds.iter().copied().map(|(clause, span)| { + ( + clause.kind().map_bound(|clause| match clause { + ty::ClauseKind::HostEffect(ty::HostEffectPredicate { + trait_ref, + host: ty::HostPolarity::Maybe, + }) => trait_ref, + _ => bug!("converted {clause:?}"), + }), + span, + ) + })) + }) +} diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 2b0e1350108f..c902e85c2673 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -154,7 +154,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { for hir_bound in hir_bounds { // In order to avoid cycles, when we're lowering `SelfThatDefines`, // we skip over any traits that don't define the given associated type. - if let PredicateFilter::SelfThatDefines(assoc_name) = predicate_filter { if let Some(trait_ref) = hir_bound.trait_ref() && let Some(trait_did) = trait_ref.trait_def_id() @@ -193,6 +192,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); } hir::GenericBound::Outlives(lifetime) => { + // `ConstIfConst` is only interested in `~const` bounds. + if matches!( + predicate_filter, + PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst + ) { + continue; + } + let region = self.lower_lifetime(lifetime, RegionInferReason::OutlivesBound); bounds.push_region_bound( self.tcx(), @@ -392,21 +399,31 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }, ); - bounds.push_projection_bound( - tcx, - projection_term.map_bound(|projection_term| ty::ProjectionPredicate { - projection_term, - term, - }), - constraint.span, - ); + match predicate_filter { + PredicateFilter::All + | PredicateFilter::SelfOnly + | PredicateFilter::SelfThatDefines(_) + | PredicateFilter::SelfAndAssociatedTypeBounds => { + bounds.push_projection_bound( + tcx, + projection_term.map_bound(|projection_term| ty::ProjectionPredicate { + projection_term, + term, + }), + constraint.span, + ); + } + // `ConstIfConst` is only interested in `~const` bounds. + PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {} + } } // Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator` // to a bound involving a projection: `::Item: Debug`. hir::AssocItemConstraintKind::Bound { bounds: hir_bounds } => { match predicate_filter { - PredicateFilter::SelfOnly | PredicateFilter::SelfThatDefines(_) => {} - PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => { + PredicateFilter::All + | PredicateFilter::SelfAndAssociatedTypeBounds + | PredicateFilter::ConstIfConst => { let projection_ty = projection_term .map_bound(|projection_term| projection_term.expect_ty(self.tcx())); // Calling `skip_binder` is okay, because `lower_bounds` expects the `param_ty` @@ -421,6 +438,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { predicate_filter, ); } + PredicateFilter::SelfOnly + | PredicateFilter::SelfThatDefines(_) + | PredicateFilter::SelfConstIfConst => {} } } } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index 2cee7c77aa53..3449270564a7 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -78,7 +78,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ty::ClauseKind::RegionOutlives(_) | ty::ClauseKind::ConstArgHasType(..) | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(_) => { + | ty::ClauseKind::ConstEvaluatable(_) + | ty::ClauseKind::HostEffect(..) => { span_bug!(span, "did not expect {pred} clause in object bounds"); } } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index d2636c1573e0..863c077a9e03 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -81,6 +81,12 @@ pub enum PredicateFilter { /// For example, given `Self: Tr`, this would expand to `Self: Tr` /// and `::A: B`. SelfAndAssociatedTypeBounds, + + /// Filter only the `~const` bounds, which are lowered into `HostEffect` clauses. + ConstIfConst, + + /// Filter only the `~const` bounds which are *also* in the supertrait position. + SelfConstIfConst, } #[derive(Debug)] @@ -693,8 +699,49 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { bound_vars, ); - debug!(?poly_trait_ref); - bounds.push_trait_bound(tcx, poly_trait_ref, span, polarity); + match predicate_filter { + PredicateFilter::All + | PredicateFilter::SelfOnly + | PredicateFilter::SelfThatDefines(..) + | PredicateFilter::SelfAndAssociatedTypeBounds => { + debug!(?poly_trait_ref); + bounds.push_trait_bound(tcx, poly_trait_ref, span, polarity); + + match constness { + Some(ty::BoundConstness::Const) => { + if polarity == ty::PredicatePolarity::Positive { + bounds.push_const_bound( + tcx, + poly_trait_ref, + ty::HostPolarity::Const, + span, + ); + } + } + Some(ty::BoundConstness::ConstIfConst) => { + // We don't emit a const bound here, since that would mean that we + // unconditionally need to prove a `HostEffect` predicate, even when + // the predicates are being instantiated in a non-const context. This + // is instead handled in the `const_conditions` query. + } + None => {} + } + } + // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert + // `~const` bounds. All other predicates are handled in their respective queries. + // + // Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering + // here because we only call this on self bounds, and deal with the recursive case + // in `lower_assoc_item_constraint`. + PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => match constness { + Some(ty::BoundConstness::ConstIfConst) => { + if polarity == ty::PredicatePolarity::Positive { + bounds.push_const_bound(tcx, poly_trait_ref, ty::HostPolarity::Maybe, span); + } + } + None | Some(ty::BoundConstness::Const) => {} + }, + } let mut dup_constraints = FxIndexMap::default(); for constraint in trait_segment.args().constraints { diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 0355adfcb11e..a394fc2fbb19 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -530,6 +530,7 @@ fn trait_specialization_kind<'tcx>( | ty::ClauseKind::Projection(_) | ty::ClauseKind::ConstArgHasType(..) | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(..) => None, + | ty::ClauseKind::ConstEvaluatable(..) + | ty::ClauseKind::HostEffect(..) => None, } } diff --git a/compiler/rustc_hir_analysis/src/outlives/explicit.rs b/compiler/rustc_hir_analysis/src/outlives/explicit.rs index f576499ecac3..2c1d443f9512 100644 --- a/compiler/rustc_hir_analysis/src/outlives/explicit.rs +++ b/compiler/rustc_hir_analysis/src/outlives/explicit.rs @@ -53,7 +53,8 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { | ty::ClauseKind::Projection(_) | ty::ClauseKind::ConstArgHasType(_, _) | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(_) => {} + | ty::ClauseKind::ConstEvaluatable(_) + | ty::ClauseKind::HostEffect(..) => {} } } diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index b642ba03aee2..081cb8c18e65 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -836,14 +836,51 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn_sig.output() } - #[tracing::instrument(level = "debug", skip(self, _span))] + #[tracing::instrument(level = "debug", skip(self, span))] pub(super) fn enforce_context_effects( &self, - _span: Span, - _callee_did: DefId, - _callee_args: GenericArgsRef<'tcx>, + span: Span, + callee_did: DefId, + callee_args: GenericArgsRef<'tcx>, ) { - todo!() + // FIXME(effects): We should be enforcing these effects unconditionally. + // This can be done as soon as we convert the standard library back to + // using const traits, since if we were to enforce these conditions now, + // we'd fail on basically every builtin trait call (i.e. `1 + 2`). + if !self.tcx.features().effects() { + return; + } + + let host = match self.tcx.hir().body_const_context(self.body_id) { + Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => { + ty::HostPolarity::Const + } + Some(hir::ConstContext::ConstFn) => ty::HostPolarity::Maybe, + None => return, + }; + + // FIXME(effects): Should this be `is_const_fn_raw`? It depends on if we move + // const stability checking here too, I guess. + if self.tcx.is_const_fn(callee_did) + || self + .tcx + .trait_of_item(callee_did) + .is_some_and(|def_id| self.tcx.is_const_trait(def_id)) + { + let q = self.tcx.const_conditions(callee_did); + // FIXME(effects): Use this span with a better cause code. + for (cond, _) in q.instantiate(self.tcx, callee_args) { + self.register_predicate(Obligation::new( + self.tcx, + self.misc(span), + self.param_env, + cond.to_host_effect_clause(self.tcx, host), + )); + } + } else { + // FIXME(effects): This should eventually be caught here. + // For now, though, we defer some const checking to MIR. + } } fn confirm_overloaded_call( diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs index 693cb4465cc1..eb5fe3a86e4c 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs @@ -52,6 +52,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | ty::PredicateKind::AliasRelate(..) | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) | ty::PredicateKind::ConstEquate(..) + | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) | ty::PredicateKind::Ambiguous => false, } } diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index b60fa8bbfa14..569fdea11ce7 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -813,7 +813,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { | ty::ClauseKind::Projection(_) | ty::ClauseKind::ConstArgHasType(_, _) | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(_) => None, + | ty::ClauseKind::ConstEvaluatable(_) + | ty::ClauseKind::HostEffect(..) => None, } }); diff --git a/compiler/rustc_infer/src/infer/outlives/mod.rs b/compiler/rustc_infer/src/infer/outlives/mod.rs index e23bb1aaa563..1afe50e336da 100644 --- a/compiler/rustc_infer/src/infer/outlives/mod.rs +++ b/compiler/rustc_infer/src/infer/outlives/mod.rs @@ -24,19 +24,9 @@ pub fn explicit_outlives_bounds<'tcx>( param_env .caller_bounds() .into_iter() - .map(ty::Clause::kind) + .filter_map(ty::Clause::as_region_outlives_clause) .filter_map(ty::Binder::no_bound_vars) - .filter_map(move |kind| match kind { - ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { - Some(OutlivesBound::RegionSubRegion(r_b, r_a)) - } - ty::ClauseKind::Trait(_) - | ty::ClauseKind::TypeOutlives(_) - | ty::ClauseKind::Projection(_) - | ty::ClauseKind::ConstArgHasType(_, _) - | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(_) => None, - }) + .map(|ty::OutlivesPredicate(r_a, r_b)| OutlivesBound::RegionSubRegion(r_b, r_a)) } impl<'tcx> InferCtxt<'tcx> { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 71c667b2cd6b..cf889e958a9d 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1554,7 +1554,9 @@ impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { // Ignore bounds that a user can't type | ClauseKind::WellFormed(..) // FIXME(generic_const_exprs): `ConstEvaluatable` can be written - | ClauseKind::ConstEvaluatable(..) => continue, + | ClauseKind::ConstEvaluatable(..) + // Users don't write this directly, only via another trait ref. + | ty::ClauseKind::HostEffect(..) => continue, }; if predicate.is_global() { cx.emit_span_lint(TRIVIAL_BOUNDS, span, BuiltinTrivialBounds { diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index d4cbf6e13afb..71c7231a7882 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -275,6 +275,8 @@ provide! { tcx, def_id, other, cdata, impl_parent => { table } defaultness => { table_direct } constness => { table_direct } + const_conditions => { table } + implied_const_bounds => { table_defaulted_array } coerce_unsized_info => { Ok(cdata .root diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 80b979fe088f..a71d1993c6c1 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1423,6 +1423,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { let g = tcx.generics_of(def_id); record!(self.tables.generics_of[def_id] <- g); record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id)); + record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id)); let inferred_outlives = self.tcx.inferred_outlives_of(def_id); record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives); @@ -1456,7 +1457,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.tcx.explicit_super_predicates_of(def_id).skip_binder()); record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <- self.tcx.explicit_implied_predicates_of(def_id).skip_binder()); - + record_defaulted_array!(self.tables.implied_const_bounds[def_id] + <- self.tcx.implied_const_bounds(def_id).skip_binder()); let module_children = self.tcx.module_children_local(local_id); record_array!(self.tables.module_children_non_reexports[def_id] <- module_children.iter().map(|child| child.res.def_id().index)); @@ -1467,6 +1469,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.tcx.explicit_super_predicates_of(def_id).skip_binder()); record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <- self.tcx.explicit_implied_predicates_of(def_id).skip_binder()); + record_defaulted_array!(self.tables.implied_const_bounds[def_id] + <- self.tcx.implied_const_bounds(def_id).skip_binder()); } if let DefKind::Trait | DefKind::Impl { .. } = def_kind { let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); @@ -1649,6 +1653,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if let ty::AssocKind::Type = item.kind { self.encode_explicit_item_bounds(def_id); self.encode_explicit_item_super_predicates(def_id); + record_defaulted_array!(self.tables.implied_const_bounds[def_id] + <- self.tcx.implied_const_bounds(def_id).skip_binder()); } } AssocItemContainer::ImplContainer => { diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 8da1be805446..a00ca27aacc0 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -392,6 +392,7 @@ define_tables! { inferred_outlives_of: Table, Span)>>, explicit_super_predicates_of: Table, Span)>>, explicit_implied_predicates_of: Table, Span)>>, + implied_const_bounds: Table, Span)>>, inherent_impls: Table>, associated_types_for_impl_traits_in_associated_fn: Table>, opt_rpitit_info: Table>>, @@ -435,6 +436,7 @@ define_tables! { thir_abstract_const: Table>>>, impl_parent: Table, constness: Table, + const_conditions: Table>>, defaultness: Table, // FIXME(eddyb) perhaps compute this on the fly if cheap enough? coerce_unsized_info: Table>, diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index 48bf4ffced0c..5f8427bd707a 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -370,6 +370,7 @@ tcx_lifetime! { rustc_middle::ty::FnSig, rustc_middle::ty::GenericArg, rustc_middle::ty::GenericPredicates, + rustc_middle::ty::ConstConditions, rustc_middle::ty::inhabitedness::InhabitedPredicate, rustc_middle::ty::Instance, rustc_middle::ty::InstanceKind, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 0b751779501d..d03fc39c9ade 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -683,6 +683,24 @@ rustc_queries! { } } + query const_conditions( + key: DefId + ) -> ty::ConstConditions<'tcx> { + desc { |tcx| "computing the conditions for `{}` to be considered const", + tcx.def_path_str(key) + } + separate_provide_extern + } + + query implied_const_bounds( + key: DefId + ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> { + desc { |tcx| "computing the implied `~const` bounds for `{}`", + tcx.def_path_str(key) + } + separate_provide_extern + } + /// To avoid cycles within the predicates of a single item we compute /// per-type-parameter predicates for resolving `T::AssocTy`. query type_param_predicates( diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 7e533bc4291a..ef9dfdd2f962 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -386,6 +386,17 @@ impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [(ty::Claus } } +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> + for [(ty::PolyTraitRef<'tcx>, Span)] +{ + fn decode(decoder: &mut D) -> &'tcx Self { + decoder + .interner() + .arena + .alloc_from_iter((0..decoder.read_usize()).map(|_| Decodable::decode(decoder))) + } +} + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 281899647efb..c8fe6cbf4c65 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -78,10 +78,10 @@ use crate::traits::solve::{ use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; use crate::ty::{ self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Clauses, Const, GenericArg, GenericArgs, - GenericArgsRef, GenericParamDefKind, ImplPolarity, List, ListWithCachedTypeInfo, ParamConst, - ParamTy, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, - PredicatePolarity, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, - Visibility, + GenericArgsRef, GenericParamDefKind, HostPolarity, ImplPolarity, List, ListWithCachedTypeInfo, + ParamConst, ParamTy, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, + PredicateKind, PredicatePolarity, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, + TyKind, TyVid, Visibility, }; #[allow(rustc::usage_of_ty_tykind)] @@ -383,6 +383,28 @@ impl<'tcx> Interner for TyCtxt<'tcx> { self.explicit_implied_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied()) } + fn is_const_impl(self, def_id: DefId) -> bool { + self.constness(def_id) == hir::Constness::Const + } + + fn const_conditions( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>>> { + ty::EarlyBinder::bind( + self.const_conditions(def_id).instantiate_identity(self).into_iter().map(|(c, _)| c), + ) + } + + fn implied_const_bounds( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>>> { + ty::EarlyBinder::bind( + self.implied_const_bounds(def_id).iter_identity_copied().map(|(c, _)| c), + ) + } + fn has_target_features(self, def_id: DefId) -> bool { !self.codegen_fn_attrs(def_id).target_features.is_empty() } @@ -2189,7 +2211,7 @@ macro_rules! nop_slice_lift { nop_slice_lift! {ty::ValTree<'a> => ty::ValTree<'tcx>} TrivialLiftImpls! { - ImplPolarity, PredicatePolarity, Promoted + ImplPolarity, PredicatePolarity, Promoted, HostPolarity, } macro_rules! sty_debug_print { diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 39899f1d32be..704a197aa49d 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -265,6 +265,12 @@ impl FlagComputation { ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => { self.add_args(trait_pred.trait_ref.args); } + ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(ty::HostEffectPredicate { + trait_ref, + host: _, + })) => { + self.add_args(trait_ref.args); + } ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate( a, b, diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index e24a3f281fc5..ab1b8fa6a732 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -422,3 +422,73 @@ impl<'tcx> GenericPredicates<'tcx> { instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s)); } } + +/// `~const` bounds for a given item. This is represented using a struct much like +/// `GenericPredicates`, where you can either choose to only instantiate the "own" +/// bounds or all of the bounds including those from the parent. This distinction +/// is necessary for code like `compare_method_predicate_entailment`. +#[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)] +pub struct ConstConditions<'tcx> { + pub parent: Option, + pub predicates: &'tcx [(ty::PolyTraitRef<'tcx>, Span)], +} + +impl<'tcx> ConstConditions<'tcx> { + pub fn instantiate( + self, + tcx: TyCtxt<'tcx>, + args: GenericArgsRef<'tcx>, + ) -> Vec<(ty::PolyTraitRef<'tcx>, Span)> { + let mut instantiated = vec![]; + self.instantiate_into(tcx, &mut instantiated, args); + instantiated + } + + pub fn instantiate_own( + self, + tcx: TyCtxt<'tcx>, + args: GenericArgsRef<'tcx>, + ) -> impl Iterator, Span)> + DoubleEndedIterator + ExactSizeIterator + { + EarlyBinder::bind(self.predicates).iter_instantiated_copied(tcx, args) + } + + pub fn instantiate_own_identity( + self, + ) -> impl Iterator, Span)> + DoubleEndedIterator + ExactSizeIterator + { + EarlyBinder::bind(self.predicates).iter_identity_copied() + } + + #[instrument(level = "debug", skip(self, tcx))] + fn instantiate_into( + self, + tcx: TyCtxt<'tcx>, + instantiated: &mut Vec<(ty::PolyTraitRef<'tcx>, Span)>, + args: GenericArgsRef<'tcx>, + ) { + if let Some(def_id) = self.parent { + tcx.const_conditions(def_id).instantiate_into(tcx, instantiated, args); + } + instantiated.extend( + self.predicates.iter().map(|&(p, s)| (EarlyBinder::bind(p).instantiate(tcx, args), s)), + ); + } + + pub fn instantiate_identity(self, tcx: TyCtxt<'tcx>) -> Vec<(ty::PolyTraitRef<'tcx>, Span)> { + let mut instantiated = vec![]; + self.instantiate_identity_into(tcx, &mut instantiated); + instantiated + } + + fn instantiate_identity_into( + self, + tcx: TyCtxt<'tcx>, + instantiated: &mut Vec<(ty::PolyTraitRef<'tcx>, Span)>, + ) { + if let Some(def_id) = self.parent { + tcx.const_conditions(def_id).instantiate_identity_into(tcx, instantiated); + } + instantiated.extend(self.predicates.iter().copied()); + } +} diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index ed24fcc7eb88..84e1897019e7 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -84,12 +84,13 @@ pub use self::parameterized::ParameterizedOverTcx; pub use self::pattern::{Pattern, PatternKind}; pub use self::predicate::{ AliasTerm, Clause, ClauseKind, CoercePredicate, ExistentialPredicate, - ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef, NormalizesTo, - OutlivesPredicate, PolyCoercePredicate, PolyExistentialPredicate, PolyExistentialProjection, - PolyExistentialTraitRef, PolyProjectionPredicate, PolyRegionOutlivesPredicate, - PolySubtypePredicate, PolyTraitPredicate, PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, - PredicateKind, ProjectionPredicate, RegionOutlivesPredicate, SubtypePredicate, ToPolyTraitRef, - TraitPredicate, TraitRef, TypeOutlivesPredicate, + ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef, + HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate, + PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef, + PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate, + PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate, + RegionOutlivesPredicate, SubtypePredicate, ToPolyTraitRef, TraitPredicate, TraitRef, + TypeOutlivesPredicate, }; pub use self::region::BoundRegionKind::*; pub use self::region::{ diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index 7e1255f606c3..43bdce5b576d 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -132,6 +132,7 @@ parameterized_over_tcx! { ty::Ty, ty::FnSig, ty::GenericPredicates, + ty::ConstConditions, ty::TraitRef, ty::Const, ty::Predicate, diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index d20cb368278b..3ecaa3e22d39 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -19,6 +19,7 @@ pub type ExistentialPredicate<'tcx> = ir::ExistentialPredicate>; pub type ExistentialTraitRef<'tcx> = ir::ExistentialTraitRef>; pub type ExistentialProjection<'tcx> = ir::ExistentialProjection>; pub type TraitPredicate<'tcx> = ir::TraitPredicate>; +pub type HostEffectPredicate<'tcx> = ir::HostEffectPredicate>; pub type ClauseKind<'tcx> = ir::ClauseKind>; pub type PredicateKind<'tcx> = ir::PredicateKind>; pub type NormalizesTo<'tcx> = ir::NormalizesTo>; @@ -143,6 +144,7 @@ impl<'tcx> Predicate<'tcx> { | PredicateKind::AliasRelate(..) | PredicateKind::NormalizesTo(..) => false, PredicateKind::Clause(ClauseKind::Trait(_)) + | PredicateKind::Clause(ClauseKind::HostEffect(..)) | PredicateKind::Clause(ClauseKind::RegionOutlives(_)) | PredicateKind::Clause(ClauseKind::TypeOutlives(_)) | PredicateKind::Clause(ClauseKind::Projection(_)) @@ -644,6 +646,7 @@ impl<'tcx> Predicate<'tcx> { match predicate.skip_binder() { PredicateKind::Clause(ClauseKind::Trait(t)) => Some(predicate.rebind(t)), PredicateKind::Clause(ClauseKind::Projection(..)) + | PredicateKind::Clause(ClauseKind::HostEffect(..)) | PredicateKind::Clause(ClauseKind::ConstArgHasType(..)) | PredicateKind::NormalizesTo(..) | PredicateKind::AliasRelate(..) @@ -664,6 +667,7 @@ impl<'tcx> Predicate<'tcx> { match predicate.skip_binder() { PredicateKind::Clause(ClauseKind::Projection(t)) => Some(predicate.rebind(t)), PredicateKind::Clause(ClauseKind::Trait(..)) + | PredicateKind::Clause(ClauseKind::HostEffect(..)) | PredicateKind::Clause(ClauseKind::ConstArgHasType(..)) | PredicateKind::NormalizesTo(..) | PredicateKind::AliasRelate(..) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 10c3522eb0e9..0248aad53e24 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -3075,6 +3075,15 @@ define_print! { p!(print(self.trait_ref.print_trait_sugared())) } + ty::HostEffectPredicate<'tcx> { + let constness = match self.host { + ty::HostPolarity::Const => { "const" } + ty::HostPolarity::Maybe => { "~const" } + }; + p!(print(self.trait_ref.self_ty()), ": {constness} "); + p!(print(self.trait_ref.print_trait_sugared())) + } + ty::TypeAndMut<'tcx> { p!(write("{}", self.mutbl.prefix_str()), print(self.ty)) } @@ -3087,6 +3096,7 @@ define_print! { ty::ClauseKind::RegionOutlives(predicate) => p!(print(predicate)), ty::ClauseKind::TypeOutlives(predicate) => p!(print(predicate)), ty::ClauseKind::Projection(predicate) => p!(print(predicate)), + ty::ClauseKind::HostEffect(predicate) => p!(print(predicate)), ty::ClauseKind::ConstArgHasType(ct, ty) => { p!("the constant `", print(ct), "` has type `", print(ty), "`") }, diff --git a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs new file mode 100644 index 000000000000..62b4bb0004ca --- /dev/null +++ b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs @@ -0,0 +1,296 @@ +//! Dealing with host effect goals, i.e. enforcing the constness in +//! `T: const Trait` or `T: ~const Trait`. + +use rustc_type_ir::fast_reject::DeepRejectCtxt; +use rustc_type_ir::inherent::*; +use rustc_type_ir::{self as ty, Interner}; +use tracing::instrument; + +use super::assembly::Candidate; +use crate::delegate::SolverDelegate; +use crate::solve::assembly::{self}; +use crate::solve::{ + BuiltinImplSource, CandidateSource, Certainty, EvalCtxt, Goal, GoalSource, NoSolution, + QueryResult, +}; + +impl assembly::GoalKind for ty::HostEffectPredicate +where + D: SolverDelegate, + I: Interner, +{ + fn self_ty(self) -> I::Ty { + self.self_ty() + } + + fn trait_ref(self, _: I) -> ty::TraitRef { + self.trait_ref + } + + fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self { + self.with_self_ty(cx, self_ty) + } + + fn trait_def_id(self, _: I) -> I::DefId { + self.def_id() + } + + fn probe_and_match_goal_against_assumption( + ecx: &mut EvalCtxt<'_, D>, + source: rustc_type_ir::solve::CandidateSource, + goal: Goal, + assumption: ::Clause, + then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult, + ) -> Result, NoSolution> { + if let Some(host_clause) = assumption.as_host_effect_clause() { + if host_clause.def_id() == goal.predicate.def_id() + && host_clause.host().satisfies(goal.predicate.host) + { + if !DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify( + goal.predicate.trait_ref.args, + host_clause.skip_binder().trait_ref.args, + ) { + return Err(NoSolution); + } + + ecx.probe_trait_candidate(source).enter(|ecx| { + let assumption_trait_pred = ecx.instantiate_binder_with_infer(host_clause); + ecx.eq( + goal.param_env, + goal.predicate.trait_ref, + assumption_trait_pred.trait_ref, + )?; + then(ecx) + }) + } else { + Err(NoSolution) + } + } else { + Err(NoSolution) + } + } + + fn consider_impl_candidate( + ecx: &mut EvalCtxt<'_, D>, + goal: Goal, + impl_def_id: ::DefId, + ) -> Result, NoSolution> { + let cx = ecx.cx(); + + let impl_trait_ref = cx.impl_trait_ref(impl_def_id); + if !DeepRejectCtxt::relate_rigid_infer(ecx.cx()) + .args_may_unify(goal.predicate.trait_ref.args, impl_trait_ref.skip_binder().args) + { + return Err(NoSolution); + } + + let impl_polarity = cx.impl_polarity(impl_def_id); + match impl_polarity { + ty::ImplPolarity::Negative => return Err(NoSolution), + ty::ImplPolarity::Reservation => { + unimplemented!("reservation impl for const trait: {:?}", goal) + } + ty::ImplPolarity::Positive => {} + }; + + if !cx.is_const_impl(impl_def_id) { + return Err(NoSolution); + } + + ecx.probe_trait_candidate(CandidateSource::Impl(impl_def_id)).enter(|ecx| { + let impl_args = ecx.fresh_args_for_item(impl_def_id); + ecx.record_impl_args(impl_args); + let impl_trait_ref = impl_trait_ref.instantiate(cx, impl_args); + + ecx.eq(goal.param_env, goal.predicate.trait_ref, impl_trait_ref)?; + let where_clause_bounds = cx + .predicates_of(impl_def_id) + .iter_instantiated(cx, impl_args) + .map(|pred| goal.with(cx, pred)); + ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds); + + // For this impl to be `const`, we need to check its `~const` bounds too. + let const_conditions = cx + .const_conditions(impl_def_id) + .iter_instantiated(cx, impl_args) + .map(|bound_trait_ref| { + goal.with(cx, bound_trait_ref.to_host_effect_clause(cx, goal.predicate.host)) + }); + ecx.add_goals(GoalSource::ImplWhereBound, const_conditions); + + ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + }) + } + + fn consider_error_guaranteed_candidate( + ecx: &mut EvalCtxt<'_, D>, + _guar: ::ErrorGuaranteed, + ) -> Result, NoSolution> { + ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc) + .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)) + } + + fn consider_auto_trait_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("auto traits are never const") + } + + fn consider_trait_alias_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("trait aliases are never const") + } + + fn consider_builtin_sized_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("Sized is never const") + } + + fn consider_builtin_copy_clone_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + todo!("Copy/Clone is not yet const") + } + + fn consider_builtin_pointer_like_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("PointerLike is not const") + } + + fn consider_builtin_fn_ptr_trait_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + todo!("Fn* are not yet const") + } + + fn consider_builtin_fn_trait_candidates( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + _kind: rustc_type_ir::ClosureKind, + ) -> Result, NoSolution> { + todo!("Fn* are not yet const") + } + + fn consider_builtin_async_fn_trait_candidates( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + _kind: rustc_type_ir::ClosureKind, + ) -> Result, NoSolution> { + todo!("AsyncFn* are not yet const") + } + + fn consider_builtin_async_fn_kind_helper_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("AsyncFnKindHelper is not const") + } + + fn consider_builtin_tuple_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("Tuple trait is not const") + } + + fn consider_builtin_pointee_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("Pointee is not const") + } + + fn consider_builtin_future_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("Future is not const") + } + + fn consider_builtin_iterator_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + todo!("Iterator is not yet const") + } + + fn consider_builtin_fused_iterator_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("FusedIterator is not const") + } + + fn consider_builtin_async_iterator_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("AsyncIterator is not const") + } + + fn consider_builtin_coroutine_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("Coroutine is not const") + } + + fn consider_builtin_discriminant_kind_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("DiscriminantKind is not const") + } + + fn consider_builtin_async_destruct_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("AsyncDestruct is not const") + } + + fn consider_builtin_destruct_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("Destruct is not const") + } + + fn consider_builtin_transmute_candidate( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Result, NoSolution> { + unreachable!("TransmuteFrom is not const") + } + + fn consider_structural_builtin_unsize_candidates( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + ) -> Vec> { + unreachable!("Unsize is not const") + } +} + +impl EvalCtxt<'_, D> +where + D: SolverDelegate, + I: Interner, +{ + #[instrument(level = "trace", skip(self))] + pub(super) fn compute_host_effect_goal( + &mut self, + goal: Goal>, + ) -> QueryResult { + let candidates = self.assemble_and_evaluate_candidates(goal); + self.merge_candidates(candidates) + } +} diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 250174e033e3..7608253882a2 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -443,6 +443,9 @@ where ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => { self.compute_trait_goal(Goal { param_env, predicate }) } + ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => { + self.compute_host_effect_goal(Goal { param_env, predicate }) + } ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => { self.compute_projection_goal(Goal { param_env, predicate }) } diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index b7fdc339be5c..6793779b205d 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -13,6 +13,7 @@ mod alias_relate; mod assembly; +mod effect_goals; mod eval_ctxt; pub mod inspect; mod normalizes_to; diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 7827975d3caf..05954143aee0 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -137,6 +137,10 @@ where ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => { self.visit_trait(trait_ref) } + ty::ClauseKind::HostEffect(pred) => { + try_visit!(self.visit_trait(pred.trait_ref)); + pred.host.visit_with(self) + } ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_term: projection_ty, term, diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index 0abc89ddb81a..8f05f859c077 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -689,6 +689,9 @@ impl<'tcx> Stable<'tcx> for ty::ClauseKind<'tcx> { ClauseKind::ConstEvaluatable(const_) => { stable_mir::ty::ClauseKind::ConstEvaluatable(const_.stable(tables)) } + ClauseKind::HostEffect(..) => { + todo!() + } } } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index b0175fff8a7f..b7e2ed391cd4 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -156,8 +156,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { (leaf_trait_predicate, &obligation) }; - let (main_trait_predicate, leaf_trait_predicate, predicate_constness) = self.get_effects_trait_pred_override(main_trait_predicate, leaf_trait_predicate, span); - let main_trait_ref = main_trait_predicate.to_poly_trait_ref(); let leaf_trait_ref = leaf_trait_predicate.to_poly_trait_ref(); @@ -228,7 +226,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let err_msg = self.get_standard_error_message( main_trait_predicate, message, - predicate_constness, + None, append_const_msg, post_message, ); @@ -289,13 +287,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ); } - if tcx.is_lang_item(leaf_trait_ref.def_id(), LangItem::Drop) - && matches!(predicate_constness, Some(ty::BoundConstness::ConstIfConst | ty::BoundConstness::Const)) - { - err.note("`~const Drop` was renamed to `~const Destruct`"); - err.note("See for more details"); - } - let explanation = get_explanation_based_on_obligation( self.tcx, &obligation, @@ -541,6 +532,29 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err } + ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => { + // FIXME(effects): We should recompute the predicate with `~const` + // if it's `const`, and if it holds, explain that this bound only + // *conditionally* holds. If that fails, we should also do selection + // to drill this down to an impl or built-in source, so we can + // point at it and explain that while the trait *is* implemented, + // that implementation is not const. + let err_msg = self.get_standard_error_message( + bound_predicate.rebind(ty::TraitPredicate { + trait_ref: predicate.trait_ref, + polarity: ty::PredicatePolarity::Positive, + }), + None, + Some(match predicate.host { + ty::HostPolarity::Maybe => ty::BoundConstness::ConstIfConst, + ty::HostPolarity::Const => ty::BoundConstness::Const, + }), + None, + String::new(), + ); + struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg) + } + ty::PredicateKind::Subtype(predicate) => { // Errors for Subtype predicates show up as // `FulfillmentErrorCode::SubtypeError`, @@ -2374,16 +2388,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }) } - // FIXME(effects): Remove this. - fn get_effects_trait_pred_override( - &self, - p: ty::PolyTraitPredicate<'tcx>, - leaf: ty::PolyTraitPredicate<'tcx>, - _span: Span, - ) -> (ty::PolyTraitPredicate<'tcx>, ty::PolyTraitPredicate<'tcx>, ty::BoundConstness) { - (p, leaf, ty::BoundConstness::NotConst) - } - fn add_tuple_trait_message( &self, obligation_cause_code: &ObligationCauseCode<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 12aeee0d02fe..934fe9ec47c0 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -806,7 +806,8 @@ impl<'tcx> AutoTraitFinder<'tcx> { | ty::PredicateKind::Subtype(..) // FIXME(generic_const_exprs): you can absolutely add this as a where clauses | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) - | ty::PredicateKind::Coerce(..) => {} + | ty::PredicateKind::Coerce(..) + | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => {} ty::PredicateKind::Ambiguous => return false, }; } diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs index cc0450e0b057..a068f25fe35e 100644 --- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs +++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs @@ -245,6 +245,7 @@ fn predicate_references_self<'tcx>( | ty::ClauseKind::RegionOutlives(..) // FIXME(generic_const_exprs): this can mention `Self` | ty::ClauseKind::ConstEvaluatable(..) + | ty::ClauseKind::HostEffect(..) => None, } } @@ -284,7 +285,8 @@ fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool { | ty::ClauseKind::Projection(_) | ty::ClauseKind::ConstArgHasType(_, _) | ty::ClauseKind::WellFormed(_) - | ty::ClauseKind::ConstEvaluatable(_) => false, + | ty::ClauseKind::ConstEvaluatable(_) + | ty::ClauseKind::HostEffect(..) => false, }) } diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index ca9e6cd662d9..1754418156d9 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -372,7 +372,11 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { | ty::PredicateKind::Subtype(_) | ty::PredicateKind::Coerce(_) | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) - | ty::PredicateKind::ConstEquate(..) => { + | ty::PredicateKind::ConstEquate(..) + // FIXME(effects): We may need to do this using the higher-ranked + // pred instead of just instantiating it with placeholders b/c of + // higher-ranked implied bound issues in the old solver. + | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => { let pred = ty::Binder::dummy(infcx.enter_forall_and_leak_universe(binder)); let mut obligations = PredicateObligations::with_capacity(1); obligations.push(obligation.with(infcx.tcx, pred)); @@ -398,6 +402,10 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { ) } + ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => { + ProcessResult::Changed(Default::default()) + } + ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(data)) => { if infcx.considering_regions { infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs index dfd0cab69058..c6e41e57f0ce 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs @@ -96,6 +96,7 @@ pub fn compute_implied_outlives_bounds_inner<'tcx>( // FIXME(const_generics): Make sure that `<'a, 'b, const N: &'a &'b u32>` is sound // if we ever support that ty::PredicateKind::Clause(ty::ClauseKind::Trait(..)) + | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) | ty::PredicateKind::Subtype(..) | ty::PredicateKind::Coerce(..) @@ -200,6 +201,7 @@ pub fn compute_implied_outlives_bounds_compat_inner<'tcx>( // FIXME(const_generics): Make sure that `<'a, 'b, const N: &'a &'b u32>` is sound // if we ever support that ty::PredicateKind::Clause(ty::ClauseKind::Trait(..)) + | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) | ty::PredicateKind::Subtype(..) | ty::PredicateKind::Coerce(..) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 4d7e2769af5f..ec4114fd9d72 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -645,6 +645,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { self.evaluate_trait_predicate_recursively(previous_stack, obligation) } + ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => { + // FIXME(effects): It should be relatively straightforward to implement + // old trait solver support for `HostEffect` bounds; or at least basic + // support for them. + todo!() + } + ty::PredicateKind::Subtype(p) => { let p = bound_predicate.rebind(p); // Does this code ever run? diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 8904a9a68580..437343b569c4 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -170,6 +170,10 @@ pub fn clause_obligations<'tcx>( ty::ClauseKind::Trait(t) => { wf.compute_trait_pred(t, Elaborate::None); } + ty::ClauseKind::HostEffect(..) => { + // Technically the well-formedness of this predicate is implied by + // the corresponding trait predicate it should've been generated beside. + } ty::ClauseKind::RegionOutlives(..) => {} ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { wf.compute(ty.into()); @@ -1021,6 +1025,7 @@ pub(crate) fn required_region_bounds<'tcx>( } } ty::ClauseKind::Trait(_) + | ty::ClauseKind::HostEffect(..) | ty::ClauseKind::RegionOutlives(_) | ty::ClauseKind::Projection(_) | ty::ClauseKind::ConstArgHasType(_, _) diff --git a/compiler/rustc_traits/src/normalize_erasing_regions.rs b/compiler/rustc_traits/src/normalize_erasing_regions.rs index f01a12b0a00c..3e2794f6489f 100644 --- a/compiler/rustc_traits/src/normalize_erasing_regions.rs +++ b/compiler/rustc_traits/src/normalize_erasing_regions.rs @@ -55,6 +55,7 @@ fn not_outlives_predicate(p: ty::Predicate<'_>) -> bool { | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => false, ty::PredicateKind::Clause(ty::ClauseKind::Trait(..)) | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) + | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) | ty::PredicateKind::NormalizesTo(..) | ty::PredicateKind::AliasRelate(..) diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 28a81b1b0621..ac2708a29f4a 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -150,6 +150,15 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> { }); } + // We extend the param-env of our item with the const conditions of the item, + // since we're allowed to assume `~const` bounds hold within the item itself. + predicates.extend( + tcx.const_conditions(def_id) + .instantiate_identity(tcx) + .into_iter() + .map(|(trait_ref, _)| trait_ref.to_host_effect_clause(tcx, ty::HostPolarity::Maybe)), + ); + let local_did = def_id.as_local(); let unnormalized_env = diff --git a/compiler/rustc_type_ir/src/elaborate.rs b/compiler/rustc_type_ir/src/elaborate.rs index 56a72f943ab4..72d392ecd7bd 100644 --- a/compiler/rustc_type_ir/src/elaborate.rs +++ b/compiler/rustc_type_ir/src/elaborate.rs @@ -155,6 +155,16 @@ impl> Elaborator { ), }; } + // `T: ~const Trait` implies `T: ~const Supertrait`. + ty::ClauseKind::HostEffect(data) => self.extend_deduped( + cx.implied_const_bounds(data.def_id()).iter_identity().map(|trait_ref| { + elaboratable.child( + trait_ref + .to_host_effect_clause(cx, data.host) + .instantiate_supertrait(cx, bound_clause.rebind(data.trait_ref)), + ) + }), + ), ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_max, r_min)) => { // We know that `T: 'a` for some type `T`. We can // often elaborate this. For example, if we know that diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 02ec29a7f3d5..5af1aa2f8faa 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -468,6 +468,14 @@ pub trait Clause>: .transpose() } + fn as_host_effect_clause(self) -> Option>> { + self.kind() + .map_bound( + |clause| if let ty::ClauseKind::HostEffect(t) = clause { Some(t) } else { None }, + ) + .transpose() + } + fn as_projection_clause(self) -> Option>> { self.kind() .map_bound( diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 4184e9e313ff..6a8113b38b7b 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -24,6 +24,7 @@ pub trait Interner: + IrPrint> + IrPrint> + IrPrint> + + IrPrint> + IrPrint> + IrPrint> + IrPrint> @@ -228,6 +229,16 @@ pub trait Interner: def_id: Self::DefId, ) -> ty::EarlyBinder>; + fn is_const_impl(self, def_id: Self::DefId) -> bool; + fn const_conditions( + self, + def_id: Self::DefId, + ) -> ty::EarlyBinder>>>; + fn implied_const_bounds( + self, + def_id: Self::DefId, + ) -> ty::EarlyBinder>>>; + fn has_target_features(self, def_id: Self::DefId) -> bool; fn require_lang_item(self, lang_item: TraitSolverLangItem) -> Self::DefId; diff --git a/compiler/rustc_type_ir/src/ir_print.rs b/compiler/rustc_type_ir/src/ir_print.rs index d57d0816680b..0c71f3a3df2a 100644 --- a/compiler/rustc_type_ir/src/ir_print.rs +++ b/compiler/rustc_type_ir/src/ir_print.rs @@ -2,8 +2,8 @@ use std::fmt; use crate::{ AliasTerm, AliasTy, Binder, CoercePredicate, ExistentialProjection, ExistentialTraitRef, FnSig, - Interner, NormalizesTo, OutlivesPredicate, ProjectionPredicate, SubtypePredicate, - TraitPredicate, TraitRef, + HostEffectPredicate, Interner, NormalizesTo, OutlivesPredicate, ProjectionPredicate, + SubtypePredicate, TraitPredicate, TraitRef, }; pub trait IrPrint { @@ -53,6 +53,7 @@ define_display_via_print!( NormalizesTo, SubtypePredicate, CoercePredicate, + HostEffectPredicate, AliasTy, AliasTerm, FnSig, diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index e8ce39be3e50..c31645503487 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -111,6 +111,13 @@ impl ty::Binder> { pub fn def_id(&self) -> I::DefId { self.skip_binder().def_id } + + pub fn to_host_effect_clause(self, cx: I, host: HostPolarity) -> I::Clause { + self.map_bound(|trait_ref| { + ty::ClauseKind::HostEffect(HostEffectPredicate { trait_ref, host }) + }) + .upcast(cx) + } } #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] @@ -745,6 +752,64 @@ impl fmt::Debug for NormalizesTo { } } +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] +#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] +#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +pub struct HostEffectPredicate { + pub trait_ref: ty::TraitRef, + pub host: HostPolarity, +} + +impl HostEffectPredicate { + pub fn self_ty(self) -> I::Ty { + self.trait_ref.self_ty() + } + + pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> Self { + Self { trait_ref: self.trait_ref.with_self_ty(interner, self_ty), ..self } + } + + pub fn def_id(self) -> I::DefId { + self.trait_ref.def_id + } +} + +impl ty::Binder> { + pub fn def_id(self) -> I::DefId { + // Ok to skip binder since trait `DefId` does not care about regions. + self.skip_binder().def_id() + } + + pub fn self_ty(self) -> ty::Binder { + self.map_bound(|trait_ref| trait_ref.self_ty()) + } + + #[inline] + pub fn host(self) -> HostPolarity { + self.skip_binder().host + } +} + +#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] +#[derive(TypeVisitable_Generic, TypeFoldable_Generic)] +#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +pub enum HostPolarity { + /// May be called in const environments if the callee is const. + Maybe, + /// Always allowed to be called in const environments. + Const, +} + +impl HostPolarity { + pub fn satisfies(self, goal: HostPolarity) -> bool { + match (self, goal) { + (HostPolarity::Const, HostPolarity::Const | HostPolarity::Maybe) => true, + (HostPolarity::Maybe, HostPolarity::Maybe) => true, + (HostPolarity::Maybe, HostPolarity::Const) => false, + } + } +} + /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates /// whether the `a` type is the type that we should label as "expected" when /// presenting user diagnostics. diff --git a/compiler/rustc_type_ir/src/predicate_kind.rs b/compiler/rustc_type_ir/src/predicate_kind.rs index 46202dbb0f27..21f4456abd11 100644 --- a/compiler/rustc_type_ir/src/predicate_kind.rs +++ b/compiler/rustc_type_ir/src/predicate_kind.rs @@ -37,6 +37,12 @@ pub enum ClauseKind { /// Constant initializer must evaluate successfully. ConstEvaluatable(I::Const), + + /// Enforces the constness of the predicate we're calling. Like a projection + /// goal from a where clause, it's always going to be paired with a + /// corresponding trait clause; this just enforces the *constness* of that + /// implementation. + HostEffect(ty::HostEffectPredicate), } #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] @@ -110,6 +116,7 @@ impl fmt::Debug for ClauseKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ClauseKind::ConstArgHasType(ct, ty) => write!(f, "ConstArgHasType({ct:?}, {ty:?})"), + ClauseKind::HostEffect(data) => data.fmt(f), ClauseKind::Trait(a) => a.fmt(f), ClauseKind::RegionOutlives(pair) => pair.fmt(f), ClauseKind::TypeOutlives(pair) => pair.fmt(f), diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 861ca70cd83d..81264b49dfd0 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -368,7 +368,9 @@ pub(crate) fn clean_predicate<'tcx>( // FIXME(generic_const_exprs): should this do something? ty::ClauseKind::ConstEvaluatable(..) | ty::ClauseKind::WellFormed(..) - | ty::ClauseKind::ConstArgHasType(..) => None, + | ty::ClauseKind::ConstArgHasType(..) + // FIXME(effects): We can probably use this `HostEffect` pred to render `~const`. + | ty::ClauseKind::HostEffect(_) => None, } } diff --git a/tests/crashes/118320.rs b/tests/crashes/118320.rs deleted file mode 100644 index 093c58e1c05f..000000000000 --- a/tests/crashes/118320.rs +++ /dev/null @@ -1,14 +0,0 @@ -//@ known-bug: #118320 -//@ edition:2021 -#![feature(const_trait_impl, effects, const_closures)] - -#[const_trait] -trait Bar { - fn foo(&self); -} - -impl Bar for () {} - -const FOO: () = { - (const || (()).foo())(); -}; diff --git a/tests/crashes/119924-6.rs b/tests/crashes/119924-6.rs deleted file mode 100644 index f1cc9d291591..000000000000 --- a/tests/crashes/119924-6.rs +++ /dev/null @@ -1,15 +0,0 @@ -//@ known-bug: #119924 -//@ compile-flags: -Znext-solver -#![feature(const_trait_impl, effects)] - -struct S; -#[const_trait] -trait Trait {} - -const fn f>(U); // should've gotten rejected during AST validation - //~^ ICE no host param id for call in const yet no errors reported - 0 -}>>() {} - -pub fn main() {} diff --git a/tests/ui/const-generics/issues/issue-88119.stderr b/tests/ui/const-generics/issues/issue-88119.stderr index 98bb81968100..a0ca33e38ef8 100644 --- a/tests/ui/const-generics/issues/issue-88119.stderr +++ b/tests/ui/const-generics/issues/issue-88119.stderr @@ -11,30 +11,12 @@ error[E0284]: type annotations needed: cannot normalize `<&T as ConstName>::{con | LL | impl const ConstName for &T | ^^ cannot normalize `<&T as ConstName>::{constant#0}` - | -note: required for `&T` to implement `ConstName` - --> $DIR/issue-88119.rs:19:35 - | -LL | impl const ConstName for &T - | ^^^^^^^^^ ^^ -LL | where -LL | [(); name_len::()]:, - | --------------------- unsatisfied trait bound introduced here error[E0284]: type annotations needed: cannot normalize `<&mut T as ConstName>::{constant#0}` --> $DIR/issue-88119.rs:26:49 | LL | impl const ConstName for &mut T | ^^^^^^ cannot normalize `<&mut T as ConstName>::{constant#0}` - | -note: required for `&mut T` to implement `ConstName` - --> $DIR/issue-88119.rs:26:35 - | -LL | impl const ConstName for &mut T - | ^^^^^^^^^ ^^^^^^ -LL | where -LL | [(); name_len::()]:, - | --------------------- unsatisfied trait bound introduced here error: aborting due to 3 previous errors diff --git a/tests/ui/consts/const-block-const-bound.stderr b/tests/ui/consts/const-block-const-bound.stderr index 42a42ae3938b..8cb91d78f6ca 100644 --- a/tests/ui/consts/const-block-const-bound.stderr +++ b/tests/ui/consts/const-block-const-bound.stderr @@ -4,6 +4,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn f(x: T) {} | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-block-const-bound.rs:8:22 + | +LL | const fn f(x: T) {} + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/const-block-const-bound.rs:8:32 | @@ -12,6 +20,6 @@ LL | const fn f(x: T) {} | | | the destructor for this type cannot be evaluated in constant functions -error: aborting due to 2 previous errors +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0493`. diff --git a/tests/ui/consts/constifconst-call-in-const-position.stderr b/tests/ui/consts/constifconst-call-in-const-position.stderr index 7de10f0287b4..2195cab3f4d0 100644 --- a/tests/ui/consts/constifconst-call-in-const-position.stderr +++ b/tests/ui/consts/constifconst-call-in-const-position.stderr @@ -3,24 +3,12 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = note: the next trait solver must be enabled globally for the effects feature to work correctly = help: use `-Znext-solver` to enable -error[E0308]: mismatched types +error[E0080]: evaluation of `foo::<()>::{constant#0}` failed --> $DIR/constifconst-call-in-const-position.rs:17:38 | LL | const fn foo() -> [u8; T::a()] { - | ^^^^^^ expected `false`, found `host` - | - = note: expected constant `false` - found constant `host` + | ^^^^^^ calling non-const function `<() as Tr>::a` -error[E0308]: mismatched types - --> $DIR/constifconst-call-in-const-position.rs:18:9 - | -LL | [0; T::a()] - | ^^^^^^ expected `false`, found `host` - | - = note: expected constant `false` - found constant `host` +error: aborting due to 2 previous errors -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0308`. +For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/fn_trait_refs.stderr b/tests/ui/consts/fn_trait_refs.stderr index 218c90f89a9e..2b012432afd4 100644 --- a/tests/ui/consts/fn_trait_refs.stderr +++ b/tests/ui/consts/fn_trait_refs.stderr @@ -30,6 +30,22 @@ LL | T: ~const Fn<()> + ~const Destruct, | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:13:15 + | +LL | T: ~const Fn<()> + ~const Destruct, + | ^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:13:31 + | +LL | T: ~const Fn<()> + ~const Destruct, + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/fn_trait_refs.rs:20:15 | @@ -50,6 +66,22 @@ LL | T: ~const FnMut<()> + ~const Destruct, | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:20:15 + | +LL | T: ~const FnMut<()> + ~const Destruct, + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:20:34 + | +LL | T: ~const FnMut<()> + ~const Destruct, + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/fn_trait_refs.rs:27:15 | @@ -64,6 +96,14 @@ LL | T: ~const FnOnce<()>, | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:27:15 + | +LL | T: ~const FnOnce<()>, + | ^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/fn_trait_refs.rs:34:15 | @@ -84,6 +124,22 @@ LL | T: ~const Fn<()> + ~const Destruct, | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:34:15 + | +LL | T: ~const Fn<()> + ~const Destruct, + | ^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:34:31 + | +LL | T: ~const Fn<()> + ~const Destruct, + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/fn_trait_refs.rs:48:15 | @@ -104,6 +160,22 @@ LL | T: ~const FnMut<()> + ~const Destruct, | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:48:15 + | +LL | T: ~const FnMut<()> + ~const Destruct, + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/fn_trait_refs.rs:48:34 + | +LL | T: ~const FnMut<()> + ~const Destruct, + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0015]: cannot call non-const operator in constants --> $DIR/fn_trait_refs.rs:70:17 | @@ -212,7 +284,7 @@ LL | const fn test_fn_mut(mut f: T) -> (T::Output, T::Output) LL | } | - value is dropped here -error: aborting due to 25 previous errors +error: aborting due to 34 previous errors Some errors have detailed explanations: E0015, E0493, E0635. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/unstable-const-fn-in-libcore.stderr b/tests/ui/consts/unstable-const-fn-in-libcore.stderr index 6c83eff4de01..59476f986032 100644 --- a/tests/ui/consts/unstable-const-fn-in-libcore.stderr +++ b/tests/ui/consts/unstable-const-fn-in-libcore.stderr @@ -4,6 +4,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn unwrap_or_else T>(self, f: F) -> T { | ^^^^^^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/unstable-const-fn-in-libcore.rs:19:39 + | +LL | const fn unwrap_or_else T>(self, f: F) -> T { + | ^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0015]: cannot call non-const closure in constant functions --> $DIR/unstable-const-fn-in-libcore.rs:24:26 | @@ -38,7 +46,7 @@ LL | const fn unwrap_or_else T>(self, f: F) -> T { LL | } | - value is dropped here -error: aborting due to 4 previous errors +error: aborting due to 5 previous errors Some errors have detailed explanations: E0015, E0493. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/delegation/ice-issue-124347.rs b/tests/ui/delegation/ice-issue-124347.rs index ee2bf9e33eb8..b2b3c61a722b 100644 --- a/tests/ui/delegation/ice-issue-124347.rs +++ b/tests/ui/delegation/ice-issue-124347.rs @@ -4,7 +4,7 @@ // FIXME(fn_delegation): `recursive delegation` error should be emitted here trait Trait { reuse Trait::foo { &self.0 } - //~^ ERROR cycle detected when computing generics of `Trait::foo` + //~^ ERROR recursive delegation is not supported yet } reuse foo; diff --git a/tests/ui/delegation/ice-issue-124347.stderr b/tests/ui/delegation/ice-issue-124347.stderr index bd0bc970b94c..74c4b5cd949a 100644 --- a/tests/ui/delegation/ice-issue-124347.stderr +++ b/tests/ui/delegation/ice-issue-124347.stderr @@ -1,16 +1,8 @@ -error[E0391]: cycle detected when computing generics of `Trait::foo` +error: recursive delegation is not supported yet --> $DIR/ice-issue-124347.rs:6:18 | LL | reuse Trait::foo { &self.0 } - | ^^^ - | - = note: ...which immediately requires computing generics of `Trait::foo` again -note: cycle used when inheriting delegation signature - --> $DIR/ice-issue-124347.rs:6:18 - | -LL | reuse Trait::foo { &self.0 } - | ^^^ - = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information + | ^^^ callee defined here error[E0391]: cycle detected when computing generics of `foo` --> $DIR/ice-issue-124347.rs:10:7 diff --git a/tests/ui/delegation/unsupported.rs b/tests/ui/delegation/unsupported.rs index e57effff48d8..56296db85a3f 100644 --- a/tests/ui/delegation/unsupported.rs +++ b/tests/ui/delegation/unsupported.rs @@ -51,7 +51,7 @@ mod effects { } reuse Trait::foo; - //~^ ERROR delegation to a function with effect parameter is not supported yet + //~^ ERROR type annotations needed } fn main() {} diff --git a/tests/ui/delegation/unsupported.stderr b/tests/ui/delegation/unsupported.stderr index 6a627be3b64e..1c79a603503f 100644 --- a/tests/ui/delegation/unsupported.stderr +++ b/tests/ui/delegation/unsupported.stderr @@ -81,15 +81,15 @@ LL | pub reuse to_reuse2::foo; LL | reuse to_reuse1::foo; | ^^^ -error: delegation to a function with effect parameter is not supported yet +error[E0283]: type annotations needed --> $DIR/unsupported.rs:53:18 | -LL | fn foo(); - | --------- callee defined here -... LL | reuse Trait::foo; - | ^^^ + | ^^^ cannot infer type + | + = note: cannot satisfy `_: effects::Trait` error: aborting due to 5 previous errors; 2 warnings emitted -For more information about this error, try `rustc --explain E0391`. +Some errors have detailed explanations: E0283, E0391. +For more information about an error, try `rustc --explain E0283`. diff --git a/tests/ui/impl-trait/normalize-tait-in-const.stderr b/tests/ui/impl-trait/normalize-tait-in-const.stderr index e0d193b5d402..f1e6207ed817 100644 --- a/tests/ui/impl-trait/normalize-tait-in-const.stderr +++ b/tests/ui/impl-trait/normalize-tait-in-const.stderr @@ -10,6 +10,22 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/normalize-tait-in-const.rs:26:42 + | +LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { + | ^^^^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/normalize-tait-in-const.rs:26:69 + | +LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0015]: cannot call non-const closure in constant functions --> $DIR/normalize-tait-in-const.rs:27:5 | @@ -35,7 +51,7 @@ LL | fun(filter_positive()); LL | } | - value is dropped here -error: aborting due to 4 previous errors +error: aborting due to 6 previous errors Some errors have detailed explanations: E0015, E0493. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/specialization/const_trait_impl.stderr b/tests/ui/specialization/const_trait_impl.stderr index 643f1de3e8d7..746b08fa7105 100644 --- a/tests/ui/specialization/const_trait_impl.stderr +++ b/tests/ui/specialization/const_trait_impl.stderr @@ -1,23 +1,3 @@ -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const_trait_impl.rs:6:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub unsafe trait Sup { -LL | fn foo() -> u32; - | - expected 0 const parameters - -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const_trait_impl.rs:6:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub unsafe trait Sup { -LL | fn foo() -> u32; - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/const_trait_impl.rs:34:16 | @@ -36,34 +16,27 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | impl const A for T { | ^^^^^^^ -error[E0049]: associated function `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const_trait_impl.rs:29:1 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const_trait_impl.rs:40:16 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait A { -LL | fn a() -> u32; - | - expected 0 const parameters - -error[E0049]: associated function `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const_trait_impl.rs:29:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait A { -LL | fn a() -> u32; - | - expected 0 const parameters +LL | impl const A for T { + | ^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error[E0049]: associated function `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const_trait_impl.rs:29:1 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const_trait_impl.rs:34:16 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait A { -LL | fn a() -> u32; - | - expected 0 const parameters +LL | impl const A for T { + | ^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const_trait_impl.rs:46:16 + | +LL | impl const A for T { + | ^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -115,7 +88,6 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 12 previous errors +error: aborting due to 10 previous errors -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr index 8288c660ce7c..20448f51de22 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr @@ -3,44 +3,5 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = note: the next trait solver must be enabled globally for the effects feature to work correctly = help: use `-Znext-solver` to enable -error[E0277]: the trait bound `::Assoc: Trait` is not satisfied - --> $DIR/assoc-type-const-bound-usage-0.rs:13:5 - | -LL | T::Assoc::func() - | ^^^^^^^^ the trait `Trait` is not implemented for `::Assoc` - | -note: required by a bound in `Trait::func` - --> $DIR/assoc-type-const-bound-usage-0.rs:6:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Trait::func` -... -LL | fn func() -> i32; - | ---- required by a bound in this associated function -help: consider further restricting the associated type - | -LL | const fn unqualified() -> i32 where ::Assoc: Trait { - | ++++++++++++++++++++++++++++++++ +error: aborting due to 1 previous error -error[E0277]: the trait bound `::Assoc: Trait` is not satisfied - --> $DIR/assoc-type-const-bound-usage-0.rs:17:5 - | -LL | ::Assoc::func() - | ^^^^^^^^^^^^^^^^^^^ the trait `Trait` is not implemented for `::Assoc` - | -note: required by a bound in `Trait::func` - --> $DIR/assoc-type-const-bound-usage-0.rs:6:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Trait::func` -... -LL | fn func() -> i32; - | ---- required by a bound in this associated function -help: consider further restricting the associated type - | -LL | const fn qualified() -> i32 where ::Assoc: Trait { - | ++++++++++++++++++++++++++++++++ - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr index 0792d090321d..20448f51de22 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr @@ -3,44 +3,5 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = note: the next trait solver must be enabled globally for the effects feature to work correctly = help: use `-Znext-solver` to enable -error[E0277]: the trait bound `::Assoc: Trait` is not satisfied - --> $DIR/assoc-type-const-bound-usage-1.rs:15:44 - | -LL | fn unqualified() -> Type<{ T::Assoc::func() }> { - | ^^^^^^^^ the trait `Trait` is not implemented for `::Assoc` - | -note: required by a bound in `Trait::func` - --> $DIR/assoc-type-const-bound-usage-1.rs:7:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Trait::func` -... -LL | fn func() -> i32; - | ---- required by a bound in this associated function -help: consider further restricting the associated type - | -LL | fn unqualified() -> Type<{ T::Assoc::func() }> where ::Assoc: Trait { - | ++++++++++++++++++++++++++++++++ +error: aborting due to 1 previous error -error[E0277]: the trait bound `::Assoc: Trait` is not satisfied - --> $DIR/assoc-type-const-bound-usage-1.rs:19:42 - | -LL | fn qualified() -> Type<{ ::Assoc::func() }> { - | ^^^^^^^^^^^^^^^^^^^ the trait `Trait` is not implemented for `::Assoc` - | -note: required by a bound in `Trait::func` - --> $DIR/assoc-type-const-bound-usage-1.rs:7:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Trait::func` -... -LL | fn func() -> i32; - | ---- required by a bound in this associated function -help: consider further restricting the associated type - | -LL | fn qualified() -> Type<{ ::Assoc::func() }> where ::Assoc: Trait { - | ++++++++++++++++++++++++++++++++ - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/call-const-trait-method-fail.stderr b/tests/ui/traits/const-traits/call-const-trait-method-fail.stderr index 5d2333d94fe8..40a06af85edc 100644 --- a/tests/ui/traits/const-traits/call-const-trait-method-fail.stderr +++ b/tests/ui/traits/const-traits/call-const-trait-method-fail.stderr @@ -2,20 +2,7 @@ error[E0277]: the trait bound `u32: ~const Plus` is not satisfied --> $DIR/call-const-trait-method-fail.rs:27:5 | LL | a.plus(b) - | ^ the trait `Plus` is not implemented for `u32` - | -note: required by a bound in `Plus::plus` - --> $DIR/call-const-trait-method-fail.rs:5:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Plus::plus` -LL | pub trait Plus { -LL | fn plus(self, rhs: Self) -> Self; - | ---- required by a bound in this associated function -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | pub const fn add_u32(a: u32, b: u32) -> u32 where u32: Plus { - | +++++++++++++++ + | ^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr b/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr index bf455a714a34..c1cead542163 100644 --- a/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr +++ b/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr @@ -16,15 +16,6 @@ LL | impl const PartialEq for Int { = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error[E0049]: method `plus` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/call-const-trait-method-pass.rs:24:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait Plus { -LL | fn plus(self, rhs: Self) -> Self; - | - expected 0 const parameters - error[E0015]: cannot call non-const operator in constants --> $DIR/call-const-trait-method-pass.rs:39:22 | @@ -73,7 +64,6 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 7 previous errors +error: aborting due to 6 previous errors -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/call-generic-in-impl.stderr b/tests/ui/traits/const-traits/call-generic-in-impl.stderr index 5cd274c6c5a2..368c22675e7f 100644 --- a/tests/ui/traits/const-traits/call-generic-in-impl.stderr +++ b/tests/ui/traits/const-traits/call-generic-in-impl.stderr @@ -4,14 +4,13 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | impl const MyPartialEq for T { | ^^^^^^^^^ -error[E0049]: method `eq` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/call-generic-in-impl.rs:5:1 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-in-impl.rs:10:16 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait MyPartialEq { -LL | fn eq(&self, other: &Self) -> bool; - | - expected 0 const parameters +LL | impl const MyPartialEq for T { + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0015]: cannot call non-const fn `::eq` in constant functions --> $DIR/call-generic-in-impl.rs:12:9 @@ -27,5 +26,4 @@ LL + #![feature(effects)] error: aborting due to 3 previous errors -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/call-generic-method-chain.stderr b/tests/ui/traits/const-traits/call-generic-method-chain.stderr index 57d57dfd5b93..dce9f0853904 100644 --- a/tests/ui/traits/const-traits/call-generic-method-chain.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-chain.stderr @@ -27,11 +27,27 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-chain.rs:19:32 + | +LL | const fn equals_self(t: &T) -> bool { + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/call-generic-method-chain.rs:23:40 | LL | const fn equals_self_wrapper(t: &T) -> bool { | ^^^^^^^^^ -error: aborting due to 4 previous errors; 1 warning emitted +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-chain.rs:23:40 + | +LL | const fn equals_self_wrapper(t: &T) -> bool { + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 6 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr index 0088ed2eb13d..5da511a580e2 100644 --- a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr @@ -27,11 +27,27 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-dup-bound.rs:19:44 + | +LL | const fn equals_self(t: &T) -> bool { + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/call-generic-method-dup-bound.rs:26:37 | LL | const fn equals_self2(t: &T) -> bool { | ^^^^^^^^^ -error: aborting due to 4 previous errors; 1 warning emitted +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-dup-bound.rs:26:37 + | +LL | const fn equals_self2(t: &T) -> bool { + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 6 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/call-generic-method-nonconst.stderr b/tests/ui/traits/const-traits/call-generic-method-nonconst.stderr index 68c9fc400104..06b99375cdaa 100644 --- a/tests/ui/traits/const-traits/call-generic-method-nonconst.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-nonconst.stderr @@ -1,20 +1,8 @@ error[E0277]: the trait bound `S: const Foo` is not satisfied - --> $DIR/call-generic-method-nonconst.rs:25:34 + --> $DIR/call-generic-method-nonconst.rs:25:22 | LL | pub const EQ: bool = equals_self(&S); - | ----------- ^^ the trait `Foo` is not implemented for `S` - | | - | required by a bound introduced by this call - | -note: required by a bound in `equals_self` - --> $DIR/call-generic-method-nonconst.rs:18:25 - | -LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^^ required by this bound in `equals_self` -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | pub const EQ: bool where S: Foo = equals_self(&S); - | ++++++++++++ + | ^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/call-generic-method-pass.stderr b/tests/ui/traits/const-traits/call-generic-method-pass.stderr index 4a6100c3c1aa..52579813b691 100644 --- a/tests/ui/traits/const-traits/call-generic-method-pass.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-pass.stderr @@ -27,5 +27,13 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ -error: aborting due to 3 previous errors; 1 warning emitted +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-pass.rs:19:32 + | +LL | const fn equals_self(t: &T) -> bool { + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/const-bounds-non-const-trait.rs b/tests/ui/traits/const-traits/const-bounds-non-const-trait.rs index db446f8bc2ea..d51d231b8a97 100644 --- a/tests/ui/traits/const-traits/const-bounds-non-const-trait.rs +++ b/tests/ui/traits/const-traits/const-bounds-non-const-trait.rs @@ -5,6 +5,7 @@ trait NonConst {} const fn perform() {} //~^ ERROR `~const` can only be applied to `#[const_trait]` traits +//~| ERROR `~const` can only be applied to `#[const_trait]` traits fn operate() {} //~^ ERROR `const` can only be applied to `#[const_trait]` traits diff --git a/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr b/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr index e1a85fc54144..6c3c11c6a475 100644 --- a/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr +++ b/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr @@ -18,11 +18,19 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn perform() {} | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-bounds-non-const-trait.rs:6:28 + | +LL | const fn perform() {} + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `const` can only be applied to `#[const_trait]` traits - --> $DIR/const-bounds-non-const-trait.rs:9:21 + --> $DIR/const-bounds-non-const-trait.rs:10:21 | LL | fn operate() {} | ^^^^^^^^ -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr index 507ceaae2eab..4e6707bba51c 100644 --- a/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr +++ b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr @@ -1,17 +1,16 @@ -error[E0049]: method `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-closure-trait-method-fail.rs:5:1 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-closure-trait-method-fail.rs:14:39 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Tr { -LL | fn a(self) -> i32; - | - expected 0 const parameters +LL | const fn need_const_closure i32>(x: T) -> i32 { + | ^^^^^^^^^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/const-closure-trait-method-fail.rs:14:39 | LL | const fn need_const_closure i32>(x: T) -> i32 { | ^^^^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0015]: cannot call non-const closure in constant functions --> $DIR/const-closure-trait-method-fail.rs:15:5 @@ -31,5 +30,4 @@ LL + #![feature(effects)] error: aborting due to 3 previous errors -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-closure-trait-method.stderr b/tests/ui/traits/const-traits/const-closure-trait-method.stderr index 2a54cd5d7f6e..0f0cd73cc102 100644 --- a/tests/ui/traits/const-traits/const-closure-trait-method.stderr +++ b/tests/ui/traits/const-traits/const-closure-trait-method.stderr @@ -1,17 +1,16 @@ -error[E0049]: method `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-closure-trait-method.rs:5:1 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-closure-trait-method.rs:14:39 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Tr { -LL | fn a(self) -> i32; - | - expected 0 const parameters +LL | const fn need_const_closure i32>(x: T) -> i32 { + | ^^^^^^^^^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/const-closure-trait-method.rs:14:39 | LL | const fn need_const_closure i32>(x: T) -> i32 { | ^^^^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0015]: cannot call non-const closure in constant functions --> $DIR/const-closure-trait-method.rs:15:5 @@ -31,5 +30,4 @@ LL + #![feature(effects)] error: aborting due to 3 previous errors -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-closures.stderr b/tests/ui/traits/const-traits/const-closures.stderr index a0f053253892..4d354cb281fe 100644 --- a/tests/ui/traits/const-traits/const-closures.stderr +++ b/tests/ui/traits/const-traits/const-closures.stderr @@ -16,12 +16,44 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | F: ~const Fn() -> u8, | ^^^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-closures.rs:8:19 + | +LL | F: ~const FnOnce() -> u8, + | ^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-closures.rs:9:19 + | +LL | F: ~const FnMut() -> u8, + | ^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-closures.rs:10:19 + | +LL | F: ~const Fn() -> u8, + | ^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/const-closures.rs:23:27 | LL | const fn answer u8>(f: &F) -> u8 { | ^^^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-closures.rs:23:27 + | +LL | const fn answer u8>(f: &F) -> u8 { + | ^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0015]: cannot call non-const closure in constant functions --> $DIR/const-closures.rs:24:5 | @@ -70,6 +102,6 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 7 previous errors +error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-default-method-bodies.stderr b/tests/ui/traits/const-traits/const-default-method-bodies.stderr index 0809d9c1e1d3..071eaf495418 100644 --- a/tests/ui/traits/const-traits/const-default-method-bodies.stderr +++ b/tests/ui/traits/const-traits/const-default-method-bodies.stderr @@ -1,21 +1,8 @@ error[E0277]: the trait bound `NonConstImpl: ~const ConstDefaultFn` is not satisfied - --> $DIR/const-default-method-bodies.rs:26:18 + --> $DIR/const-default-method-bodies.rs:26:5 | LL | NonConstImpl.a(); - | ^ the trait `ConstDefaultFn` is not implemented for `NonConstImpl` - | -note: required by a bound in `ConstDefaultFn::a` - --> $DIR/const-default-method-bodies.rs:5:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `ConstDefaultFn::a` -... -LL | fn a(self) { - | - required by a bound in this associated function -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | const fn test() where NonConstImpl: ConstDefaultFn { - | ++++++++++++++++++++++++++++++++++ + | ^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/const-drop-bound.stderr b/tests/ui/traits/const-traits/const-drop-bound.stderr index be197006f021..d94b0542324f 100644 --- a/tests/ui/traits/const-traits/const-drop-bound.stderr +++ b/tests/ui/traits/const-traits/const-drop-bound.stderr @@ -4,6 +4,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn foo(res: Result) -> Option where E: ~const Destruct { | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-bound.rs:9:68 + | +LL | const fn foo(res: Result) -> Option where E: ~const Destruct { + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: `~const` can only be applied to `#[const_trait]` traits --> $DIR/const-drop-bound.rs:20:15 | @@ -16,12 +24,28 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | E: ~const Destruct, | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-bound.rs:20:15 + | +LL | T: ~const Destruct, + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-bound.rs:21:15 + | +LL | E: ~const Destruct, + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0493]: destructor of `E` cannot be evaluated at compile-time --> $DIR/const-drop-bound.rs:12:13 | LL | Err(_e) => None, | ^^ the destructor for this type cannot be evaluated in constant functions -error: aborting due to 4 previous errors +error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0493`. diff --git a/tests/ui/traits/const-traits/const-drop-fail-2.stderr b/tests/ui/traits/const-traits/const-drop-fail-2.stderr index faf24c6d9114..27e8053c9690 100644 --- a/tests/ui/traits/const-traits/const-drop-fail-2.stderr +++ b/tests/ui/traits/const-traits/const-drop-fail-2.stderr @@ -13,6 +13,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn check(_: T) {} | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-fail-2.rs:20:26 + | +LL | const fn check(_: T) {} + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/const-drop-fail-2.rs:20:36 | @@ -33,7 +41,7 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 4 previous errors +error: aborting due to 5 previous errors Some errors have detailed explanations: E0015, E0493. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-drop-fail.precise.stderr b/tests/ui/traits/const-traits/const-drop-fail.precise.stderr index 3d400bf01587..bde13b4d6cfa 100644 --- a/tests/ui/traits/const-traits/const-drop-fail.precise.stderr +++ b/tests/ui/traits/const-traits/const-drop-fail.precise.stderr @@ -13,6 +13,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn check(_: T) {} | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-fail.rs:23:26 + | +LL | const fn check(_: T) {} + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/const-drop-fail.rs:23:36 | @@ -71,7 +79,7 @@ LL | | } | |_- in this macro invocation = note: this error originates in the macro `check_all` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 5 previous errors +error: aborting due to 6 previous errors Some errors have detailed explanations: E0080, E0493. For more information about an error, try `rustc --explain E0080`. diff --git a/tests/ui/traits/const-traits/const-drop-fail.stock.stderr b/tests/ui/traits/const-traits/const-drop-fail.stock.stderr index fd0f6d02684a..064ffacca427 100644 --- a/tests/ui/traits/const-traits/const-drop-fail.stock.stderr +++ b/tests/ui/traits/const-traits/const-drop-fail.stock.stderr @@ -13,6 +13,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn check(_: T) {} | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-fail.rs:23:26 + | +LL | const fn check(_: T) {} + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/const-drop-fail.rs:23:36 | @@ -21,6 +29,6 @@ LL | const fn check(_: T) {} | | | the destructor for this type cannot be evaluated in constant functions -error: aborting due to 3 previous errors +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0493`. diff --git a/tests/ui/traits/const-traits/const-drop.precise.stderr b/tests/ui/traits/const-traits/const-drop.precise.stderr index dd3ea5d241d7..7b6d185c7cc8 100644 --- a/tests/ui/traits/const-traits/const-drop.precise.stderr +++ b/tests/ui/traits/const-traits/const-drop.precise.stderr @@ -40,23 +40,11 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn a(_: T) {} | ^^^^^^^^ -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-drop.rs:53:5 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop.rs:18:22 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait SomeTrait { -LL | fn foo(); - | - expected 0 const parameters - -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-drop.rs:53:5 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait SomeTrait { -LL | fn foo(); - | - expected 0 const parameters +LL | const fn a(_: T) {} + | ^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -78,7 +66,7 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 9 previous errors +error: aborting due to 8 previous errors -Some errors have detailed explanations: E0015, E0049, E0493. +Some errors have detailed explanations: E0015, E0493. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-drop.stock.stderr b/tests/ui/traits/const-traits/const-drop.stock.stderr index aa59e1c8dc49..b497c39b08aa 100644 --- a/tests/ui/traits/const-traits/const-drop.stock.stderr +++ b/tests/ui/traits/const-traits/const-drop.stock.stderr @@ -40,23 +40,11 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn a(_: T) {} | ^^^^^^^^ -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-drop.rs:53:5 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/const-drop.rs:18:22 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait SomeTrait { -LL | fn foo(); - | - expected 0 const parameters - -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-drop.rs:53:5 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait SomeTrait { -LL | fn foo(); - | - expected 0 const parameters +LL | const fn a(_: T) {} + | ^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -80,7 +68,7 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 9 previous errors +error: aborting due to 8 previous errors -Some errors have detailed explanations: E0015, E0049, E0493. +Some errors have detailed explanations: E0015, E0493. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-fns-are-early-bound.rs b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs index 59a61e4f954d..6d08d8bdd919 100644 --- a/tests/ui/traits/const-traits/const-fns-are-early-bound.rs +++ b/tests/ui/traits/const-traits/const-fns-are-early-bound.rs @@ -1,4 +1,6 @@ //@ known-bug: #110395 +//@ failure-status: 101 +//@ dont-check-compiler-stderr // FIXME(effects) check-pass //@ compile-flags: -Znext-solver diff --git a/tests/ui/traits/const-traits/const-fns-are-early-bound.stderr b/tests/ui/traits/const-traits/const-fns-are-early-bound.stderr deleted file mode 100644 index 9eda9d98ec55..000000000000 --- a/tests/ui/traits/const-traits/const-fns-are-early-bound.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error[E0277]: the trait bound `fn() {foo}: const FnOnce()` is not satisfied - --> $DIR/const-fns-are-early-bound.rs:31:17 - | -LL | is_const_fn(foo); - | ----------- ^^^ the trait `FnOnce()` is not implemented for fn item `fn() {foo}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `is_const_fn` - --> $DIR/const-fns-are-early-bound.rs:25:12 - | -LL | fn is_const_fn(_: F) - | ----------- required by a bound in this function -LL | where -LL | F: const FnOnce<()>, - | ^^^^^^^^^^^^^^^^ required by this bound in `is_const_fn` - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/const-impl-trait.stderr b/tests/ui/traits/const-traits/const-impl-trait.stderr deleted file mode 100644 index 1040af7541c0..000000000000 --- a/tests/ui/traits/const-traits/const-impl-trait.stderr +++ /dev/null @@ -1,249 +0,0 @@ -error[E0635]: unknown feature `const_cmp` - --> $DIR/const-impl-trait.rs:8:5 - | -LL | const_cmp, - | ^^^^^^^^^ - -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:13:30 - | -LL | const fn cmp(a: &impl ~const PartialEq) -> bool { - | ^^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:17:30 - | -LL | const fn wrap(x: impl ~const PartialEq + ~const Destruct) - | ^^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:17:49 - | -LL | const fn wrap(x: impl ~const PartialEq + ~const Destruct) - | ^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:18:20 - | -LL | -> impl ~const PartialEq + ~const Destruct - | ^^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:18:39 - | -LL | -> impl ~const PartialEq + ~const Destruct - | ^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:18:20 - | -LL | -> impl ~const PartialEq + ~const Destruct - | ^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:18:39 - | -LL | -> impl ~const PartialEq + ~const Destruct - | ^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:29 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:48 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:29:29 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy { - | ^^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:29:48 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy { - | ^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:29:29 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy { - | ^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:29:48 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy { - | ^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:50:41 - | -LL | const fn apit(_: impl ~const T + ~const Destruct) {} - | ^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:54:73 - | -LL | const fn apit_assoc_bound(_: impl IntoIterator + ~const Destruct) {} - | ^^^^^^^^ - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:29 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:48 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:29 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:48 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:29 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-impl-trait.rs:25:48 - | -LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; - | ^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:37:26 - | -LL | assert!(wrap(123) == wrap(123)); - | ^^^^^^^^^- value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:37:26 - | -LL | assert!(wrap(123) == wrap(123)); - | ^^^^^^^^^- value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:37:13 - | -LL | assert!(wrap(123) == wrap(123)); - | ^^^^^^^^^ - value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:37:13 - | -LL | assert!(wrap(123) == wrap(123)); - | ^^^^^^^^^ - value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:38:26 - | -LL | assert!(wrap(123) != wrap(456)); - | ^^^^^^^^^- value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:38:26 - | -LL | assert!(wrap(123) != wrap(456)); - | ^^^^^^^^^- value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:38:13 - | -LL | assert!(wrap(123) != wrap(456)); - | ^^^^^^^^^ - value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - -error[E0493]: destructor of `impl PartialEq + Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:38:13 - | -LL | assert!(wrap(123) != wrap(456)); - | ^^^^^^^^^ - value is dropped here - | | - | the destructor for this type cannot be evaluated in constants - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0493]: destructor of `impl ~const T + ~const Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:50:15 - | -LL | const fn apit(_: impl ~const T + ~const Destruct) {} - | ^ - value is dropped here - | | - | the destructor for this type cannot be evaluated in constant functions - -error[E0493]: destructor of `impl IntoIterator + ~const Destruct` cannot be evaluated at compile-time - --> $DIR/const-impl-trait.rs:54:27 - | -LL | const fn apit_assoc_bound(_: impl IntoIterator + ~const Destruct) {} - | ^ - value is dropped here - | | - | the destructor for this type cannot be evaluated in constant functions - -error: aborting due to 33 previous errors - -Some errors have detailed explanations: E0493, E0635. -For more information about an error, try `rustc --explain E0493`. diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr index addce8dcd6c7..3388ee30a5d3 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr @@ -30,5 +30,14 @@ LL | #[derive_const(PartialEq)] | = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 3 previous errors; 1 warning emitted +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/derive-const-with-params.rs:7:16 + | +LL | #[derive_const(PartialEq)] + | ^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/cross-crate.gatednc.stderr b/tests/ui/traits/const-traits/cross-crate.gatednc.stderr index a34bae843c81..b6f2434140d6 100644 --- a/tests/ui/traits/const-traits/cross-crate.gatednc.stderr +++ b/tests/ui/traits/const-traits/cross-crate.gatednc.stderr @@ -1,21 +1,8 @@ error[E0277]: the trait bound `cross_crate::NonConst: ~const cross_crate::MyTrait` is not satisfied - --> $DIR/cross-crate.rs:19:14 + --> $DIR/cross-crate.rs:19:5 | LL | NonConst.func(); - | ^^^^ the trait `cross_crate::MyTrait` is not implemented for `cross_crate::NonConst` - | -note: required by a bound in `func` - --> $DIR/auxiliary/cross-crate.rs:5:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `MyTrait::func` -... -LL | fn func(self); - | ---- required by a bound in this associated function -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | const fn const_context() where cross_crate::NonConst: cross_crate::MyTrait { - | +++++++++++++++++++++++++++++++++++++++++++++++++ + | ^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.stderr b/tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.stderr index d0f22c0b9b62..7b4d512e3918 100644 --- a/tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.stderr +++ b/tests/ui/traits/const-traits/default-method-body-is-const-same-trait-ck.stderr @@ -1,21 +1,8 @@ error[E0277]: the trait bound `(): ~const Tr` is not satisfied - --> $DIR/default-method-body-is-const-same-trait-ck.rs:10:12 + --> $DIR/default-method-body-is-const-same-trait-ck.rs:10:9 | LL | ().a() - | ^ the trait `Tr` is not implemented for `()` - | -note: required by a bound in `Tr::a` - --> $DIR/default-method-body-is-const-same-trait-ck.rs:5:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Tr::a` -LL | pub trait Tr { -LL | fn a(&self) {} - | - required by a bound in this associated function -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | pub trait Tr where (): Tr { - | ++++++++++++ + | ^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/effects/minicore.stderr b/tests/ui/traits/const-traits/effects/minicore.stderr index 823ab69df9cb..568d98cfe871 100644 --- a/tests/ui/traits/const-traits/effects/minicore.stderr +++ b/tests/ui/traits/const-traits/effects/minicore.stderr @@ -1,13 +1,13 @@ error: the compiler unexpectedly panicked. this is a bug. query stack during panic: -#0 [check_well_formed] checking that `` is well-formed -#1 [check_mod_type_wf] checking that types are well-formed in top-level module +#0 [typeck] type-checking `Clone::clone_from` +#1 [analysis] running analysis passes on this crate end of query stack error: the compiler unexpectedly panicked. this is a bug. query stack during panic: -#0 [check_well_formed] checking that `drop` is well-formed -#1 [check_mod_type_wf] checking that types are well-formed in top-level module +#0 [typeck] type-checking `test_const_eval_select` +#1 [analysis] running analysis passes on this crate end of query stack diff --git a/tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.stderr b/tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.stderr index 8c591edac540..eea6a06c1c81 100644 --- a/tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.stderr +++ b/tests/ui/traits/const-traits/effects/no-explicit-const-params-cross-crate.stderr @@ -16,17 +16,15 @@ error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplie --> $DIR/no-explicit-const-params-cross-crate.rs:16:12 | LL | <() as Bar>::bar(); - | ^^^ expected 0 generic arguments + | ^^^------- help: remove the unnecessary generics + | | + | expected 0 generic arguments | note: trait defined here, with 0 generic parameters --> $DIR/auxiliary/cross-crate.rs:8:11 | LL | pub trait Bar { | ^^^ -help: replace the generic bound with the associated type - | -LL | <() as Bar< = false>>::bar(); - | + error[E0107]: function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/no-explicit-const-params-cross-crate.rs:7:5 @@ -46,17 +44,15 @@ error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplie --> $DIR/no-explicit-const-params-cross-crate.rs:9:12 | LL | <() as Bar>::bar(); - | ^^^ expected 0 generic arguments + | ^^^------ help: remove the unnecessary generics + | | + | expected 0 generic arguments | note: trait defined here, with 0 generic parameters --> $DIR/auxiliary/cross-crate.rs:8:11 | LL | pub trait Bar { | ^^^ -help: replace the generic bound with the associated type - | -LL | <() as Bar< = true>>::bar(); - | + error: aborting due to 4 previous errors diff --git a/tests/ui/traits/const-traits/effects/no-explicit-const-params.rs b/tests/ui/traits/const-traits/effects/no-explicit-const-params.rs index 84f5f2803e15..b08aba9acbcd 100644 --- a/tests/ui/traits/const-traits/effects/no-explicit-const-params.rs +++ b/tests/ui/traits/const-traits/effects/no-explicit-const-params.rs @@ -23,5 +23,4 @@ const FOO: () = { //~^ ERROR: function takes 0 generic arguments but 1 generic argument was supplied <() as Bar>::bar(); //~^ ERROR: trait takes 0 generic arguments but 1 generic argument was supplied - //~| ERROR: mismatched types }; diff --git a/tests/ui/traits/const-traits/effects/no-explicit-const-params.stderr b/tests/ui/traits/const-traits/effects/no-explicit-const-params.stderr index cc08114ddb56..a3aa970e94d2 100644 --- a/tests/ui/traits/const-traits/effects/no-explicit-const-params.stderr +++ b/tests/ui/traits/const-traits/effects/no-explicit-const-params.stderr @@ -30,26 +30,15 @@ error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplie --> $DIR/no-explicit-const-params.rs:24:12 | LL | <() as Bar>::bar(); - | ^^^ expected 0 generic arguments + | ^^^------- help: remove the unnecessary generics + | | + | expected 0 generic arguments | note: trait defined here, with 0 generic parameters --> $DIR/no-explicit-const-params.rs:6:7 | LL | trait Bar { | ^^^ -help: replace the generic bound with the associated type - | -LL | <() as Bar< = false>>::bar(); - | + - -error[E0308]: mismatched types - --> $DIR/no-explicit-const-params.rs:24:5 - | -LL | <() as Bar>::bar(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected `false`, found `true` - | - = note: expected constant `false` - found constant `true` error[E0107]: function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/no-explicit-const-params.rs:15:5 @@ -69,19 +58,16 @@ error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplie --> $DIR/no-explicit-const-params.rs:17:12 | LL | <() as Bar>::bar(); - | ^^^ expected 0 generic arguments + | ^^^------ help: remove the unnecessary generics + | | + | expected 0 generic arguments | note: trait defined here, with 0 generic parameters --> $DIR/no-explicit-const-params.rs:6:7 | LL | trait Bar { | ^^^ -help: replace the generic bound with the associated type - | -LL | <() as Bar< = true>>::bar(); - | + -error: aborting due to 6 previous errors; 1 warning emitted +error: aborting due to 5 previous errors; 1 warning emitted -Some errors have detailed explanations: E0107, E0308. -For more information about an error, try `rustc --explain E0107`. +For more information about this error, try `rustc --explain E0107`. diff --git a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs index 0508b1c5e26b..73d3e883aad9 100644 --- a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs +++ b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs @@ -1,4 +1,3 @@ -//@ check-fail // Fixes #119830 #![feature(effects)] //~ WARN the feature `effects` is incomplete @@ -15,7 +14,9 @@ impl const Foo for T {} impl const Foo for T where T: const Specialize {} //~^ error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` //~| error: `const` can only be applied to `#[const_trait]` traits +//~| error: `const` can only be applied to `#[const_trait]` traits //~| error: specialization impl does not specialize any associated items //~| error: cannot specialize on trait `Specialize` +//~| ERROR cannot specialize on predicate fn main() {} diff --git a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr index e97a9615ae1a..2556903150b4 100644 --- a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr +++ b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/spec-effectvar-ice.rs:4:12 + --> $DIR/spec-effectvar-ice.rs:3:12 | LL | #![feature(effects)] | ^^^^^^^ @@ -13,7 +13,7 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = help: use `-Znext-solver` to enable error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` - --> $DIR/spec-effectvar-ice.rs:12:15 + --> $DIR/spec-effectvar-ice.rs:11:15 | LL | trait Foo {} | - help: mark `Foo` as const: `#[const_trait]` @@ -25,7 +25,7 @@ LL | impl const Foo for T {} = note: adding a non-const method body in the future would be a breaking change error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` - --> $DIR/spec-effectvar-ice.rs:15:15 + --> $DIR/spec-effectvar-ice.rs:14:15 | LL | trait Foo {} | - help: mark `Foo` as const: `#[const_trait]` @@ -37,28 +37,42 @@ LL | impl const Foo for T where T: const Specialize {} = note: adding a non-const method body in the future would be a breaking change error: `const` can only be applied to `#[const_trait]` traits - --> $DIR/spec-effectvar-ice.rs:15:40 + --> $DIR/spec-effectvar-ice.rs:14:40 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^ +error: `const` can only be applied to `#[const_trait]` traits + --> $DIR/spec-effectvar-ice.rs:14:40 + | +LL | impl const Foo for T where T: const Specialize {} + | ^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error: specialization impl does not specialize any associated items - --> $DIR/spec-effectvar-ice.rs:15:1 + --> $DIR/spec-effectvar-ice.rs:14:1 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: impl is a specialization of this impl - --> $DIR/spec-effectvar-ice.rs:12:1 + --> $DIR/spec-effectvar-ice.rs:11:1 | LL | impl const Foo for T {} | ^^^^^^^^^^^^^^^^^^^^^^^ -error: cannot specialize on trait `Specialize` - --> $DIR/spec-effectvar-ice.rs:15:34 +error: cannot specialize on predicate `T: const Specialize` + --> $DIR/spec-effectvar-ice.rs:14:34 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^^^^^^^ -error: aborting due to 6 previous errors; 1 warning emitted +error: cannot specialize on trait `Specialize` + --> $DIR/spec-effectvar-ice.rs:14:34 + | +LL | impl const Foo for T where T: const Specialize {} + | ^^^^^^^^^^^^^^^^ + +error: aborting due to 8 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.rs b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.rs index 64634e7b7ac3..29f40604747b 100644 --- a/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.rs +++ b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.rs @@ -3,5 +3,6 @@ const fn with_positive() {} //~^ ERROR `~const` can only be applied to `#[const_trait]` traits +//~| ERROR `~const` can only be applied to `#[const_trait]` traits pub fn main() {} diff --git a/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr index c937430a1ca1..03f88be00936 100644 --- a/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr +++ b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr @@ -9,5 +9,13 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn with_positive() {} | ^^^^ -error: aborting due to 2 previous errors +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/ice-123664-unexpected-bound-var.rs:4:34 + | +LL | const fn with_positive() {} + | ^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 3 previous errors diff --git a/tests/ui/traits/const-traits/issue-92111.stderr b/tests/ui/traits/const-traits/issue-92111.stderr index ecc994a3fe65..805cc5370149 100644 --- a/tests/ui/traits/const-traits/issue-92111.stderr +++ b/tests/ui/traits/const-traits/issue-92111.stderr @@ -4,6 +4,14 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | const fn a(t: T) {} | ^^^^^^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/issue-92111.rs:20:22 + | +LL | const fn a(t: T) {} + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/issue-92111.rs:20:32 | @@ -12,6 +20,6 @@ LL | const fn a(t: T) {} | | | the destructor for this type cannot be evaluated in constant functions -error: aborting due to 2 previous errors +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0493`. diff --git a/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr index de4783bdb3fe..2803c37646b1 100644 --- a/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr +++ b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr @@ -4,14 +4,13 @@ error: `~const` can only be applied to `#[const_trait]` traits LL | impl const Convert for A where B: ~const From { | ^^^^^^^ -error[E0049]: method `to` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/non-const-op-in-closure-in-const.rs:5:1 +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/non-const-op-in-closure-in-const.rs:10:51 | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Convert { -LL | fn to(self) -> T; - | - expected 0 const parameters +LL | impl const Convert for A where B: ~const From { + | ^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0015]: cannot call non-const fn `>::from` in constant functions --> $DIR/non-const-op-in-closure-in-const.rs:12:9 @@ -27,5 +26,4 @@ LL + #![feature(effects)] error: aborting due to 3 previous errors -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.stderr b/tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.stderr index 7643697874f2..bffc60c65fce 100644 --- a/tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.stderr +++ b/tests/ui/traits/const-traits/specialization/const-default-bound-non-const-specialized-bound.stderr @@ -1,12 +1,3 @@ -error[E0049]: associated function `bar` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-default-bound-non-const-specialized-bound.rs:16:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Bar { -LL | fn bar(); - | - expected 0 const parameters - error: cannot specialize on const impl with non-const impl --> $DIR/const-default-bound-non-const-specialized-bound.rs:28:1 | @@ -16,26 +7,5 @@ LL | | T: Foo, //FIXME ~ ERROR missing `~const` qualifier LL | | T: Specialize, | |__________________^ -error[E0049]: associated function `baz` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-default-bound-non-const-specialized-bound.rs:36:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Baz { -LL | fn baz(); - | - expected 0 const parameters +error: aborting due to 1 previous error -error[E0049]: associated function `baz` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-default-bound-non-const-specialized-bound.rs:36:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Baz { -LL | fn baz(); - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0049`. diff --git a/tests/ui/traits/const-traits/specialization/const-default-const-specialized.stderr b/tests/ui/traits/const-traits/specialization/const-default-const-specialized.stderr index 9b2ae8d739c8..f127268d2a1c 100644 --- a/tests/ui/traits/const-traits/specialization/const-default-const-specialized.stderr +++ b/tests/ui/traits/const-traits/specialization/const-default-const-specialized.stderr @@ -1,23 +1,3 @@ -error[E0049]: associated function `value` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-default-const-specialized.rs:10:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Value { -LL | fn value() -> u32; - | - expected 0 const parameters - -error[E0049]: associated function `value` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/const-default-const-specialized.rs:10:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Value { -LL | fn value() -> u32; - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - error[E0015]: cannot call non-const fn `::value` in constant functions --> $DIR/const-default-const-specialized.rs:16:5 | @@ -30,7 +10,6 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 3 previous errors +error: aborting due to 1 previous error -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/specialization/default-keyword.rs b/tests/ui/traits/const-traits/specialization/default-keyword.rs index d9ffd237dcef..bc45a70777ca 100644 --- a/tests/ui/traits/const-traits/specialization/default-keyword.rs +++ b/tests/ui/traits/const-traits/specialization/default-keyword.rs @@ -1,5 +1,4 @@ -//@ known-bug: #110395 -// FIXME check-pass +//@ check-pass #![feature(const_trait_impl)] #![feature(min_specialization)] diff --git a/tests/ui/traits/const-traits/specialization/default-keyword.stderr b/tests/ui/traits/const-traits/specialization/default-keyword.stderr deleted file mode 100644 index 18a25045f4b0..000000000000 --- a/tests/ui/traits/const-traits/specialization/default-keyword.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/default-keyword.rs:7:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Foo { -LL | fn foo(); - | - expected 0 const parameters - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0049`. diff --git a/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs b/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs index 219e5f3a600c..d80370aee820 100644 --- a/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs +++ b/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.rs @@ -1,7 +1,6 @@ // Tests that `~const` trait bounds can be used to specialize const trait impls. -//@ known-bug: #110395 -// FIXME check-pass +//@ check-pass #![feature(const_trait_impl)] #![feature(rustc_attrs)] diff --git a/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.stderr b/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.stderr deleted file mode 100644 index ecdc7b930e60..000000000000 --- a/tests/ui/traits/const-traits/specialization/issue-95186-specialize-on-tilde-const.stderr +++ /dev/null @@ -1,43 +0,0 @@ -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95186-specialize-on-tilde-const.rs:14:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Foo { -LL | fn foo(); - | - expected 0 const parameters - -error[E0049]: associated function `foo` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95186-specialize-on-tilde-const.rs:14:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Foo { -LL | fn foo(); - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0049]: associated function `bar` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95186-specialize-on-tilde-const.rs:30:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Bar { -LL | fn bar() {} - | - expected 0 const parameters - -error[E0049]: associated function `bar` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95186-specialize-on-tilde-const.rs:30:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Bar { -LL | fn bar() {} - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0049`. diff --git a/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs b/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs index 7514baa2fd55..d97469edaf97 100644 --- a/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs +++ b/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.rs @@ -2,8 +2,7 @@ // `T: Foo` in the default impl for the purposes of specialization (i.e., it // does not think that the user is attempting to specialize on trait `Foo`). -//@ known-bug: #110395 -// FIXME check-pass +//@ check-pass #![feature(rustc_attrs)] #![feature(min_specialization)] diff --git a/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.stderr b/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.stderr deleted file mode 100644 index 6679bb465378..000000000000 --- a/tests/ui/traits/const-traits/specialization/issue-95187-same-trait-bound-different-constness.stderr +++ /dev/null @@ -1,43 +0,0 @@ -error[E0049]: associated function `bar` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95187-same-trait-bound-different-constness.rs:18:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Bar { -LL | fn bar(); - | - expected 0 const parameters - -error[E0049]: associated function `bar` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95187-same-trait-bound-different-constness.rs:18:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Bar { -LL | fn bar(); - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0049]: associated function `baz` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95187-same-trait-bound-different-constness.rs:38:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Baz { -LL | fn baz(); - | - expected 0 const parameters - -error[E0049]: associated function `baz` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/issue-95187-same-trait-bound-different-constness.rs:38:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Baz { -LL | fn baz(); - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0049`. diff --git a/tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.stderr b/tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.stderr index 7f363922947f..a4095d7e8ce5 100644 --- a/tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.stderr +++ b/tests/ui/traits/const-traits/specialization/non-const-default-const-specialized.stderr @@ -1,23 +1,3 @@ -error[E0049]: associated function `value` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/non-const-default-const-specialized.rs:9:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Value { -LL | fn value() -> u32; - | - expected 0 const parameters - -error[E0049]: associated function `value` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/non-const-default-const-specialized.rs:9:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | trait Value { -LL | fn value() -> u32; - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - error[E0015]: cannot call non-const fn `::value` in constant functions --> $DIR/non-const-default-const-specialized.rs:15:5 | @@ -30,7 +10,6 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 3 previous errors +error: aborting due to 1 previous error -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/specializing-constness-2.stderr b/tests/ui/traits/const-traits/specializing-constness-2.stderr index bf273f349b4b..8e6f6945a1b8 100644 --- a/tests/ui/traits/const-traits/specializing-constness-2.stderr +++ b/tests/ui/traits/const-traits/specializing-constness-2.stderr @@ -1,23 +1,3 @@ -error[E0049]: associated function `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/specializing-constness-2.rs:9:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait A { -LL | fn a() -> u32; - | - expected 0 const parameters - -error[E0049]: associated function `a` has 1 const parameter but its trait declaration has 0 const parameters - --> $DIR/specializing-constness-2.rs:9:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ found 1 const parameter -LL | pub trait A { -LL | fn a() -> u32; - | - expected 0 const parameters - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - error[E0015]: cannot call non-const fn `::a` in constant functions --> $DIR/specializing-constness-2.rs:27:5 | @@ -30,7 +10,6 @@ help: add `#![feature(effects)]` to the crate attributes to enable LL + #![feature(effects)] | -error: aborting due to 3 previous errors +error: aborting due to 1 previous error -Some errors have detailed explanations: E0015, E0049. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/specializing-constness.rs b/tests/ui/traits/const-traits/specializing-constness.rs index 4501a218ad72..3aabaf137d54 100644 --- a/tests/ui/traits/const-traits/specializing-constness.rs +++ b/tests/ui/traits/const-traits/specializing-constness.rs @@ -22,8 +22,6 @@ impl const A for T { impl A for T { //~^ ERROR: cannot specialize -//~| ERROR: cannot specialize -//~| ERROR: cannot specialize //FIXME(effects) ~| ERROR: missing `~const` qualifier fn a() -> u32 { 3 diff --git a/tests/ui/traits/const-traits/specializing-constness.stderr b/tests/ui/traits/const-traits/specializing-constness.stderr index 90721af8e5aa..e8c4fb0f0c72 100644 --- a/tests/ui/traits/const-traits/specializing-constness.stderr +++ b/tests/ui/traits/const-traits/specializing-constness.stderr @@ -18,17 +18,5 @@ error: cannot specialize on const impl with non-const impl LL | impl A for T { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: cannot specialize on trait `Compat` - --> $DIR/specializing-constness.rs:23:16 - | -LL | impl A for T { - | ^^^ - -error: cannot specialize on trait `Compat` - --> $DIR/specializing-constness.rs:23:9 - | -LL | impl A for T { - | ^^^^ - -error: aborting due to 4 previous errors; 1 warning emitted +error: aborting due to 2 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr index 029c3b4bde3e..a0848fe520e8 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr @@ -20,5 +20,21 @@ LL | trait Bar: ~const Foo {} | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 3 previous errors +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/super-traits-fail-2.rs:12:19 + | +LL | trait Bar: ~const Foo {} + | ^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/super-traits-fail-2.rs:12:19 + | +LL | trait Bar: ~const Foo {} + | ^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 5 previous errors diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.rs b/tests/ui/traits/const-traits/super-traits-fail-2.rs index 93a6f385e47d..0ea61f4ae200 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.rs +++ b/tests/ui/traits/const-traits/super-traits-fail-2.rs @@ -13,7 +13,9 @@ trait Bar: ~const Foo {} //[ny,nn]~^ ERROR: `~const` can only be applied to `#[const_trait]` //[ny,nn]~| ERROR: `~const` can only be applied to `#[const_trait]` //[ny,nn]~| ERROR: `~const` can only be applied to `#[const_trait]` -//[yn,nn]~^^^^ ERROR: `~const` is not allowed here +//[ny]~| ERROR: `~const` can only be applied to `#[const_trait]` +//[ny]~| ERROR: `~const` can only be applied to `#[const_trait]` +//[yn,nn]~^^^^^^ ERROR: `~const` is not allowed here const fn foo(x: &T) { x.a(); diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.yn.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.yn.stderr index 873c57ec71ff..ec6ca1072890 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.yn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.yn.stderr @@ -11,23 +11,10 @@ LL | trait Bar: ~const Foo {} | ^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `T: ~const Foo` is not satisfied - --> $DIR/super-traits-fail-2.rs:19:7 + --> $DIR/super-traits-fail-2.rs:21:5 | LL | x.a(); - | ^ the trait `Foo` is not implemented for `T` - | -note: required by a bound in `Foo::a` - --> $DIR/super-traits-fail-2.rs:6:25 - | -LL | #[cfg_attr(any(yy, yn), const_trait)] - | ^^^^^^^^^^^ required by this bound in `Foo::a` -LL | trait Foo { -LL | fn a(&self); - | - required by a bound in this associated function -help: consider further restricting this bound - | -LL | const fn foo(x: &T) { - | +++++ + | ^^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.yy.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.yy.stderr index bea3aea2f3af..3fa6256abc34 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.yy.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.yy.stderr @@ -1,21 +1,8 @@ error[E0277]: the trait bound `T: ~const Foo` is not satisfied - --> $DIR/super-traits-fail-2.rs:19:7 + --> $DIR/super-traits-fail-2.rs:21:5 | LL | x.a(); - | ^ the trait `Foo` is not implemented for `T` - | -note: required by a bound in `Foo::a` - --> $DIR/super-traits-fail-2.rs:6:25 - | -LL | #[cfg_attr(any(yy, yn), const_trait)] - | ^^^^^^^^^^^ required by this bound in `Foo::a` -LL | trait Foo { -LL | fn a(&self); - | - required by a bound in this associated function -help: consider further restricting this bound - | -LL | const fn foo(x: &T) { - | +++++ + | ^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr index f40583f0ca57..294545014bf5 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr @@ -33,10 +33,18 @@ LL | trait Bar: ~const Foo {} = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:20:24 + --> $DIR/super-traits-fail-3.rs:22:24 | LL | const fn foo(x: &T) { | ^^^ -error: aborting due to 5 previous errors +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/super-traits-fail-3.rs:22:24 + | +LL | const fn foo(x: &T) { + | ^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 6 previous errors diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr index 3f6dfa7b0089..54bb6c5ca441 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr @@ -20,5 +20,21 @@ LL | trait Bar: ~const Foo {} | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 3 previous errors +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/super-traits-fail-3.rs:14:19 + | +LL | trait Bar: ~const Foo {} + | ^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/super-traits-fail-3.rs:14:19 + | +LL | trait Bar: ~const Foo {} + | ^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 5 previous errors diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.rs b/tests/ui/traits/const-traits/super-traits-fail-3.rs index b5643b117000..a9b08e6edcdc 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.rs +++ b/tests/ui/traits/const-traits/super-traits-fail-3.rs @@ -15,10 +15,13 @@ trait Bar: ~const Foo {} //[ny,nn]~^ ERROR: `~const` can only be applied to `#[const_trait]` //[ny,nn]~| ERROR: `~const` can only be applied to `#[const_trait]` //[ny,nn]~| ERROR: `~const` can only be applied to `#[const_trait]` -//[yn,nn]~^^^^ ERROR: `~const` is not allowed here +//[ny]~| ERROR: `~const` can only be applied to `#[const_trait]` +//[ny]~| ERROR: `~const` can only be applied to `#[const_trait]` +//[yn,nn]~^^^^^^ ERROR: `~const` is not allowed here const fn foo(x: &T) { //[yn,nn]~^ ERROR: `~const` can only be applied to `#[const_trait]` + //[yn,nn]~| ERROR: `~const` can only be applied to `#[const_trait]` x.a(); //[yn]~^ ERROR: the trait bound `T: ~const Foo` is not satisfied } diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr index bbc95948a59d..b6747d10e83c 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr @@ -11,30 +11,25 @@ LL | trait Bar: ~const Foo {} | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:20:24 + --> $DIR/super-traits-fail-3.rs:22:24 | LL | const fn foo(x: &T) { | ^^^ +error: `~const` can only be applied to `#[const_trait]` traits + --> $DIR/super-traits-fail-3.rs:22:24 + | +LL | const fn foo(x: &T) { + | ^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + error[E0277]: the trait bound `T: ~const Foo` is not satisfied - --> $DIR/super-traits-fail-3.rs:22:7 + --> $DIR/super-traits-fail-3.rs:25:5 | LL | x.a(); - | ^ the trait `Foo` is not implemented for `T` - | -note: required by a bound in `Foo::a` - --> $DIR/super-traits-fail-3.rs:8:25 - | -LL | #[cfg_attr(any(yy, yn), const_trait)] - | ^^^^^^^^^^^ required by this bound in `Foo::a` -LL | trait Foo { -LL | fn a(&self); - | - required by a bound in this associated function -help: consider further restricting this bound - | -LL | const fn foo(x: &T) { - | +++++ + | ^^^^^ -error: aborting due to 3 previous errors +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/super-traits-fail.rs b/tests/ui/traits/const-traits/super-traits-fail.rs index da41d7fcc723..c07619fbf621 100644 --- a/tests/ui/traits/const-traits/super-traits-fail.rs +++ b/tests/ui/traits/const-traits/super-traits-fail.rs @@ -1,4 +1,3 @@ -//~ ERROR the trait bound //@ compile-flags: -Znext-solver #![allow(incomplete_features)] diff --git a/tests/ui/traits/const-traits/super-traits-fail.stderr b/tests/ui/traits/const-traits/super-traits-fail.stderr index 3870f0f722f9..7a734a6c9f1c 100644 --- a/tests/ui/traits/const-traits/super-traits-fail.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail.stderr @@ -1,24 +1,9 @@ -error[E0277]: the trait bound `Bar::{synthetic#0}: TyCompat` is not satisfied - --> $DIR/super-traits-fail.rs:19:12 +error[E0277]: the trait bound `S: ~const Foo` is not satisfied + --> $DIR/super-traits-fail.rs:18:20 | LL | impl const Bar for S {} - | ^^^ the trait `TyCompat` is not implemented for `Bar::{synthetic#0}`, which is required by `S: Bar` - | - = help: the trait `Bar` is implemented for `S` -note: required for `S` to implement `Bar` - --> $DIR/super-traits-fail.rs:12:7 - | -LL | trait Bar: ~const Foo {} - | ^^^ + | ^ -error[E0277]: the trait bound `Maybe: TyCompat` is not satisfied - | -note: required by a bound in `Bar::{synthetic#0}` - --> $DIR/super-traits-fail.rs:12:12 - | -LL | trait Bar: ~const Foo {} - | ^^^^^^^^^^ required by this bound in `Bar::{synthetic#0}` - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/tilde-const-and-const-params.rs b/tests/ui/traits/const-traits/tilde-const-and-const-params.rs index 4b720b534a49..f6a7c7c17461 100644 --- a/tests/ui/traits/const-traits/tilde-const-and-const-params.rs +++ b/tests/ui/traits/const-traits/tilde-const-and-const-params.rs @@ -8,7 +8,6 @@ struct Foo; impl Foo { fn add(self) -> Foo<{ A::add(N) }> { //~^ ERROR `~const` is not allowed here - //~| ERROR mismatched types Foo } } @@ -26,7 +25,6 @@ impl const Add42 for () { fn bar(_: Foo) -> Foo<{ A::add(N) }> { //~^ ERROR `~const` is not allowed here - //~| ERROR mismatched types Foo } diff --git a/tests/ui/traits/const-traits/tilde-const-and-const-params.stderr b/tests/ui/traits/const-traits/tilde-const-and-const-params.stderr index 73526a26e081..84a425f6791b 100644 --- a/tests/ui/traits/const-traits/tilde-const-and-const-params.stderr +++ b/tests/ui/traits/const-traits/tilde-const-and-const-params.stderr @@ -11,13 +11,13 @@ LL | fn add(self) -> Foo<{ A::add(N) }> { | ^^^ error: `~const` is not allowed here - --> $DIR/tilde-const-and-const-params.rs:27:11 + --> $DIR/tilde-const-and-const-params.rs:26:11 | LL | fn bar(_: Foo) -> Foo<{ A::add(N) }> { | ^^^^^^ | note: this function is not `const`, so it cannot have `~const` trait bounds - --> $DIR/tilde-const-and-const-params.rs:27:4 + --> $DIR/tilde-const-and-const-params.rs:26:4 | LL | fn bar(_: Foo) -> Foo<{ A::add(N) }> { | ^^^ @@ -27,24 +27,5 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = note: the next trait solver must be enabled globally for the effects feature to work correctly = help: use `-Znext-solver` to enable -error[E0308]: mismatched types - --> $DIR/tilde-const-and-const-params.rs:27:61 - | -LL | fn bar(_: Foo) -> Foo<{ A::add(N) }> { - | ^^^^^^^^^ expected `false`, found `true` - | - = note: expected constant `false` - found constant `true` +error: aborting due to 3 previous errors -error[E0308]: mismatched types - --> $DIR/tilde-const-and-const-params.rs:9:44 - | -LL | fn add(self) -> Foo<{ A::add(N) }> { - | ^^^^^^^^^ expected `false`, found `true` - | - = note: expected constant `false` - found constant `true` - -error: aborting due to 5 previous errors - -For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/traits/const-traits/trait-where-clause-const.rs b/tests/ui/traits/const-traits/trait-where-clause-const.rs index 8ca9b7cc7aa0..61e2bc384268 100644 --- a/tests/ui/traits/const-traits/trait-where-clause-const.rs +++ b/tests/ui/traits/const-traits/trait-where-clause-const.rs @@ -20,11 +20,9 @@ trait Foo { const fn test1() { T::a(); T::b(); - //~^ ERROR mismatched types - //~| ERROR the trait bound + //~^ ERROR the trait bound T::c::(); - //~^ ERROR mismatched types - //~| ERROR the trait bound + //~^ ERROR the trait bound } const fn test2() { diff --git a/tests/ui/traits/const-traits/trait-where-clause-const.stderr b/tests/ui/traits/const-traits/trait-where-clause-const.stderr index eaa981ec7444..30a7ef1fd0d3 100644 --- a/tests/ui/traits/const-traits/trait-where-clause-const.stderr +++ b/tests/ui/traits/const-traits/trait-where-clause-const.stderr @@ -1,52 +1,15 @@ -error[E0277]: the trait bound `T: Foo` is not satisfied +error[E0277]: the trait bound `T: ~const Bar` is not satisfied --> $DIR/trait-where-clause-const.rs:22:5 | LL | T::b(); - | ^ the trait `Foo` is not implemented for `T` - | -note: required by a bound in `Foo::b` - --> $DIR/trait-where-clause-const.rs:13:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Foo::b` -... -LL | fn b() where Self: ~const Bar; - | - required by a bound in this associated function + | ^^^^^^ -error[E0308]: mismatched types - --> $DIR/trait-where-clause-const.rs:22:5 - | -LL | T::b(); - | ^^^^^^ expected `host`, found `true` - | - = note: expected constant `host` - found constant `true` - -error[E0277]: the trait bound `T: Foo` is not satisfied - --> $DIR/trait-where-clause-const.rs:25:5 +error[E0277]: the trait bound `T: ~const Bar` is not satisfied + --> $DIR/trait-where-clause-const.rs:24:5 | LL | T::c::(); - | ^ the trait `Foo` is not implemented for `T` - | -note: required by a bound in `Foo::c` - --> $DIR/trait-where-clause-const.rs:13:1 - | -LL | #[const_trait] - | ^^^^^^^^^^^^^^ required by this bound in `Foo::c` -... -LL | fn c(); - | - required by a bound in this associated function + | ^^^^^^^^^^^ -error[E0308]: mismatched types - --> $DIR/trait-where-clause-const.rs:25:5 - | -LL | T::c::(); - | ^^^^^^^^^^^ expected `host`, found `true` - | - = note: expected constant `host` - found constant `true` +error: aborting due to 2 previous errors -error: aborting due to 4 previous errors - -Some errors have detailed explanations: E0277, E0308. -For more information about an error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr b/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr index 848aa68689b4..e0cf062ad95e 100644 --- a/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr +++ b/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr @@ -6,41 +6,30 @@ LL | #![feature(const_trait_impl, effects, generic_const_exprs)] | = help: remove one of these features -error[E0308]: mismatched types +error[E0277]: the trait bound `T: const Trait` is not satisfied --> $DIR/unsatisfied-const-trait-bound.rs:29:37 | LL | fn accept0(_: Container<{ T::make() }>) {} - | ^^^^^^^^^ expected `false`, found `true` - | - = note: expected constant `false` - found constant `true` + | ^^^^^^^^^ -error[E0308]: mismatched types +error[E0277]: the trait bound `T: const Trait` is not satisfied --> $DIR/unsatisfied-const-trait-bound.rs:33:50 | LL | const fn accept1(_: Container<{ T::make() }>) {} - | ^^^^^^^^^ expected `false`, found `host` - | - = note: expected constant `false` - found constant `host` + | ^^^^^^^^^ error[E0277]: the trait bound `Ty: const Trait` is not satisfied - --> $DIR/unsatisfied-const-trait-bound.rs:22:15 + --> $DIR/unsatisfied-const-trait-bound.rs:22:5 | LL | require::(); - | ^^ the trait `Trait` is not implemented for `Ty` + | ^^^^^^^^^^^^^^^ | note: required by a bound in `require` --> $DIR/unsatisfied-const-trait-bound.rs:8:15 | LL | fn require() {} | ^^^^^^^^^^^ required by this bound in `require` -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | fn main() where Ty: Trait { - | +++++++++++++++ error: aborting due to 4 previous errors -Some errors have detailed explanations: E0277, E0308. -For more information about an error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0277`. From 779b3943d32816ce1d77672be78eb2871071322c Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 21 Oct 2024 19:37:48 +0000 Subject: [PATCH 203/366] Add next-solver to more effects tests --- tests/ui/consts/const-try.rs | 4 +++- tests/ui/consts/const-try.stderr | 9 ++----- .../assoc-type-const-bound-usage-0.rs | 1 + .../assoc-type-const-bound-usage-0.stderr | 16 +++++++++---- .../assoc-type-const-bound-usage-1.rs | 2 +- .../assoc-type-const-bound-usage-1.stderr | 24 +++++++++++++++---- tests/ui/traits/const-traits/assoc-type.rs | 5 ++-- .../ui/traits/const-traits/assoc-type.stderr | 16 +++++++++---- .../const-traits/call-generic-method-chain.rs | 1 + .../call-generic-method-chain.stderr | 19 ++++++--------- .../call-generic-method-dup-bound.rs | 1 + .../call-generic-method-dup-bound.stderr | 19 ++++++--------- .../const-traits/call-generic-method-pass.rs | 1 + .../call-generic-method-pass.stderr | 15 ++++-------- .../const-bound-on-not-const-associated-fn.rs | 2 ++ ...st-bound-on-not-const-associated-fn.stderr | 15 ++++-------- .../const-check-fns-in-const-impl.rs | 2 ++ .../const-check-fns-in-const-impl.stderr | 11 +++------ .../const-impl-requires-const-trait.rs | 7 +++--- .../const-impl-requires-const-trait.stderr | 20 +++------------- .../traits/const-traits/const-impl-trait.rs | 3 +++ .../ui/traits/const-traits/hir-const-check.rs | 2 ++ .../const-traits/hir-const-check.stderr | 11 +++------ 23 files changed, 102 insertions(+), 104 deletions(-) diff --git a/tests/ui/consts/const-try.rs b/tests/ui/consts/const-try.rs index 9089dd70a26a..2862b6ffb17b 100644 --- a/tests/ui/consts/const-try.rs +++ b/tests/ui/consts/const-try.rs @@ -1,4 +1,4 @@ -//@ known-bug: #110395 +//@ compile-flags: -Znext-solver // Demonstrates what's needed to make use of `?` in const contexts. @@ -14,12 +14,14 @@ struct TryMe; struct Error; impl const FromResidual for TryMe { + //~^ ERROR const `impl` for trait `FromResidual` which is not marked with `#[const_trait]` fn from_residual(residual: Error) -> Self { TryMe } } impl const Try for TryMe { + //~^ ERROR const `impl` for trait `Try` which is not marked with `#[const_trait]` type Output = (); type Residual = Error; fn from_output(output: Self::Output) -> Self { diff --git a/tests/ui/consts/const-try.stderr b/tests/ui/consts/const-try.stderr index 8afdd4e0d61b..ba9da2421073 100644 --- a/tests/ui/consts/const-try.stderr +++ b/tests/ui/consts/const-try.stderr @@ -1,8 +1,3 @@ -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - error: const `impl` for trait `FromResidual` which is not marked with `#[const_trait]` --> $DIR/const-try.rs:16:12 | @@ -13,7 +8,7 @@ LL | impl const FromResidual for TryMe { = note: adding a non-const method body in the future would be a breaking change error: const `impl` for trait `Try` which is not marked with `#[const_trait]` - --> $DIR/const-try.rs:22:12 + --> $DIR/const-try.rs:23:12 | LL | impl const Try for TryMe { | ^^^ @@ -21,5 +16,5 @@ LL | impl const Try for TryMe { = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs index 4399ae2d1be3..5a54e8eec91f 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs @@ -1,3 +1,4 @@ +//@ compile-flags: -Znext-solver //@ known-bug: unknown #![allow(incomplete_features)] diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr index 20448f51de22..35069a5a52fc 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr @@ -1,7 +1,15 @@ -error: using `#![feature(effects)]` without enabling next trait solver globally +error[E0271]: type mismatch resolving `::Assoc == T` + --> $DIR/assoc-type-const-bound-usage-0.rs:14:5 | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable +LL | T::Assoc::func() + | ^^^^^^^^^^^^^^^^ types differ -error: aborting due to 1 previous error +error[E0271]: type mismatch resolving `::Assoc == T` + --> $DIR/assoc-type-const-bound-usage-0.rs:18:5 + | +LL | ::Assoc::func() + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.rs index 8a1bf75f87e1..04ad94556c38 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.rs +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.rs @@ -1,5 +1,5 @@ +//@ compile-flags: -Znext-solver //@ known-bug: unknown -// FIXME(effects) #![feature(const_trait_impl, effects, generic_const_exprs)] #![allow(incomplete_features)] diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr index 20448f51de22..ed9182c73342 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr @@ -1,7 +1,23 @@ -error: using `#![feature(effects)]` without enabling next trait solver globally +error: `-Znext-solver=globally` and `generic_const_exprs` are incompatible, using them at the same time is not allowed + --> $DIR/assoc-type-const-bound-usage-1.rs:4:39 | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable +LL | #![feature(const_trait_impl, effects, generic_const_exprs)] + | ^^^^^^^^^^^^^^^^^^^ + | + = help: remove one of these features -error: aborting due to 1 previous error +error[E0271]: type mismatch resolving `::Assoc == T` + --> $DIR/assoc-type-const-bound-usage-1.rs:15:44 + | +LL | fn unqualified() -> Type<{ T::Assoc::func() }> { + | ^^^^^^^^^^^^^^^^ types differ +error[E0271]: type mismatch resolving `::Assoc == T` + --> $DIR/assoc-type-const-bound-usage-1.rs:19:42 + | +LL | fn qualified() -> Type<{ ::Assoc::func() }> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/const-traits/assoc-type.rs b/tests/ui/traits/const-traits/assoc-type.rs index ea3cbabf3020..a9394d90ed88 100644 --- a/tests/ui/traits/const-traits/assoc-type.rs +++ b/tests/ui/traits/const-traits/assoc-type.rs @@ -1,4 +1,5 @@ -// FIXME(effects): Replace `Add` with `std::ops::Add` once the latter a `#[const_trait]` again. +//@ compile-flags: -Znext-solver + #![feature(const_trait_impl, effects)] //~ WARN the feature `effects` is incomplete #[const_trait] @@ -33,7 +34,7 @@ trait Foo { impl const Foo for NonConstAdd { type Bar = NonConstAdd; - // FIXME(effects) ERROR the trait bound `NonConstAdd: ~const Add` is not satisfied + //~^ ERROR the trait bound `NonConstAdd: ~const Add` is not satisfied } #[const_trait] diff --git a/tests/ui/traits/const-traits/assoc-type.stderr b/tests/ui/traits/const-traits/assoc-type.stderr index c20b53c210fe..5c77754200a6 100644 --- a/tests/ui/traits/const-traits/assoc-type.stderr +++ b/tests/ui/traits/const-traits/assoc-type.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/assoc-type.rs:2:30 + --> $DIR/assoc-type.rs:3:30 | LL | #![feature(const_trait_impl, effects)] | ^^^^^^^ @@ -7,10 +7,18 @@ LL | #![feature(const_trait_impl, effects)] = note: see issue #102090 for more information = note: `#[warn(incomplete_features)]` on by default -error: using `#![feature(effects)]` without enabling next trait solver globally +error[E0277]: the trait bound `NonConstAdd: ~const Add` is not satisfied + --> $DIR/assoc-type.rs:36:16 | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable +LL | type Bar = NonConstAdd; + | ^^^^^^^^^^^ + | +note: required by a bound in `Foo::Bar` + --> $DIR/assoc-type.rs:32:15 + | +LL | type Bar: ~const Add; + | ^^^^^^^^^^ required by this bound in `Foo::Bar` error: aborting due to 1 previous error; 1 warning emitted +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/call-generic-method-chain.rs b/tests/ui/traits/const-traits/call-generic-method-chain.rs index 9df694a02f59..e5baedae818b 100644 --- a/tests/ui/traits/const-traits/call-generic-method-chain.rs +++ b/tests/ui/traits/const-traits/call-generic-method-chain.rs @@ -1,6 +1,7 @@ //! Basic test for calling methods on generic type parameters in `const fn`. //@ known-bug: #110395 +//@ compile-flags: -Znext-solver // FIXME(effects) check-pass #![feature(const_trait_impl, effects)] diff --git a/tests/ui/traits/const-traits/call-generic-method-chain.stderr b/tests/ui/traits/const-traits/call-generic-method-chain.stderr index dce9f0853904..62eed0f14f9c 100644 --- a/tests/ui/traits/const-traits/call-generic-method-chain.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-chain.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/call-generic-method-chain.rs:6:30 + --> $DIR/call-generic-method-chain.rs:7:30 | LL | #![feature(const_trait_impl, effects)] | ^^^^^^^ @@ -7,13 +7,8 @@ LL | #![feature(const_trait_impl, effects)] = note: see issue #102090 for more information = note: `#[warn(incomplete_features)]` on by default -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` - --> $DIR/call-generic-method-chain.rs:10:12 + --> $DIR/call-generic-method-chain.rs:11:12 | LL | impl const PartialEq for S { | ^^^^^^^^^ @@ -22,13 +17,13 @@ LL | impl const PartialEq for S { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:19:32 + --> $DIR/call-generic-method-chain.rs:20:32 | LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:19:32 + --> $DIR/call-generic-method-chain.rs:20:32 | LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ @@ -36,18 +31,18 @@ LL | const fn equals_self(t: &T) -> bool { = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:23:40 + --> $DIR/call-generic-method-chain.rs:24:40 | LL | const fn equals_self_wrapper(t: &T) -> bool { | ^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:23:40 + --> $DIR/call-generic-method-chain.rs:24:40 | LL | const fn equals_self_wrapper(t: &T) -> bool { | ^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 6 previous errors; 1 warning emitted +error: aborting due to 5 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/call-generic-method-dup-bound.rs b/tests/ui/traits/const-traits/call-generic-method-dup-bound.rs index f46a34911f19..83a4bb254362 100644 --- a/tests/ui/traits/const-traits/call-generic-method-dup-bound.rs +++ b/tests/ui/traits/const-traits/call-generic-method-dup-bound.rs @@ -1,3 +1,4 @@ +//@ compile-flags: -Znext-solver //@ known-bug: #110395 // FIXME(effects) check-pass diff --git a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr index 5da511a580e2..3f9dce919d05 100644 --- a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/call-generic-method-dup-bound.rs:4:30 + --> $DIR/call-generic-method-dup-bound.rs:5:30 | LL | #![feature(const_trait_impl, effects)] | ^^^^^^^ @@ -7,13 +7,8 @@ LL | #![feature(const_trait_impl, effects)] = note: see issue #102090 for more information = note: `#[warn(incomplete_features)]` on by default -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` - --> $DIR/call-generic-method-dup-bound.rs:8:12 + --> $DIR/call-generic-method-dup-bound.rs:9:12 | LL | impl const PartialEq for S { | ^^^^^^^^^ @@ -22,13 +17,13 @@ LL | impl const PartialEq for S { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:19:44 + --> $DIR/call-generic-method-dup-bound.rs:20:44 | LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:19:44 + --> $DIR/call-generic-method-dup-bound.rs:20:44 | LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ @@ -36,18 +31,18 @@ LL | const fn equals_self(t: &T) -> bool { = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:26:37 + --> $DIR/call-generic-method-dup-bound.rs:27:37 | LL | const fn equals_self2(t: &T) -> bool { | ^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:26:37 + --> $DIR/call-generic-method-dup-bound.rs:27:37 | LL | const fn equals_self2(t: &T) -> bool { | ^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 6 previous errors; 1 warning emitted +error: aborting due to 5 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/call-generic-method-pass.rs b/tests/ui/traits/const-traits/call-generic-method-pass.rs index 413685d8b344..cbeeb2567dd5 100644 --- a/tests/ui/traits/const-traits/call-generic-method-pass.rs +++ b/tests/ui/traits/const-traits/call-generic-method-pass.rs @@ -1,5 +1,6 @@ //! Basic test for calling methods on generic type parameters in `const fn`. +//@ compile-flags: -Znext-solver //@ known-bug: #110395 // FIXME(effects) check-pass diff --git a/tests/ui/traits/const-traits/call-generic-method-pass.stderr b/tests/ui/traits/const-traits/call-generic-method-pass.stderr index 52579813b691..e35de48ed606 100644 --- a/tests/ui/traits/const-traits/call-generic-method-pass.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-pass.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/call-generic-method-pass.rs:6:30 + --> $DIR/call-generic-method-pass.rs:7:30 | LL | #![feature(const_trait_impl, effects)] | ^^^^^^^ @@ -7,13 +7,8 @@ LL | #![feature(const_trait_impl, effects)] = note: see issue #102090 for more information = note: `#[warn(incomplete_features)]` on by default -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` - --> $DIR/call-generic-method-pass.rs:10:12 + --> $DIR/call-generic-method-pass.rs:11:12 | LL | impl const PartialEq for S { | ^^^^^^^^^ @@ -22,18 +17,18 @@ LL | impl const PartialEq for S { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-pass.rs:19:32 + --> $DIR/call-generic-method-pass.rs:20:32 | LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-pass.rs:19:32 + --> $DIR/call-generic-method-pass.rs:20:32 | LL | const fn equals_self(t: &T) -> bool { | ^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 4 previous errors; 1 warning emitted +error: aborting due to 3 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.rs b/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.rs index 099cf0b00d3f..7c3e2af17977 100644 --- a/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.rs +++ b/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.rs @@ -1,3 +1,5 @@ +//@ compile-flags: -Znext-solver + #![allow(incomplete_features)] #![feature(const_trait_impl, effects)] diff --git a/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.stderr b/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.stderr index b5d9b1fff8a1..ae1260ffab79 100644 --- a/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.stderr +++ b/tests/ui/traits/const-traits/const-bound-on-not-const-associated-fn.stderr @@ -1,31 +1,26 @@ error: `~const` is not allowed here - --> $DIR/const-bound-on-not-const-associated-fn.rs:10:40 + --> $DIR/const-bound-on-not-const-associated-fn.rs:12:40 | LL | fn do_something_else() where Self: ~const MyTrait; | ^^^^^^ | note: this function is not `const`, so it cannot have `~const` trait bounds - --> $DIR/const-bound-on-not-const-associated-fn.rs:10:8 + --> $DIR/const-bound-on-not-const-associated-fn.rs:12:8 | LL | fn do_something_else() where Self: ~const MyTrait; | ^^^^^^^^^^^^^^^^^ error: `~const` is not allowed here - --> $DIR/const-bound-on-not-const-associated-fn.rs:21:32 + --> $DIR/const-bound-on-not-const-associated-fn.rs:23:32 | LL | pub fn foo(&self) where T: ~const MyTrait { | ^^^^^^ | note: this function is not `const`, so it cannot have `~const` trait bounds - --> $DIR/const-bound-on-not-const-associated-fn.rs:21:12 + --> $DIR/const-bound-on-not-const-associated-fn.rs:23:12 | LL | pub fn foo(&self) where T: ~const MyTrait { | ^^^ -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/const-check-fns-in-const-impl.rs b/tests/ui/traits/const-traits/const-check-fns-in-const-impl.rs index a1710e652529..7f9b38b82076 100644 --- a/tests/ui/traits/const-traits/const-check-fns-in-const-impl.rs +++ b/tests/ui/traits/const-traits/const-check-fns-in-const-impl.rs @@ -1,3 +1,5 @@ +//@ compile-flags: -Znext-solver + #![feature(const_trait_impl, effects)] //~ WARN the feature `effects` is incomplete struct S; diff --git a/tests/ui/traits/const-traits/const-check-fns-in-const-impl.stderr b/tests/ui/traits/const-traits/const-check-fns-in-const-impl.stderr index 49cd1725c8cf..ba12854987e2 100644 --- a/tests/ui/traits/const-traits/const-check-fns-in-const-impl.stderr +++ b/tests/ui/traits/const-traits/const-check-fns-in-const-impl.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/const-check-fns-in-const-impl.rs:1:30 + --> $DIR/const-check-fns-in-const-impl.rs:3:30 | LL | #![feature(const_trait_impl, effects)] | ^^^^^^^ @@ -7,19 +7,14 @@ LL | #![feature(const_trait_impl, effects)] = note: see issue #102090 for more information = note: `#[warn(incomplete_features)]` on by default -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - error[E0015]: cannot call non-const fn `non_const` in constant functions - --> $DIR/const-check-fns-in-const-impl.rs:12:16 + --> $DIR/const-check-fns-in-const-impl.rs:14:16 | LL | fn foo() { non_const() } | ^^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-impl-requires-const-trait.rs b/tests/ui/traits/const-traits/const-impl-requires-const-trait.rs index bd6f476f8792..e49e9090eb43 100644 --- a/tests/ui/traits/const-traits/const-impl-requires-const-trait.rs +++ b/tests/ui/traits/const-traits/const-impl-requires-const-trait.rs @@ -1,11 +1,10 @@ -//@ known-bug: #110395 - +//@ compile-flags: -Znext-solver #![feature(const_trait_impl, effects)] +#![allow(incomplete_features)] pub trait A {} -// FIXME ~^ HELP: mark `A` as const impl const A for () {} -// FIXME ~^ ERROR: const `impl` for trait `A` which is not marked with `#[const_trait]` +//~^ ERROR: const `impl` for trait `A` which is not marked with `#[const_trait]` fn main() {} diff --git a/tests/ui/traits/const-traits/const-impl-requires-const-trait.stderr b/tests/ui/traits/const-traits/const-impl-requires-const-trait.stderr index 2a030369093d..828e2174f000 100644 --- a/tests/ui/traits/const-traits/const-impl-requires-const-trait.stderr +++ b/tests/ui/traits/const-traits/const-impl-requires-const-trait.stderr @@ -1,28 +1,14 @@ -warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/const-impl-requires-const-trait.rs:3:30 - | -LL | #![feature(const_trait_impl, effects)] - | ^^^^^^^ - | - = note: see issue #102090 for more information - = note: `#[warn(incomplete_features)]` on by default - -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - error: const `impl` for trait `A` which is not marked with `#[const_trait]` - --> $DIR/const-impl-requires-const-trait.rs:8:12 + --> $DIR/const-impl-requires-const-trait.rs:7:12 | LL | pub trait A {} | - help: mark `A` as const: `#[const_trait]` -... +LL | LL | impl const A for () {} | ^ | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/const-impl-trait.rs b/tests/ui/traits/const-traits/const-impl-trait.rs index 51dfe29b8290..61b8c9a5bff8 100644 --- a/tests/ui/traits/const-traits/const-impl-trait.rs +++ b/tests/ui/traits/const-traits/const-impl-trait.rs @@ -1,4 +1,7 @@ +//@ compile-flags: -Znext-solver //@ known-bug: #110395 +//@ failure-status: 101 +//@ dont-check-compiler-stderr // Broken until we have `&T: const Deref` impl in stdlib #![allow(incomplete_features)] diff --git a/tests/ui/traits/const-traits/hir-const-check.rs b/tests/ui/traits/const-traits/hir-const-check.rs index f5fb0fd516a7..b3df6495afc9 100644 --- a/tests/ui/traits/const-traits/hir-const-check.rs +++ b/tests/ui/traits/const-traits/hir-const-check.rs @@ -1,3 +1,5 @@ +//@ compile-flags: -Znext-solver + // Regression test for #69615. #![feature(const_trait_impl, effects)] //~ WARN the feature `effects` is incomplete diff --git a/tests/ui/traits/const-traits/hir-const-check.stderr b/tests/ui/traits/const-traits/hir-const-check.stderr index 598129d8694e..19ea734efb77 100644 --- a/tests/ui/traits/const-traits/hir-const-check.stderr +++ b/tests/ui/traits/const-traits/hir-const-check.stderr @@ -1,5 +1,5 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/hir-const-check.rs:3:30 + --> $DIR/hir-const-check.rs:5:30 | LL | #![feature(const_trait_impl, effects)] | ^^^^^^^ @@ -8,7 +8,7 @@ LL | #![feature(const_trait_impl, effects)] = note: `#[warn(incomplete_features)]` on by default error[E0658]: `?` is not allowed in a `const fn` - --> $DIR/hir-const-check.rs:12:9 + --> $DIR/hir-const-check.rs:14:9 | LL | Some(())?; | ^^^^^^^^^ @@ -17,11 +17,6 @@ LL | Some(())?; = help: add `#![feature(const_try)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: using `#![feature(effects)]` without enabling next trait solver globally - | - = note: the next trait solver must be enabled globally for the effects feature to work correctly - = help: use `-Znext-solver` to enable - -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0658`. From 25c9253379fa89ae2b45bb6359ef4243ee77345b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 21 Oct 2024 20:16:33 +0000 Subject: [PATCH 204/366] Add tests --- .../traits/const-traits/call-const-closure.rs | 22 +++++++ .../const-traits/call-const-closure.stderr | 9 +++ .../const-traits/call-const-in-tilde-const.rs | 14 ++++ .../call-const-in-tilde-const.stderr | 18 +++++ .../const-traits/const-bound-in-host.rs | 15 +++++ .../const-traits/const-bound-in-host.stderr | 11 ++++ .../traits/const-traits/const-in-closure.rs | 25 +++++++ .../const-traits/const-in-closure.stderr | 11 ++++ .../const-traits/dont-observe-host-opaque.rs | 12 ++++ .../dont-observe-host-opaque.stderr | 11 ++++ .../traits/const-traits/dont-observe-host.rs | 23 +++++++ .../const-traits/dont-observe-host.stderr | 11 ++++ tests/ui/traits/const-traits/fn-ptr-lub.rs | 20 ++++++ .../ui/traits/const-traits/fn-ptr-lub.stderr | 11 ++++ .../item-bound-entailment-fails.rs | 31 +++++++++ .../item-bound-entailment-fails.stderr | 36 ++++++++++ .../const-traits/item-bound-entailment.rs | 31 +++++++++ .../const-traits/item-bound-entailment.stderr | 11 ++++ .../predicate-entailment-fails.rs | 43 ++++++++++++ .../predicate-entailment-fails.stderr | 66 +++++++++++++++++++ .../predicate-entailment-passes.rs | 39 +++++++++++ .../predicate-entailment-passes.stderr | 11 ++++ .../tilde-const-in-struct-args.rs | 21 ++++++ .../tilde-const-in-struct-args.stderr | 11 ++++ 24 files changed, 513 insertions(+) create mode 100644 tests/ui/traits/const-traits/call-const-closure.rs create mode 100644 tests/ui/traits/const-traits/call-const-closure.stderr create mode 100644 tests/ui/traits/const-traits/call-const-in-tilde-const.rs create mode 100644 tests/ui/traits/const-traits/call-const-in-tilde-const.stderr create mode 100644 tests/ui/traits/const-traits/const-bound-in-host.rs create mode 100644 tests/ui/traits/const-traits/const-bound-in-host.stderr create mode 100644 tests/ui/traits/const-traits/const-in-closure.rs create mode 100644 tests/ui/traits/const-traits/const-in-closure.stderr create mode 100644 tests/ui/traits/const-traits/dont-observe-host-opaque.rs create mode 100644 tests/ui/traits/const-traits/dont-observe-host-opaque.stderr create mode 100644 tests/ui/traits/const-traits/dont-observe-host.rs create mode 100644 tests/ui/traits/const-traits/dont-observe-host.stderr create mode 100644 tests/ui/traits/const-traits/fn-ptr-lub.rs create mode 100644 tests/ui/traits/const-traits/fn-ptr-lub.stderr create mode 100644 tests/ui/traits/const-traits/item-bound-entailment-fails.rs create mode 100644 tests/ui/traits/const-traits/item-bound-entailment-fails.stderr create mode 100644 tests/ui/traits/const-traits/item-bound-entailment.rs create mode 100644 tests/ui/traits/const-traits/item-bound-entailment.stderr create mode 100644 tests/ui/traits/const-traits/predicate-entailment-fails.rs create mode 100644 tests/ui/traits/const-traits/predicate-entailment-fails.stderr create mode 100644 tests/ui/traits/const-traits/predicate-entailment-passes.rs create mode 100644 tests/ui/traits/const-traits/predicate-entailment-passes.stderr create mode 100644 tests/ui/traits/const-traits/tilde-const-in-struct-args.rs create mode 100644 tests/ui/traits/const-traits/tilde-const-in-struct-args.stderr diff --git a/tests/ui/traits/const-traits/call-const-closure.rs b/tests/ui/traits/const-traits/call-const-closure.rs new file mode 100644 index 000000000000..cbf3e6c3ac40 --- /dev/null +++ b/tests/ui/traits/const-traits/call-const-closure.rs @@ -0,0 +1,22 @@ +//@ compile-flags: -Znext-solver +//@ edition:2021 + +#![feature(const_trait_impl, effects, const_closures)] +#![allow(incomplete_features)] + +#[const_trait] +trait Bar { + fn foo(&self); +} + +impl Bar for () { + fn foo(&self) {} +} + +const FOO: () = { + (const || ().foo())(); + //~^ ERROR the trait bound `(): ~const Bar` is not satisfied + // FIXME(effects): The constness environment for const closures is wrong. +}; + +fn main() {} diff --git a/tests/ui/traits/const-traits/call-const-closure.stderr b/tests/ui/traits/const-traits/call-const-closure.stderr new file mode 100644 index 000000000000..3fed67f5d088 --- /dev/null +++ b/tests/ui/traits/const-traits/call-const-closure.stderr @@ -0,0 +1,9 @@ +error[E0277]: the trait bound `(): ~const Bar` is not satisfied + --> $DIR/call-const-closure.rs:17:15 + | +LL | (const || ().foo())(); + | ^^^^^^^^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/call-const-in-tilde-const.rs b/tests/ui/traits/const-traits/call-const-in-tilde-const.rs new file mode 100644 index 000000000000..970ee93fd49a --- /dev/null +++ b/tests/ui/traits/const-traits/call-const-in-tilde-const.rs @@ -0,0 +1,14 @@ +//@ compile-flags: -Znext-solver +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Foo { + fn foo(); +} + +const fn foo() { + const { T::foo() } + //~^ ERROR the trait bound `T: const Foo` is not satisfied +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/call-const-in-tilde-const.stderr b/tests/ui/traits/const-traits/call-const-in-tilde-const.stderr new file mode 100644 index 000000000000..49c310f1f751 --- /dev/null +++ b/tests/ui/traits/const-traits/call-const-in-tilde-const.stderr @@ -0,0 +1,18 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/call-const-in-tilde-const.rs:2:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +error[E0277]: the trait bound `T: const Foo` is not satisfied + --> $DIR/call-const-in-tilde-const.rs:10:13 + | +LL | const { T::foo() } + | ^^^^^^^^ + +error: aborting due to 1 previous error; 1 warning emitted + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/const-bound-in-host.rs b/tests/ui/traits/const-traits/const-bound-in-host.rs new file mode 100644 index 000000000000..6fbc21074b68 --- /dev/null +++ b/tests/ui/traits/const-traits/const-bound-in-host.rs @@ -0,0 +1,15 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Foo { + fn foo(); +} + +fn foo() { + const { T::foo() } +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/const-bound-in-host.stderr b/tests/ui/traits/const-traits/const-bound-in-host.stderr new file mode 100644 index 000000000000..b815f745ee8f --- /dev/null +++ b/tests/ui/traits/const-traits/const-bound-in-host.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/const-bound-in-host.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/const-in-closure.rs b/tests/ui/traits/const-traits/const-in-closure.rs new file mode 100644 index 000000000000..51b22c530361 --- /dev/null +++ b/tests/ui/traits/const-traits/const-in-closure.rs @@ -0,0 +1,25 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Trait { + fn method(); +} + +const fn foo() { + let _ = || { + // Make sure this doesn't enforce `T: ~const Trait` + T::method(); + }; +} + +fn bar() { + let _ = || { + // Make sure unconditionally const bounds propagate from parent. + const { T::method(); }; + }; +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/const-in-closure.stderr b/tests/ui/traits/const-traits/const-in-closure.stderr new file mode 100644 index 000000000000..f4b03b9ed201 --- /dev/null +++ b/tests/ui/traits/const-traits/const-in-closure.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/const-in-closure.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/dont-observe-host-opaque.rs b/tests/ui/traits/const-traits/dont-observe-host-opaque.rs new file mode 100644 index 000000000000..4a5ae346e396 --- /dev/null +++ b/tests/ui/traits/const-traits/dont-observe-host-opaque.rs @@ -0,0 +1,12 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +const fn opaque() -> impl Sized {} + +fn main() { + let mut x = const { opaque() }; + x = opaque(); +} diff --git a/tests/ui/traits/const-traits/dont-observe-host-opaque.stderr b/tests/ui/traits/const-traits/dont-observe-host-opaque.stderr new file mode 100644 index 000000000000..1b457ab76432 --- /dev/null +++ b/tests/ui/traits/const-traits/dont-observe-host-opaque.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/dont-observe-host-opaque.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/dont-observe-host.rs b/tests/ui/traits/const-traits/dont-observe-host.rs new file mode 100644 index 000000000000..d027d578c42f --- /dev/null +++ b/tests/ui/traits/const-traits/dont-observe-host.rs @@ -0,0 +1,23 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] +trait Trait { + fn method() {} +} + +impl const Trait for () {} + +fn main() { + let mut x = const { + let x = <()>::method; + x(); + x + }; + let y = <()>::method; + y(); + x = y; +} diff --git a/tests/ui/traits/const-traits/dont-observe-host.stderr b/tests/ui/traits/const-traits/dont-observe-host.stderr new file mode 100644 index 000000000000..64ef611f011c --- /dev/null +++ b/tests/ui/traits/const-traits/dont-observe-host.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/dont-observe-host.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/fn-ptr-lub.rs b/tests/ui/traits/const-traits/fn-ptr-lub.rs new file mode 100644 index 000000000000..0fc326788270 --- /dev/null +++ b/tests/ui/traits/const-traits/fn-ptr-lub.rs @@ -0,0 +1,20 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +const fn foo() {} +const fn bar() {} +fn baz() {} + +const fn caller(branch: bool) { + let mut x = if branch { + foo + } else { + bar + }; + x = baz; +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/fn-ptr-lub.stderr b/tests/ui/traits/const-traits/fn-ptr-lub.stderr new file mode 100644 index 000000000000..b333311b660e --- /dev/null +++ b/tests/ui/traits/const-traits/fn-ptr-lub.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/fn-ptr-lub.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/item-bound-entailment-fails.rs b/tests/ui/traits/const-traits/item-bound-entailment-fails.rs new file mode 100644 index 000000000000..42799e3700ca --- /dev/null +++ b/tests/ui/traits/const-traits/item-bound-entailment-fails.rs @@ -0,0 +1,31 @@ +//@ compile-flags: -Znext-solver +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Foo { + type Assoc: ~const Bar + where + T: ~const Bar; +} + +#[const_trait] trait Bar {} +struct N(T); +impl Bar for N where T: Bar {} +struct C(T); +impl const Bar for C where T: ~const Bar {} + +impl const Foo for u32 { + type Assoc = N + //~^ ERROR the trait bound `N: ~const Bar` is not satisfied + where + T: ~const Bar; +} + +impl const Foo for i32 { + type Assoc = C + //~^ ERROR the trait bound `T: ~const Bar` is not satisfied + where + T: Bar; +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr b/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr new file mode 100644 index 000000000000..3b3868c4bc84 --- /dev/null +++ b/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr @@ -0,0 +1,36 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/item-bound-entailment-fails.rs:2:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +error[E0277]: the trait bound `N: ~const Bar` is not satisfied + --> $DIR/item-bound-entailment-fails.rs:18:21 + | +LL | type Assoc = N + | ^^^^ + | +note: required by a bound in `Foo::Assoc` + --> $DIR/item-bound-entailment-fails.rs:6:20 + | +LL | type Assoc: ~const Bar + | ^^^^^^^^^^ required by this bound in `Foo::Assoc` + +error[E0277]: the trait bound `T: ~const Bar` is not satisfied + --> $DIR/item-bound-entailment-fails.rs:25:21 + | +LL | type Assoc = C + | ^^^^ + | +note: required by a bound in `Foo::Assoc` + --> $DIR/item-bound-entailment-fails.rs:6:20 + | +LL | type Assoc: ~const Bar + | ^^^^^^^^^^ required by this bound in `Foo::Assoc` + +error: aborting due to 2 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/item-bound-entailment.rs b/tests/ui/traits/const-traits/item-bound-entailment.rs new file mode 100644 index 000000000000..3670eabd66c0 --- /dev/null +++ b/tests/ui/traits/const-traits/item-bound-entailment.rs @@ -0,0 +1,31 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Foo { + type Assoc: ~const Bar + where + T: ~const Bar; +} + +#[const_trait] trait Bar {} +struct N(T); +impl Bar for N where T: Bar {} +struct C(T); +impl const Bar for C where T: ~const Bar {} + +impl Foo for u32 { + type Assoc = N + where + T: Bar; +} + +impl const Foo for i32 { + type Assoc = C + where + T: ~const Bar; +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/item-bound-entailment.stderr b/tests/ui/traits/const-traits/item-bound-entailment.stderr new file mode 100644 index 000000000000..b4a4ebdbee27 --- /dev/null +++ b/tests/ui/traits/const-traits/item-bound-entailment.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/item-bound-entailment.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/predicate-entailment-fails.rs b/tests/ui/traits/const-traits/predicate-entailment-fails.rs new file mode 100644 index 000000000000..5d6109bfad3a --- /dev/null +++ b/tests/ui/traits/const-traits/predicate-entailment-fails.rs @@ -0,0 +1,43 @@ +//@ compile-flags: -Znext-solver +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Bar {} +impl const Bar for () {} + + +#[const_trait] trait TildeConst { + type Bar where T: ~const Bar; + + fn foo() where T: ~const Bar; +} +impl TildeConst for () { + type Bar = () where T: const Bar; + //~^ ERROR impl has stricter requirements than trait + + fn foo() where T: const Bar {} + //~^ ERROR impl has stricter requirements than trait +} + + +#[const_trait] trait NeverConst { + type Bar where T: Bar; + + fn foo() where T: Bar; +} +impl NeverConst for i32 { + type Bar = () where T: const Bar; + //~^ ERROR impl has stricter requirements than trait + + fn foo() where T: const Bar {} + //~^ ERROR impl has stricter requirements than trait +} +impl const NeverConst for u32 { + type Bar = () where T: ~const Bar; + //~^ ERROR impl has stricter requirements than trait + + fn foo() where T: ~const Bar {} + //~^ ERROR impl has stricter requirements than trait +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/predicate-entailment-fails.stderr b/tests/ui/traits/const-traits/predicate-entailment-fails.stderr new file mode 100644 index 000000000000..7cd48ef1d488 --- /dev/null +++ b/tests/ui/traits/const-traits/predicate-entailment-fails.stderr @@ -0,0 +1,66 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/predicate-entailment-fails.rs:2:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +error[E0276]: impl has stricter requirements than trait + --> $DIR/predicate-entailment-fails.rs:15:31 + | +LL | type Bar where T: ~const Bar; + | ----------- definition of `Bar` from trait +... +LL | type Bar = () where T: const Bar; + | ^^^^^^^^^ impl has extra requirement `T: const Bar` + +error[E0276]: impl has stricter requirements than trait + --> $DIR/predicate-entailment-fails.rs:18:26 + | +LL | fn foo() where T: ~const Bar; + | -------------------------------- definition of `foo` from trait +... +LL | fn foo() where T: const Bar {} + | ^^^^^^^^^ impl has extra requirement `T: const Bar` + +error[E0276]: impl has stricter requirements than trait + --> $DIR/predicate-entailment-fails.rs:29:31 + | +LL | type Bar where T: Bar; + | ----------- definition of `Bar` from trait +... +LL | type Bar = () where T: const Bar; + | ^^^^^^^^^ impl has extra requirement `T: const Bar` + +error[E0276]: impl has stricter requirements than trait + --> $DIR/predicate-entailment-fails.rs:32:26 + | +LL | fn foo() where T: Bar; + | ------------------------- definition of `foo` from trait +... +LL | fn foo() where T: const Bar {} + | ^^^^^^^^^ impl has extra requirement `T: const Bar` + +error[E0276]: impl has stricter requirements than trait + --> $DIR/predicate-entailment-fails.rs:36:31 + | +LL | type Bar where T: Bar; + | ----------- definition of `Bar` from trait +... +LL | type Bar = () where T: ~const Bar; + | ^^^^^^^^^^ impl has extra requirement `T: ~const Bar` + +error[E0276]: impl has stricter requirements than trait + --> $DIR/predicate-entailment-fails.rs:39:26 + | +LL | fn foo() where T: Bar; + | ------------------------- definition of `foo` from trait +... +LL | fn foo() where T: ~const Bar {} + | ^^^^^^^^^^ impl has extra requirement `T: ~const Bar` + +error: aborting due to 6 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0276`. diff --git a/tests/ui/traits/const-traits/predicate-entailment-passes.rs b/tests/ui/traits/const-traits/predicate-entailment-passes.rs new file mode 100644 index 000000000000..b660329151be --- /dev/null +++ b/tests/ui/traits/const-traits/predicate-entailment-passes.rs @@ -0,0 +1,39 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +#![feature(const_trait_impl, effects)] +//~^ WARN the feature `effects` is incomplete + +#[const_trait] trait Bar {} +impl const Bar for () {} + + +#[const_trait] trait TildeConst { + type Bar where T: ~const Bar; + + fn foo() where T: ~const Bar; +} +impl TildeConst for () { + type Bar = () where T: Bar; + + fn foo() where T: Bar {} +} + + +#[const_trait] trait AlwaysConst { + type Bar where T: const Bar; + + fn foo() where T: const Bar; +} +impl AlwaysConst for i32 { + type Bar = () where T: Bar; + + fn foo() where T: Bar {} +} +impl const AlwaysConst for u32 { + type Bar = () where T: ~const Bar; + + fn foo() where T: ~const Bar {} +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/predicate-entailment-passes.stderr b/tests/ui/traits/const-traits/predicate-entailment-passes.stderr new file mode 100644 index 000000000000..dcaeea73b580 --- /dev/null +++ b/tests/ui/traits/const-traits/predicate-entailment-passes.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/predicate-entailment-passes.rs:4:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/const-traits/tilde-const-in-struct-args.rs b/tests/ui/traits/const-traits/tilde-const-in-struct-args.rs new file mode 100644 index 000000000000..4722be955e9e --- /dev/null +++ b/tests/ui/traits/const-traits/tilde-const-in-struct-args.rs @@ -0,0 +1,21 @@ +//@ compile-flags: -Znext-solver +//@ known-bug: #132067 +//@ check-pass + +#![feature(const_trait_impl, effects)] + +struct S; +#[const_trait] +trait Trait {} + +const fn f< + T: Trait< + { + struct I>(U); + 0 + }, + >, +>() { +} + +pub fn main() {} diff --git a/tests/ui/traits/const-traits/tilde-const-in-struct-args.stderr b/tests/ui/traits/const-traits/tilde-const-in-struct-args.stderr new file mode 100644 index 000000000000..a9759f10d06b --- /dev/null +++ b/tests/ui/traits/const-traits/tilde-const-in-struct-args.stderr @@ -0,0 +1,11 @@ +warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/tilde-const-in-struct-args.rs:5:30 + | +LL | #![feature(const_trait_impl, effects)] + | ^^^^^^^ + | + = note: see issue #102090 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + From 0f5a47d0884d9d3966f0f4a54e9e9a02cb5f482d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 23 Oct 2024 16:53:59 +0000 Subject: [PATCH 205/366] Be better at enforcing that const_conditions is only called on const items --- compiler/rustc_hir_analysis/src/bounds.rs | 6 +- .../src/check/compare_impl_item.rs | 21 ++--- .../rustc_hir_analysis/src/check/wfcheck.rs | 2 +- .../src/collect/predicates_of.rs | 80 +++++-------------- compiler/rustc_hir_typeck/src/callee.rs | 7 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 18 +++-- compiler/rustc_middle/src/ty/context.rs | 3 +- compiler/rustc_middle/src/ty/mod.rs | 67 +++++++++++++++- compiler/rustc_ty_utils/src/ty.rs | 13 +-- .../derive-const-with-params.stderr | 11 +-- .../effects/spec-effectvar-ice.rs | 2 - .../effects/spec-effectvar-ice.stderr | 16 +--- 12 files changed, 126 insertions(+), 120 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index 7a919bb25005..1121ca532401 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -89,7 +89,11 @@ impl<'tcx> Bounds<'tcx> { host: ty::HostPolarity, span: Span, ) { - self.clauses.push((bound_trait_ref.to_host_effect_clause(tcx, host), span)); + if tcx.is_const_trait(bound_trait_ref.def_id()) { + self.clauses.push((bound_trait_ref.to_host_effect_clause(tcx, host), span)); + } else { + tcx.dcx().span_delayed_bug(span, "tried to lower {host:?} bound for non-const trait"); + } } pub(crate) fn clauses( diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 439e6d784283..02cf1a502f16 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -206,8 +206,8 @@ fn compare_method_predicate_entailment<'tcx>( ); // FIXME(effects): This should be replaced with a more dedicated method. - let check_const_if_const = tcx.constness(impl_def_id) == hir::Constness::Const; - if check_const_if_const { + let is_conditionally_const = tcx.is_conditionally_const(impl_def_id); + if is_conditionally_const { // Augment the hybrid param-env with the const conditions // of the impl header and the trait method. hybrid_preds.extend( @@ -255,7 +255,7 @@ fn compare_method_predicate_entailment<'tcx>( // This registers the `~const` bounds of the impl method, which we will prove // using the hybrid param-env that we earlier augmented with the const conditions // from the impl header and trait method declaration. - if check_const_if_const { + if is_conditionally_const { for (const_condition, span) in tcx.const_conditions(impl_m.def_id).instantiate_own_identity() { @@ -1904,9 +1904,8 @@ fn compare_type_predicate_entailment<'tcx>( let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id); let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity(); - let impl_ty_own_const_conditions = - tcx.const_conditions(impl_ty.def_id).instantiate_own_identity(); - if impl_ty_own_bounds.len() == 0 && impl_ty_own_const_conditions.len() == 0 { + // If there are no bounds, then there are no const conditions, so no need to check that here. + if impl_ty_own_bounds.len() == 0 { // Nothing to check. return Ok(()); } @@ -1931,8 +1930,8 @@ fn compare_type_predicate_entailment<'tcx>( let impl_ty_span = tcx.def_span(impl_ty_def_id); let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id); - let check_const_if_const = tcx.constness(impl_def_id) == hir::Constness::Const; - if check_const_if_const { + let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id); + if is_conditionally_const { // Augment the hybrid param-env with the const conditions // of the impl header and the trait assoc type. hybrid_preds.extend( @@ -1968,8 +1967,10 @@ fn compare_type_predicate_entailment<'tcx>( ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate)); } - if check_const_if_const { + if is_conditionally_const { // Validate the const conditions of the impl associated type. + let impl_ty_own_const_conditions = + tcx.const_conditions(impl_ty.def_id).instantiate_own_identity(); for (const_condition, span) in impl_ty_own_const_conditions { let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id); let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition); @@ -2081,7 +2082,7 @@ pub(super) fn check_type_bounds<'tcx>( .collect(); // Only in a const implementation do we need to check that the `~const` item bounds hold. - if tcx.constness(container_id) == hir::Constness::Const { + if tcx.is_conditionally_const(impl_ty_def_id) { obligations.extend( tcx.implied_const_bounds(trait_ty.def_id) .iter_instantiated_copied(tcx, rebased_args) diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index f0041a577424..499e42d31c97 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1372,7 +1372,7 @@ fn check_impl<'tcx>( } // Ensure that the `~const` where clauses of the trait hold for the impl. - if tcx.constness(item.owner_id.def_id) == hir::Constness::Const { + if tcx.is_conditionally_const(item.owner_id.def_id) { for (bound, _) in tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args) { diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index ec5773d174f8..61dc4b1677c6 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -888,48 +888,8 @@ pub(super) fn const_conditions<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, ) -> ty::ConstConditions<'tcx> { - // This logic is spaghetti, and should be cleaned up. The current methods that are - // defined to deal with constness are very unintuitive. - if tcx.is_const_fn_raw(def_id.to_def_id()) { - // Ok, const fn or method in const trait. - } else { - match tcx.def_kind(def_id) { - DefKind::Trait => { - if !tcx.is_const_trait(def_id.to_def_id()) { - return Default::default(); - } - } - DefKind::Impl { .. } => { - // FIXME(effects): Should be using a dedicated function to - // test if this is a const trait impl. - if tcx.constness(def_id) != hir::Constness::Const { - return Default::default(); - } - } - DefKind::AssocTy | DefKind::AssocFn => { - let parent_def_id = tcx.local_parent(def_id).to_def_id(); - match tcx.associated_item(def_id).container { - ty::AssocItemContainer::TraitContainer => { - if !tcx.is_const_trait(parent_def_id) { - return Default::default(); - } - } - ty::AssocItemContainer::ImplContainer => { - // FIXME(effects): Should be using a dedicated function to - // test if this is a const trait impl. - if tcx.constness(parent_def_id) != hir::Constness::Const { - return Default::default(); - } - } - } - } - DefKind::Closure | DefKind::OpaqueTy => { - // Closures and RPITs will eventually have const conditions - // for `~const` bounds. - return Default::default(); - } - _ => return Default::default(), - } + if !tcx.is_conditionally_const(def_id) { + bug!("const_conditions invoked for item that is not conditionally const: {def_id:?}"); } let (generics, trait_def_id_and_supertraits, has_parent) = match tcx.hir_node_by_def_id(def_id) @@ -940,7 +900,7 @@ pub(super) fn const_conditions<'tcx>( hir::ItemKind::Trait(_, _, generics, supertraits, _) => { (generics, Some((item.owner_id.def_id, supertraits)), false) } - _ => return Default::default(), + _ => bug!("const_conditions called on wrong item: {def_id:?}"), }, // While associated types are not really const, we do allow them to have `~const` // bounds and where clauses. `const_conditions` is responsible for gathering @@ -950,13 +910,21 @@ pub(super) fn const_conditions<'tcx>( hir::TraitItemKind::Fn(_, _) | hir::TraitItemKind::Type(_, _) => { (item.generics, None, true) } - _ => return Default::default(), + _ => bug!("const_conditions called on wrong item: {def_id:?}"), }, Node::ImplItem(item) => match item.kind { - hir::ImplItemKind::Fn(_, _) | hir::ImplItemKind::Type(_) => (item.generics, None, true), - _ => return Default::default(), + hir::ImplItemKind::Fn(_, _) | hir::ImplItemKind::Type(_) => { + (item.generics, None, tcx.is_conditionally_const(tcx.local_parent(def_id))) + } + _ => bug!("const_conditions called on wrong item: {def_id:?}"), }, - _ => return Default::default(), + Node::ForeignItem(item) => match item.kind { + hir::ForeignItemKind::Fn(_, _, generics) => (generics, None, false), + _ => bug!("const_conditions called on wrong item: {def_id:?}"), + }, + // N.B. Tuple ctors are unconditionally constant. + Node::Ctor(hir::VariantData::Tuple { .. }) => return Default::default(), + _ => bug!("const_conditions called on wrong item: {def_id:?}"), }; let icx = ItemCtxt::new(tcx, def_id); @@ -1017,12 +985,12 @@ pub(super) fn implied_const_bounds<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> { + if !tcx.is_conditionally_const(def_id) { + bug!("const_conditions invoked for item that is not conditionally const: {def_id:?}"); + } + let bounds = match tcx.hir_node_by_def_id(def_id) { Node::Item(hir::Item { kind: hir::ItemKind::Trait(..), .. }) => { - if !tcx.is_const_trait(def_id.to_def_id()) { - return ty::EarlyBinder::bind(&[]); - } - implied_predicates_with_filter( tcx, def_id.to_def_id(), @@ -1030,17 +998,9 @@ pub(super) fn implied_const_bounds<'tcx>( ) } Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(..), .. }) => { - if !tcx.is_const_trait(tcx.local_parent(def_id).to_def_id()) { - return ty::EarlyBinder::bind(&[]); - } - explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst) } - Node::OpaqueTy(..) => { - // We should eventually collect the `~const` bounds on opaques. - return ty::EarlyBinder::bind(&[]); - } - _ => return ty::EarlyBinder::bind(&[]), + _ => bug!("implied_const_bounds called on wrong item: {def_id:?}"), }; bounds.map_bound(|bounds| { diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 081cb8c18e65..190e405282c1 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -861,12 +861,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // FIXME(effects): Should this be `is_const_fn_raw`? It depends on if we move // const stability checking here too, I guess. - if self.tcx.is_const_fn(callee_did) - || self - .tcx - .trait_of_item(callee_did) - .is_some_and(|def_id| self.tcx.is_const_trait(def_id)) - { + if self.tcx.is_conditionally_const(callee_did) { let q = self.tcx.const_conditions(callee_did); // FIXME(effects): Use this span with a better cause code. for (cond, _) in q.instantiate(self.tcx, callee_args) { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index a71d1993c6c1..e06c86ae4c03 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1423,7 +1423,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { let g = tcx.generics_of(def_id); record!(self.tables.generics_of[def_id] <- g); record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id)); - record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id)); let inferred_outlives = self.tcx.inferred_outlives_of(def_id); record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives); @@ -1434,6 +1433,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } } + if tcx.is_conditionally_const(def_id) { + record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id)); + } if should_encode_type(tcx, local_id, def_kind) { record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id)); } @@ -1457,11 +1459,13 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.tcx.explicit_super_predicates_of(def_id).skip_binder()); record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <- self.tcx.explicit_implied_predicates_of(def_id).skip_binder()); - record_defaulted_array!(self.tables.implied_const_bounds[def_id] - <- self.tcx.implied_const_bounds(def_id).skip_binder()); let module_children = self.tcx.module_children_local(local_id); record_array!(self.tables.module_children_non_reexports[def_id] <- module_children.iter().map(|child| child.res.def_id().index)); + if self.tcx.is_const_trait(def_id) { + record_defaulted_array!(self.tables.implied_const_bounds[def_id] + <- self.tcx.implied_const_bounds(def_id).skip_binder()); + } } if let DefKind::TraitAlias = def_kind { record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id)); @@ -1469,8 +1473,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.tcx.explicit_super_predicates_of(def_id).skip_binder()); record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <- self.tcx.explicit_implied_predicates_of(def_id).skip_binder()); - record_defaulted_array!(self.tables.implied_const_bounds[def_id] - <- self.tcx.implied_const_bounds(def_id).skip_binder()); } if let DefKind::Trait | DefKind::Impl { .. } = def_kind { let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); @@ -1653,8 +1655,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if let ty::AssocKind::Type = item.kind { self.encode_explicit_item_bounds(def_id); self.encode_explicit_item_super_predicates(def_id); - record_defaulted_array!(self.tables.implied_const_bounds[def_id] - <- self.tcx.implied_const_bounds(def_id).skip_binder()); + if tcx.is_conditionally_const(def_id) { + record_defaulted_array!(self.tables.implied_const_bounds[def_id] + <- self.tcx.implied_const_bounds(def_id).skip_binder()); + } } } AssocItemContainer::ImplContainer => { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index c8fe6cbf4c65..eab106a44039 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -384,7 +384,7 @@ impl<'tcx> Interner for TyCtxt<'tcx> { } fn is_const_impl(self, def_id: DefId) -> bool { - self.constness(def_id) == hir::Constness::Const + self.is_conditionally_const(def_id) } fn const_conditions( @@ -3140,6 +3140,7 @@ impl<'tcx> TyCtxt<'tcx> { } } + // FIXME(effects): Please remove this. It's a footgun. /// Whether the trait impl is marked const. This does not consider stability or feature gates. pub fn is_const_trait_impl_raw(self, def_id: DefId) -> bool { let Some(local_def_id) = def_id.as_local() else { return false }; diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 84e1897019e7..854147648178 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1999,10 +1999,75 @@ impl<'tcx> TyCtxt<'tcx> { pub fn is_const_fn_raw(self, def_id: DefId) -> bool { matches!( self.def_kind(def_id), - DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Closure + DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure ) && self.constness(def_id) == hir::Constness::Const } + /// Whether this item is conditionally constant for the purposes of the + /// effects implementation. + /// + /// This roughly corresponds to all const functions and other callable + /// items, along with const impls and traits, and associated types within + /// those impls and traits. + pub fn is_conditionally_const(self, def_id: impl Into) -> bool { + let def_id: DefId = def_id.into(); + match self.def_kind(def_id) { + DefKind::Impl { of_trait: true } => { + self.constness(def_id) == hir::Constness::Const + && self.is_const_trait( + self.trait_id_of_impl(def_id) + .expect("expected trait for trait implementation"), + ) + } + DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => { + self.constness(def_id) == hir::Constness::Const + } + DefKind::Trait => self.is_const_trait(def_id), + DefKind::AssocTy | DefKind::AssocFn => { + let parent_def_id = self.parent(def_id); + match self.def_kind(parent_def_id) { + DefKind::Impl { of_trait: false } => { + self.constness(def_id) == hir::Constness::Const + } + DefKind::Impl { of_trait: true } | DefKind::Trait => { + self.is_conditionally_const(parent_def_id) + } + _ => bug!("unexpected parent item of associated item: {parent_def_id:?}"), + } + } + DefKind::Closure | DefKind::OpaqueTy => { + // Closures and RPITs will eventually have const conditions + // for `~const` bounds. + false + } + DefKind::Ctor(_, CtorKind::Const) + | DefKind::Impl { of_trait: false } + | DefKind::Mod + | DefKind::Struct + | DefKind::Union + | DefKind::Enum + | DefKind::Variant + | DefKind::TyAlias + | DefKind::ForeignTy + | DefKind::TraitAlias + | DefKind::TyParam + | DefKind::Const + | DefKind::ConstParam + | DefKind::Static { .. } + | DefKind::AssocConst + | DefKind::Macro(_) + | DefKind::ExternCrate + | DefKind::Use + | DefKind::ForeignMod + | DefKind::AnonConst + | DefKind::InlineConst + | DefKind::Field + | DefKind::LifetimeParam + | DefKind::GlobalAsm + | DefKind::SyntheticCoroutineBody => false, + } + } + #[inline] pub fn is_const_trait(self, def_id: DefId) -> bool { self.trait_def(def_id).constness == hir::Constness::Const diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index ac2708a29f4a..aa499995bcb9 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -152,12 +152,13 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> { // We extend the param-env of our item with the const conditions of the item, // since we're allowed to assume `~const` bounds hold within the item itself. - predicates.extend( - tcx.const_conditions(def_id) - .instantiate_identity(tcx) - .into_iter() - .map(|(trait_ref, _)| trait_ref.to_host_effect_clause(tcx, ty::HostPolarity::Maybe)), - ); + if tcx.is_conditionally_const(def_id) { + predicates.extend( + tcx.const_conditions(def_id).instantiate_identity(tcx).into_iter().map( + |(trait_ref, _)| trait_ref.to_host_effect_clause(tcx, ty::HostPolarity::Maybe), + ), + ); + } let local_did = def_id.as_local(); diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr index 3388ee30a5d3..addce8dcd6c7 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr @@ -30,14 +30,5 @@ LL | #[derive_const(PartialEq)] | = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) -error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/derive-const-with-params.rs:7:16 - | -LL | #[derive_const(PartialEq)] - | ^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: aborting due to 4 previous errors; 1 warning emitted +error: aborting due to 3 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs index 73d3e883aad9..d29cd93d3fb7 100644 --- a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs +++ b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.rs @@ -14,9 +14,7 @@ impl const Foo for T {} impl const Foo for T where T: const Specialize {} //~^ error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` //~| error: `const` can only be applied to `#[const_trait]` traits -//~| error: `const` can only be applied to `#[const_trait]` traits //~| error: specialization impl does not specialize any associated items //~| error: cannot specialize on trait `Specialize` -//~| ERROR cannot specialize on predicate fn main() {} diff --git a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr index 2556903150b4..d9655c4995fa 100644 --- a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr +++ b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr @@ -42,14 +42,6 @@ error: `const` can only be applied to `#[const_trait]` traits LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^ -error: `const` can only be applied to `#[const_trait]` traits - --> $DIR/spec-effectvar-ice.rs:14:40 - | -LL | impl const Foo for T where T: const Specialize {} - | ^^^^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - error: specialization impl does not specialize any associated items --> $DIR/spec-effectvar-ice.rs:14:1 | @@ -62,17 +54,11 @@ note: impl is a specialization of this impl LL | impl const Foo for T {} | ^^^^^^^^^^^^^^^^^^^^^^^ -error: cannot specialize on predicate `T: const Specialize` - --> $DIR/spec-effectvar-ice.rs:14:34 - | -LL | impl const Foo for T where T: const Specialize {} - | ^^^^^^^^^^^^^^^^ - error: cannot specialize on trait `Specialize` --> $DIR/spec-effectvar-ice.rs:14:34 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^^^^^^^ -error: aborting due to 8 previous errors; 1 warning emitted +error: aborting due to 6 previous errors; 1 warning emitted From 39881f5720ffcb3d70a667fd58a966f78f739a40 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 24 Oct 2024 11:47:12 +0200 Subject: [PATCH 206/366] Fix diagnostic enable config being ignored --- .../rust-analyzer/crates/rust-analyzer/src/diagnostics.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs index 5f2871ac9922..bcdd045d7000 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs @@ -203,10 +203,12 @@ pub(crate) fn fetch_native_diagnostics( NativeDiagnosticsFetchKind::Syntax => { snapshot.analysis.syntax_diagnostics(config, file_id).ok()? } - NativeDiagnosticsFetchKind::Semantic => snapshot + + NativeDiagnosticsFetchKind::Semantic if config.enabled => snapshot .analysis .semantic_diagnostics(config, ide::AssistResolveStrategy::None, file_id) .ok()?, + NativeDiagnosticsFetchKind::Semantic => return None, }; let diagnostics = diagnostics .into_iter() From 38e9da2068c8fffbfd3eafc78c2be2608e7d2492 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 24 Oct 2024 13:34:32 +0200 Subject: [PATCH 207/366] minor: Remove intermediate allocations --- src/tools/rust-analyzer/crates/hir/src/symbols.rs | 3 +-- src/tools/rust-analyzer/crates/ide-ssr/src/parsing.rs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/symbols.rs b/src/tools/rust-analyzer/crates/hir/src/symbols.rs index cabb7e3db3d9..e2ad0081e3a7 100644 --- a/src/tools/rust-analyzer/crates/hir/src/symbols.rs +++ b/src/tools/rust-analyzer/crates/hir/src/symbols.rs @@ -214,8 +214,7 @@ impl<'a> SymbolCollector<'a> { fn collect_from_impl(&mut self, impl_id: ImplId) { let impl_data = self.db.impl_data(impl_id); - let impl_name = - Some(SmolStr::new(impl_data.self_ty.display(self.db, self.edition).to_string())); + let impl_name = Some(impl_data.self_ty.display(self.db, self.edition).to_smolstr()); self.with_container_name(impl_name, |s| { for &assoc_item_id in impl_data.items.iter() { s.push_assoc_item(assoc_item_id) diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/parsing.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/parsing.rs index e752ee3d775f..ea40d5b815ef 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/parsing.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/parsing.rs @@ -190,7 +190,7 @@ impl RawPattern { let mut res = FxHashMap::default(); for t in &self.tokens { if let PatternElement::Placeholder(placeholder) = t { - res.insert(SmolStr::new(placeholder.stand_in_name.clone()), placeholder.clone()); + res.insert(SmolStr::new(&placeholder.stand_in_name), placeholder.clone()); } } res From e789a77003d1f75e136ed8d9e46a0b9857f3a624 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 24 Oct 2024 13:44:52 +0200 Subject: [PATCH 208/366] internal: Improve proc-macro error msg for failed build scripts --- .../crates/project-model/src/workspace.rs | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs index d1ee579c0d88..d53639e24232 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs @@ -1062,7 +1062,7 @@ fn cargo_to_crate_graph( proc_macros, cargo, pkg_data, - build_data, + build_data.zip(Some(build_scripts.error().is_some())), cfg_options.clone(), file_id, name, @@ -1285,7 +1285,7 @@ fn handle_rustc_crates( proc_macros, rustc_workspace, &rustc_workspace[pkg], - build_scripts.get_output(pkg), + build_scripts.get_output(pkg).zip(Some(build_scripts.error().is_some())), cfg_options.clone(), file_id, &rustc_workspace[tgt].name, @@ -1345,7 +1345,7 @@ fn add_target_crate_root( proc_macros: &mut ProcMacroPaths, cargo: &CargoWorkspace, pkg: &PackageData, - build_data: Option<&BuildScriptOutput>, + build_data: Option<(&BuildScriptOutput, bool)>, cfg_options: CfgOptions, file_id: FileId, cargo_name: &str, @@ -1368,7 +1368,7 @@ fn add_target_crate_root( for feature in pkg.active_features.iter() { opts.insert_key_value(sym::feature.clone(), Symbol::intern(feature)); } - if let Some(cfgs) = build_data.as_ref().map(|it| &it.cfgs) { + if let Some(cfgs) = build_data.map(|(it, _)| &it.cfgs) { opts.extend(cfgs.iter().cloned()); } opts @@ -1379,7 +1379,7 @@ fn add_target_crate_root( inject_cargo_env(&mut env); inject_rustc_tool_env(&mut env, cargo, cargo_name, kind); - if let Some(envs) = build_data.map(|it| &it.envs) { + if let Some(envs) = build_data.map(|(it, _)| &it.envs) { for (k, v) in envs { env.set(k, v.clone()); } @@ -1396,11 +1396,14 @@ fn add_target_crate_root( origin, ); if let TargetKind::Lib { is_proc_macro: true } = kind { - let proc_macro = match build_data.as_ref().map(|it| it.proc_macro_dylib_path.as_ref()) { - Some(it) => match it { - Some(path) => Ok((cargo_name.to_owned(), path.clone())), - None => Err("proc-macro crate build data is missing dylib path".to_owned()), - }, + let proc_macro = match build_data { + Some((BuildScriptOutput { proc_macro_dylib_path, .. }, has_errors)) => { + match proc_macro_dylib_path { + Some(path) => Ok((cargo_name.to_owned(), path.clone())), + None if has_errors => Err("failed to build proc-macro".to_owned()), + None => Err("proc-macro crate build data is missing dylib path".to_owned()), + } + } None => Err("proc-macro crate is missing its build data".to_owned()), }; proc_macros.insert(crate_id, proc_macro); From 0e5c5a25961a94d866a65bb956d5ae9bf7c84eef Mon Sep 17 00:00:00 2001 From: Nick Mathewson Date: Wed, 16 Oct 2024 09:34:34 -0400 Subject: [PATCH 209/366] Document textual format of SocketAddrV{4,6} This commit adds new "Textual representation" documentation sections to SocketAddrV4 and SocketAddrV6, by analogy to the existing "textual representation" sections of Ipv4Addr and Ipv6Addr. Rationale: Without documentation about which formats are actually accepted, it's hard for a programmer to be sure that their code will actually behave as expected when implementing protocols that require support (or rejection) for particular representations. This lack of clarity can in turn can lead to ambiguities and security problems like those discussed in RFC 6942. (I've tried to describe the governing RFCs or standards where I could, but it's possible that the actual implementers had something else in mind. I could not find any standards that corresponded _exactly_ to the one implemented in SocketAddrv6, but I have linked the relevant documents that I could find.) --- library/core/src/net/socket_addr.rs | 39 +++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/library/core/src/net/socket_addr.rs b/library/core/src/net/socket_addr.rs index 4e339172b682..a46495add6a1 100644 --- a/library/core/src/net/socket_addr.rs +++ b/library/core/src/net/socket_addr.rs @@ -49,6 +49,15 @@ pub enum SocketAddr { /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793 /// [`IPv4` address]: Ipv4Addr /// +/// # Textual representation +/// +/// `SocketAddrV4` provides a [`FromStr`](crate::str::FromStr) implementation. +/// It accepts an IPv4 address in its [textual representation], followed by a +/// single `:`, followed by the port encoded as a decimal integer. Other +/// formats are not accepted. +/// +/// [textual representation]: Ipv4Addr#textual-representation +/// /// # Examples /// /// ``` @@ -82,6 +91,32 @@ pub struct SocketAddrV4 { /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3 /// [`IPv6` address]: Ipv6Addr /// +/// # Textual representation +/// +/// `SocketAddrV6` provides a [`FromStr`](crate::str::FromStr) implementation, +/// based on the bracketed format recommended by [IETF RFC 5952], +/// with scope identifiers based on those specified in [IETF RFC 4007]. +/// +/// It accepts addresses consisting of the following elements, in order: +/// - A left square bracket (`[`) +/// - The [textual representation] of an IPv6 address +/// - _Optionally_, a percent sign (`%`) followed by the scope identifier +/// encoded as a decimal integer +/// - A right square bracket (`]`) +/// - A colon (`:`) +/// - The port, encoded as a decimal integer. +/// +/// For example, the string `[2001:db8::413]:443` represents a `SocketAddrV6` +/// with the address `2001:db8::413` and port `443`. The string +/// `[2001:db8::413%612]:443` represents the same address and port, with a +/// scope identifier of `612`. +/// +/// Other formats are not accepted. +/// +/// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952#section-6 +/// [IETF RFC 4007]: https://tools.ietf.org/html/rfc4007#section-11 +/// [textual representation]: Ipv6Addr#textual-representation +/// /// # Examples /// /// ``` @@ -92,6 +127,10 @@ pub struct SocketAddrV4 { /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket)); /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)); /// assert_eq!(socket.port(), 8080); +/// +/// let mut with_scope = socket.clone(); +/// with_scope.set_scope_id(3); +/// assert_eq!("[2001:db8::1%3]:8080".parse(), Ok(with_scope)); /// ``` #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[stable(feature = "rust1", since = "1.0.0")] From 0635916cbe22b96708abe40499d03aef4901ad6a Mon Sep 17 00:00:00 2001 From: maxcabrajac Date: Thu, 24 Oct 2024 10:59:40 -0300 Subject: [PATCH 210/366] Remove visit_expr_post --- compiler/rustc_ast/src/visit.rs | 5 +---- compiler/rustc_lint/src/early.rs | 27 ++++++++++++--------------- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 207ec7106505..57ebab2abdf7 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -173,9 +173,6 @@ pub trait Visitor<'ast>: Sized { fn visit_method_receiver_expr(&mut self, ex: &'ast Expr) -> Self::Result { self.visit_expr(ex) } - fn visit_expr_post(&mut self, _ex: &'ast Expr) -> Self::Result { - Self::Result::output() - } fn visit_ty(&mut self, t: &'ast Ty) -> Self::Result { walk_ty(self, t) } @@ -1185,7 +1182,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) -> V ExprKind::Dummy => {} } - visitor.visit_expr_post(expression) + V::Result::output() } pub fn walk_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a Param) -> V::Result { diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 2285877c9ef2..c095199a4711 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -121,6 +121,18 @@ impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> self.with_lint_attrs(e.id, &e.attrs, |cx| { lint_callback!(cx, check_expr, e); ast_visit::walk_expr(cx, e); + // Explicitly check for lints associated with 'closure_id', since + // it does not have a corresponding AST node + match e.kind { + ast::ExprKind::Closure(box ast::Closure { + coroutine_kind: Some(coroutine_kind), + .. + }) => { + cx.check_id(coroutine_kind.closure_id()); + } + _ => {} + } + lint_callback!(cx, check_expr_post, e); }) } @@ -214,21 +226,6 @@ impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> }) } - fn visit_expr_post(&mut self, e: &'a ast::Expr) { - // Explicitly check for lints associated with 'closure_id', since - // it does not have a corresponding AST node - match e.kind { - ast::ExprKind::Closure(box ast::Closure { - coroutine_kind: Some(coroutine_kind), - .. - }) => { - self.check_id(coroutine_kind.closure_id()); - } - _ => {} - } - lint_callback!(self, check_expr_post, e); - } - fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) { lint_callback!(self, check_generic_arg, arg); ast_visit::walk_generic_arg(self, arg); From 64a34518356426beb5ab8f89c2ef754f3ac03614 Mon Sep 17 00:00:00 2001 From: maxcabrajac Date: Thu, 24 Oct 2024 10:41:44 -0300 Subject: [PATCH 211/366] Pass Ident by reference in ast Visitor --- compiler/rustc_ast/src/visit.rs | 44 +++++++++---------- .../rustc_ast_passes/src/ast_validation.rs | 16 +++---- compiler/rustc_ast_passes/src/node_count.rs | 2 +- .../src/deriving/default.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 4 +- compiler/rustc_lint/src/early.rs | 2 +- compiler/rustc_lint/src/passes.rs | 2 +- .../rustc_resolve/src/build_reduced_graph.rs | 2 +- compiler/rustc_resolve/src/late.rs | 4 +- .../clippy_utils/src/ast_utils/ident_iter.rs | 4 +- 10 files changed, 41 insertions(+), 41 deletions(-) diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 207ec7106505..dd1e9189f2e5 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -135,7 +135,7 @@ pub trait Visitor<'ast>: Sized { /// or `ControlFlow`. type Result: VisitorResult = (); - fn visit_ident(&mut self, _ident: Ident) -> Self::Result { + fn visit_ident(&mut self, _ident: &'ast Ident) -> Self::Result { Self::Result::output() } fn visit_foreign_item(&mut self, i: &'ast ForeignItem) -> Self::Result { @@ -317,12 +317,12 @@ pub fn walk_local<'a, V: Visitor<'a>>(visitor: &mut V, local: &'a Local) -> V::R } pub fn walk_label<'a, V: Visitor<'a>>(visitor: &mut V, Label { ident }: &'a Label) -> V::Result { - visitor.visit_ident(*ident) + visitor.visit_ident(ident) } pub fn walk_lifetime<'a, V: Visitor<'a>>(visitor: &mut V, lifetime: &'a Lifetime) -> V::Result { let Lifetime { id: _, ident } = lifetime; - visitor.visit_ident(*ident) + visitor.visit_ident(ident) } pub fn walk_poly_trait_ref<'a, V>(visitor: &mut V, trait_ref: &'a PolyTraitRef) -> V::Result @@ -429,7 +429,7 @@ impl WalkItemKind for ItemKind { }) => { try_visit!(walk_qself(visitor, qself)); try_visit!(visitor.visit_path(path, *id)); - visit_opt!(visitor, visit_ident, *rename); + visit_opt!(visitor, visit_ident, rename); visit_opt!(visitor, visit_block, body); } ItemKind::DelegationMac(box DelegationMac { qself, prefix, suffixes, body }) => { @@ -437,9 +437,9 @@ impl WalkItemKind for ItemKind { try_visit!(visitor.visit_path(prefix, *id)); if let Some(suffixes) = suffixes { for (ident, rename) in suffixes { - visitor.visit_ident(*ident); + visitor.visit_ident(ident); if let Some(rename) = rename { - visitor.visit_ident(*rename); + visitor.visit_ident(rename); } } } @@ -472,7 +472,7 @@ where let Variant { attrs, id: _, span: _, vis, ident, data, disr_expr, is_placeholder: _ } = variant; walk_list!(visitor, visit_attribute, attrs); try_visit!(visitor.visit_vis(vis)); - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); try_visit!(visitor.visit_variant_data(data)); visit_opt!(visitor, visit_variant_discr, disr_expr); V::Result::output() @@ -481,7 +481,7 @@ where pub fn walk_expr_field<'a, V: Visitor<'a>>(visitor: &mut V, f: &'a ExprField) -> V::Result { let ExprField { attrs, id: _, span: _, ident, expr, is_shorthand: _, is_placeholder: _ } = f; walk_list!(visitor, visit_attribute, attrs); - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); try_visit!(visitor.visit_expr(expr)); V::Result::output() } @@ -489,7 +489,7 @@ pub fn walk_expr_field<'a, V: Visitor<'a>>(visitor: &mut V, f: &'a ExprField) -> pub fn walk_pat_field<'a, V: Visitor<'a>>(visitor: &mut V, fp: &'a PatField) -> V::Result { let PatField { ident, pat, is_shorthand: _, attrs, id: _, span: _, is_placeholder: _ } = fp; walk_list!(visitor, visit_attribute, attrs); - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); try_visit!(visitor.visit_pat(pat)); V::Result::output() } @@ -564,7 +564,7 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>( match kind { UseTreeKind::Simple(rename) => { // The extra IDs are handled during AST lowering. - visit_opt!(visitor, visit_ident, *rename); + visit_opt!(visitor, visit_ident, rename); } UseTreeKind::Glob => {} UseTreeKind::Nested { ref items, span: _ } => { @@ -581,7 +581,7 @@ pub fn walk_path_segment<'a, V: Visitor<'a>>( segment: &'a PathSegment, ) -> V::Result { let PathSegment { ident, id: _, args } = segment; - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); visit_opt!(visitor, visit_generic_args, args); V::Result::output() } @@ -627,7 +627,7 @@ pub fn walk_assoc_item_constraint<'a, V: Visitor<'a>>( constraint: &'a AssocItemConstraint, ) -> V::Result { let AssocItemConstraint { id: _, ident, gen_args, kind, span: _ } = constraint; - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); visit_opt!(visitor, visit_generic_args, gen_args); match kind { AssocItemConstraintKind::Equality { term } => match term { @@ -665,7 +665,7 @@ pub fn walk_pat<'a, V: Visitor<'a>>(visitor: &mut V, pattern: &'a Pat) -> V::Res try_visit!(visitor.visit_pat(subpattern)); } PatKind::Ident(_bmode, ident, optional_subpattern) => { - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); visit_opt!(visitor, visit_pat, optional_subpattern); } PatKind::Lit(expression) => try_visit!(visitor.visit_expr(expression)), @@ -751,7 +751,7 @@ pub fn walk_generic_param<'a, V: Visitor<'a>>( let GenericParam { id: _, ident, attrs, bounds, is_placeholder: _, kind, colon_span: _ } = param; walk_list!(visitor, visit_attribute, attrs); - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); walk_list!(visitor, visit_param_bound, bounds, BoundKind::Bound); match kind { GenericParamKind::Lifetime => (), @@ -889,7 +889,7 @@ impl WalkItemKind for AssocItemKind { }) => { try_visit!(walk_qself(visitor, qself)); try_visit!(visitor.visit_path(path, *id)); - visit_opt!(visitor, visit_ident, *rename); + visit_opt!(visitor, visit_ident, rename); visit_opt!(visitor, visit_block, body); } AssocItemKind::DelegationMac(box DelegationMac { qself, prefix, suffixes, body }) => { @@ -897,9 +897,9 @@ impl WalkItemKind for AssocItemKind { try_visit!(visitor.visit_path(prefix, id)); if let Some(suffixes) = suffixes { for (ident, rename) in suffixes { - visitor.visit_ident(*ident); + visitor.visit_ident(ident); if let Some(rename) = rename { - visitor.visit_ident(*rename); + visitor.visit_ident(rename); } } } @@ -915,7 +915,7 @@ pub fn walk_assoc_item<'a, V: Visitor<'a>>( item: &'a Item, ctxt: AssocCtxt, ) -> V::Result { - let &Item { id: _, span: _, ident, ref vis, ref attrs, ref kind, tokens: _ } = item; + let Item { id: _, span: _, ident, vis, attrs, kind, tokens: _ } = item; walk_list!(visitor, visit_attribute, attrs); try_visit!(visitor.visit_vis(vis)); try_visit!(visitor.visit_ident(ident)); @@ -935,7 +935,7 @@ pub fn walk_field_def<'a, V: Visitor<'a>>(visitor: &mut V, field: &'a FieldDef) let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _ } = field; walk_list!(visitor, visit_attribute, attrs); try_visit!(visitor.visit_vis(vis)); - visit_opt!(visitor, visit_ident, *ident); + visit_opt!(visitor, visit_ident, ident); try_visit!(visitor.visit_ty(ty)); V::Result::output() } @@ -1017,7 +1017,7 @@ pub fn walk_format_args<'a, V: Visitor<'a>>(visitor: &mut V, fmt: &'a FormatArgs for FormatArgument { kind, expr } in arguments.all_args() { match kind { FormatArgumentKind::Named(ident) | FormatArgumentKind::Captured(ident) => { - try_visit!(visitor.visit_ident(*ident)) + try_visit!(visitor.visit_ident(ident)) } FormatArgumentKind::Normal => {} } @@ -1137,7 +1137,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) -> V } ExprKind::Field(subexpression, ident) => { try_visit!(visitor.visit_expr(subexpression)); - try_visit!(visitor.visit_ident(*ident)); + try_visit!(visitor.visit_ident(ident)); } ExprKind::Index(main_expression, index_expression, _span) => { try_visit!(visitor.visit_expr(main_expression)); @@ -1172,7 +1172,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) -> V ExprKind::FormatArgs(f) => try_visit!(visitor.visit_format_args(f)), ExprKind::OffsetOf(container, fields) => { try_visit!(visitor.visit_ty(container)); - walk_list!(visitor, visit_ident, fields.iter().copied()); + walk_list!(visitor, visit_ident, fields.iter()); } ExprKind::Yield(optional_expression) => { visit_opt!(visitor, visit_expr, optional_expression); diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index bf6ebfb160bc..1d149e91b851 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -249,7 +249,7 @@ impl<'a> AstValidator<'a> { } fn visit_struct_field_def(&mut self, field: &'a FieldDef) { - if let Some(ident) = field.ident + if let Some(ref ident) = field.ident && ident.name == kw::Underscore { self.visit_vis(&field.vis); @@ -899,7 +899,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } this.visit_vis(&item.vis); - this.visit_ident(item.ident); + this.visit_ident(&item.ident); let disallowed = matches!(constness, Const::No) .then(|| TildeConstReason::TraitImpl { span: item.span }); this.with_tilde_const(disallowed, |this| this.visit_generics(generics)); @@ -953,7 +953,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } this.visit_vis(&item.vis); - this.visit_ident(item.ident); + this.visit_ident(&item.ident); this.with_tilde_const( Some(TildeConstReason::Impl { span: item.span }), |this| this.visit_generics(generics), @@ -991,7 +991,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } self.visit_vis(&item.vis); - self.visit_ident(item.ident); + self.visit_ident(&item.ident); let kind = FnKind::Fn(FnCtxt::Free, item.ident, sig, &item.vis, generics, body.as_deref()); self.visit_fn(kind, item.span, item.id); @@ -1058,7 +1058,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound // context for the supertraits. this.visit_vis(&item.vis); - this.visit_ident(item.ident); + this.visit_ident(&item.ident); let disallowed = is_const_trait .is_none() .then(|| TildeConstReason::Trait { span: item.span }); @@ -1085,7 +1085,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ItemKind::Struct(vdata, generics) => match vdata { VariantData::Struct { fields, .. } => { self.visit_vis(&item.vis); - self.visit_ident(item.ident); + self.visit_ident(&item.ident); self.visit_generics(generics); // Permit `Anon{Struct,Union}` as field type. walk_list!(self, visit_struct_field_def, fields); @@ -1101,7 +1101,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { match vdata { VariantData::Struct { fields, .. } => { self.visit_vis(&item.vis); - self.visit_ident(item.ident); + self.visit_ident(&item.ident); self.visit_generics(generics); // Permit `Anon{Struct,Union}` as field type. walk_list!(self, visit_struct_field_def, fields); @@ -1521,7 +1521,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { || matches!(sig.header.constness, Const::Yes(_)) => { self.visit_vis(&item.vis); - self.visit_ident(item.ident); + self.visit_ident(&item.ident); let kind = FnKind::Fn( FnCtxt::Assoc(ctxt), item.ident, diff --git a/compiler/rustc_ast_passes/src/node_count.rs b/compiler/rustc_ast_passes/src/node_count.rs index e22e99f6e4d6..9e7204df8adf 100644 --- a/compiler/rustc_ast_passes/src/node_count.rs +++ b/compiler/rustc_ast_passes/src/node_count.rs @@ -16,7 +16,7 @@ impl NodeCounter { } impl<'ast> Visitor<'ast> for NodeCounter { - fn visit_ident(&mut self, _ident: Ident) { + fn visit_ident(&mut self, _ident: &Ident) { self.count += 1; } fn visit_foreign_item(&mut self, i: &ForeignItem) { diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index 652e6f7740f9..d4befd12190b 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -222,7 +222,7 @@ impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonVariantDefaultAttr<'a, ' rustc_ast::visit::walk_attribute(self, attr); } fn visit_variant(&mut self, v: &'a rustc_ast::Variant) { - self.visit_ident(v.ident); + self.visit_ident(&v.ident); self.visit_vis(&v.vis); self.visit_variant_data(&v.data); visit_opt!(self, visit_anon_const, &v.disr_expr); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 5c5cd99345ef..fcc8064dfe7f 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1892,11 +1892,11 @@ impl EarlyLintPass for KeywordIdents { fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { self.check_tokens(cx, &mac.args.tokens); } - fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) { + fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) { if ident.name.as_str().starts_with('\'') { self.check_ident_token(cx, UnderMacro(false), ident.without_first_quote(), "'"); } else { - self.check_ident_token(cx, UnderMacro(false), ident, ""); + self.check_ident_token(cx, UnderMacro(false), *ident, ""); } } } diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 2285877c9ef2..faf3cf1482c1 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -190,7 +190,7 @@ impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> ast_visit::walk_ty(self, t); } - fn visit_ident(&mut self, ident: Ident) { + fn visit_ident(&mut self, ident: &Ident) { lint_callback!(self, check_ident, ident); } diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index a1d436e0d3db..75ae994a86bd 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -133,7 +133,7 @@ macro_rules! early_lint_methods { ($macro:path, $args:tt) => ( $macro!($args, [ fn check_param(a: &rustc_ast::Param); - fn check_ident(a: rustc_span::symbol::Ident); + fn check_ident(a: &rustc_span::symbol::Ident); fn check_crate(a: &rustc_ast::Crate); fn check_crate_post(a: &rustc_ast::Crate); fn check_item(a: &rustc_ast::Item); diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 0ca6bb8c07d9..031ffaed808b 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -1321,7 +1321,7 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> { // Visit attributes after items for backward compatibility. // This way they can use `macro_rules` defined later. self.visit_vis(&item.vis); - self.visit_ident(item.ident); + self.visit_ident(&item.ident); item.kind.walk(item, AssocCtxt::Trait, self); visit::walk_list!(self, visit_attribute, &item.attrs); } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 033cd7d58705..adb0ba7c8203 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1205,7 +1205,7 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r } fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) { - self.visit_ident(constraint.ident); + self.visit_ident(&constraint.ident); if let Some(ref gen_args) = constraint.gen_args { // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided. self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| { @@ -4582,7 +4582,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) { self.resolve_expr(&f.expr, Some(e)); - self.visit_ident(f.ident); + self.visit_ident(&f.ident); walk_list!(self, visit_attribute, f.attrs.iter()); } diff --git a/src/tools/clippy/clippy_utils/src/ast_utils/ident_iter.rs b/src/tools/clippy/clippy_utils/src/ast_utils/ident_iter.rs index 032cd3ed7399..22b2c895f7c5 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils/ident_iter.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils/ident_iter.rs @@ -39,7 +39,7 @@ impl From<&Attribute> for IdentIter { struct IdentCollector(Vec); impl Visitor<'_> for IdentCollector { - fn visit_ident(&mut self, ident: Ident) { - self.0.push(ident); + fn visit_ident(&mut self, ident: &Ident) { + self.0.push(*ident); } } From c5a1bd93428a75a58707cc00c55e231d4d93e599 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 24 Oct 2024 16:22:12 +0200 Subject: [PATCH 212/366] feat: Implement diagnostics pull model --- .../crates/rust-analyzer/src/diagnostics.rs | 34 +++++----- .../rust-analyzer/src/handlers/dispatch.rs | 24 +++++++ .../rust-analyzer/src/handlers/request.rs | 66 ++++++++++++++++++- .../rust-analyzer/src/lsp/capabilities.rs | 19 +++++- .../crates/rust-analyzer/src/main_loop.rs | 25 ++++++- 5 files changed, 150 insertions(+), 18 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs index 5f2871ac9922..eab07589f56d 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs @@ -173,21 +173,6 @@ pub(crate) fn fetch_native_diagnostics( let _p = tracing::info_span!("fetch_native_diagnostics").entered(); let _ctx = stdx::panic_context::enter("fetch_native_diagnostics".to_owned()); - let convert_diagnostic = - |line_index: &crate::line_index::LineIndex, d: ide::Diagnostic| lsp_types::Diagnostic { - range: lsp::to_proto::range(line_index, d.range.range), - severity: Some(lsp::to_proto::diagnostic_severity(d.severity)), - code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_owned())), - code_description: Some(lsp_types::CodeDescription { - href: lsp_types::Url::parse(&d.code.url()).unwrap(), - }), - source: Some("rust-analyzer".to_owned()), - message: d.message, - related_information: None, - tags: d.unused.then(|| vec![lsp_types::DiagnosticTag::UNNECESSARY]), - data: None, - }; - // the diagnostics produced may point to different files not requested by the concrete request, // put those into here and filter later let mut odd_ones = Vec::new(); @@ -246,3 +231,22 @@ pub(crate) fn fetch_native_diagnostics( } diagnostics } + +pub(crate) fn convert_diagnostic( + line_index: &crate::line_index::LineIndex, + d: ide::Diagnostic, +) -> lsp_types::Diagnostic { + lsp_types::Diagnostic { + range: lsp::to_proto::range(line_index, d.range.range), + severity: Some(lsp::to_proto::diagnostic_severity(d.severity)), + code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_owned())), + code_description: Some(lsp_types::CodeDescription { + href: lsp_types::Url::parse(&d.code.url()).unwrap(), + }), + source: Some("rust-analyzer".to_owned()), + message: d.message, + related_information: None, + tags: d.unused.then(|| vec![lsp_types::DiagnosticTag::UNNECESSARY]), + data: None, + } +} diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs index ed7bf27843b5..21f95a945d9a 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs @@ -120,6 +120,30 @@ impl RequestDispatcher<'_> { self.on_with_thread_intent::(ThreadIntent::Worker, f) } + /// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not + /// ready this will return a default constructed [`R::Result`]. + pub(crate) fn on_or( + &mut self, + f: fn(GlobalStateSnapshot, R::Params) -> anyhow::Result, + default: impl FnOnce() -> R::Result, + ) -> &mut Self + where + R: lsp_types::request::Request< + Params: DeserializeOwned + panic::UnwindSafe + Send + fmt::Debug, + Result: Serialize, + > + 'static, + { + if !self.global_state.vfs_done { + if let Some(lsp_server::Request { id, .. }) = + self.req.take_if(|it| it.method == R::METHOD) + { + self.global_state.respond(lsp_server::Response::new_ok(id, default())); + } + return self; + } + self.on_with_thread_intent::(ThreadIntent::Worker, f) + } + /// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not /// ready this will return the parameter as is. pub(crate) fn on_identity( diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs index 5b4b678c0c6e..35c61a336e7a 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs @@ -4,6 +4,7 @@ use std::{ fs, io::Write as _, + ops::Not, process::{self, Stdio}, }; @@ -14,7 +15,7 @@ use ide::{ FilePosition, FileRange, HoverAction, HoverGotoTypeData, InlayFieldsToResolve, Query, RangeInfo, ReferenceCategory, Runnable, RunnableKind, SingleResolve, SourceChange, TextEdit, }; -use ide_db::SymbolKind; +use ide_db::{FxHashMap, SymbolKind}; use itertools::Itertools; use lsp_server::ErrorCode; use lsp_types::{ @@ -36,6 +37,7 @@ use vfs::{AbsPath, AbsPathBuf, FileId, VfsPath}; use crate::{ config::{Config, RustfmtConfig, WorkspaceSymbolConfig}, + diagnostics::convert_diagnostic, global_state::{FetchWorkspaceRequest, GlobalState, GlobalStateSnapshot}, hack_recover_crate_name, line_index::LineEndings, @@ -473,6 +475,68 @@ pub(crate) fn handle_on_type_formatting( Ok(Some(change)) } +pub(crate) fn handle_document_diagnostics( + snap: GlobalStateSnapshot, + params: lsp_types::DocumentDiagnosticParams, +) -> anyhow::Result { + let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?; + let source_root = snap.analysis.source_root_id(file_id)?; + let line_index = snap.file_line_index(file_id)?; + let config = snap.config.diagnostics(Some(source_root)); + if !config.enabled { + return Ok(lsp_types::DocumentDiagnosticReportResult::Report( + lsp_types::DocumentDiagnosticReport::Full( + lsp_types::RelatedFullDocumentDiagnosticReport { + related_documents: None, + full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport { + result_id: None, + items: vec![], + }, + }, + ), + )); + } + let supports_related = snap.config.text_document_diagnostic_related_document_support(); + + let mut related_documents = FxHashMap::default(); + let diagnostics = snap + .analysis + .full_diagnostics(&config, AssistResolveStrategy::None, file_id)? + .into_iter() + .filter_map(|d| { + let file = d.range.file_id; + let diagnostic = convert_diagnostic(&line_index, d); + if file == file_id { + return Some(diagnostic); + } + if supports_related { + related_documents.entry(file).or_insert_with(Vec::new).push(diagnostic); + } + None + }); + Ok(lsp_types::DocumentDiagnosticReportResult::Report( + lsp_types::DocumentDiagnosticReport::Full(lsp_types::RelatedFullDocumentDiagnosticReport { + full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport { + result_id: None, + items: diagnostics.collect(), + }, + related_documents: related_documents.is_empty().not().then(|| { + related_documents + .into_iter() + .map(|(id, items)| { + ( + to_proto::url(&snap, id), + lsp_types::DocumentDiagnosticReportKind::Full( + lsp_types::FullDocumentDiagnosticReport { result_id: None, items }, + ), + ) + }) + .collect() + }), + }), + )) +} + pub(crate) fn handle_document_symbol( snap: GlobalStateSnapshot, params: lsp_types::DocumentSymbolParams, diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs index 939593dd4533..271a9c0f3d12 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/lsp/capabilities.rs @@ -155,7 +155,15 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities { "ssr": true, "workspaceSymbolScopeKindFiltering": true, })), - diagnostic_provider: None, + diagnostic_provider: Some(lsp_types::DiagnosticServerCapabilities::Options( + lsp_types::DiagnosticOptions { + identifier: None, + inter_file_dependencies: true, + // FIXME + workspace_diagnostics: false, + work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None }, + }, + )), inline_completion_provider: None, } } @@ -380,6 +388,15 @@ impl ClientCapabilities { .unwrap_or_default() } + pub fn text_document_diagnostic(&self) -> bool { + (|| -> _ { self.0.text_document.as_ref()?.diagnostic.as_ref() })().is_some() + } + + pub fn text_document_diagnostic_related_document_support(&self) -> bool { + (|| -> _ { self.0.text_document.as_ref()?.diagnostic.as_ref()?.related_document_support })() + == Some(true) + } + pub fn code_action_group(&self) -> bool { self.experimental_bool("codeActionGroup") } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index 20be38a9e4be..c531cd8d114e 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -417,6 +417,8 @@ impl GlobalState { } } + let supports_diagnostic_pull_model = self.config.text_document_diagnostic(); + let client_refresh = became_quiescent || state_changed; if client_refresh { // Refresh semantic tokens if the client supports it. @@ -434,11 +436,21 @@ impl GlobalState { if self.config.inlay_hints_refresh() { self.send_request::((), |_, _| ()); } + + if supports_diagnostic_pull_model { + self.send_request::( + (), + |_, _| (), + ); + } } let project_or_mem_docs_changed = became_quiescent || state_changed || memdocs_added_or_removed; - if project_or_mem_docs_changed && self.config.publish_diagnostics(None) { + if project_or_mem_docs_changed + && !supports_diagnostic_pull_model + && self.config.publish_diagnostics(None) + { self.update_diagnostics(); } if project_or_mem_docs_changed && self.config.test_explorer() { @@ -1080,6 +1092,17 @@ impl GlobalState { .on_latency_sensitive::(handlers::handle_semantic_tokens_range) // FIXME: Some of these NO_RETRY could be retries if the file they are interested didn't change. // All other request handlers + .on_or::(handlers::handle_document_diagnostics, || lsp_types::DocumentDiagnosticReportResult::Report( + lsp_types::DocumentDiagnosticReport::Full( + lsp_types::RelatedFullDocumentDiagnosticReport { + related_documents: None, + full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport { + result_id: None, + items: vec![], + }, + }, + ), + )) .on::(handlers::handle_document_symbol) .on::(handlers::handle_folding_range) .on::(handlers::handle_signature_help) From 105961ecb4ad32d0694f298aa7794d1f0797f7d9 Mon Sep 17 00:00:00 2001 From: David Wood Date: Fri, 27 Sep 2024 13:56:41 +0100 Subject: [PATCH 213/366] ci: add aarch64-gnu-debug job Adds a new CI job which checks that the compiler builds with `--enable-debug` and tests that `needs-force-clang-based-tests` pass (where cross-language LTO is tested). --- .../host-aarch64/aarch64-gnu-debug/Dockerfile | 58 +++++++++++++++++++ src/ci/github-actions/jobs.yml | 3 + tests/run-make/cross-lang-lto-clang/rmake.rs | 26 +++++++-- 3 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile diff --git a/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile b/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile new file mode 100644 index 000000000000..dcfea77149ed --- /dev/null +++ b/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile @@ -0,0 +1,58 @@ +FROM ubuntu:22.04 + +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++ \ + make \ + ninja-build \ + file \ + curl \ + ca-certificates \ + python3 \ + python3-dev \ + libxml2-dev \ + libncurses-dev \ + libedit-dev \ + swig \ + doxygen \ + git \ + cmake \ + sudo \ + gdb \ + libssl-dev \ + pkg-config \ + xz-utils \ + lld \ + clang \ + && rm -rf /var/lib/apt/lists/* + +COPY scripts/sccache.sh /scripts/ +RUN sh /scripts/sccache.sh + +ENV RUSTBUILD_FORCE_CLANG_BASED_TESTS 1 +ENV RUN_CHECK_WITH_PARALLEL_QUERIES 1 + +# llvm.use-linker conflicts with downloading CI LLVM +ENV NO_DOWNLOAD_CI_LLVM 1 + +ENV RUST_CONFIGURE_ARGS \ + --build=aarch64-unknown-linux-gnu \ + --enable-debug \ + --enable-lld \ + --set llvm.use-linker=lld \ + --set target.aarch64-unknown-linux-gnu.linker=clang \ + --set target.aarch64-unknown-linux-gnu.cc=clang \ + --set target.aarch64-unknown-linux-gnu.cxx=clang++ + +# This job appears to be checking two separate things: +# - That we can build the compiler with `--enable-debug` +# (without necessarily testing the result). +# - That the tests with `//@ needs-force-clang-based-tests` pass, since they +# don't run by default unless RUSTBUILD_FORCE_CLANG_BASED_TESTS is set. +# - FIXME(https://github.com/rust-lang/rust/pull/126155#issuecomment-2156314273): +# Currently we only run the subset of tests with "clang" in their name. +# - See also FIXME(#132034) + +ENV SCRIPT \ + python3 ../x.py --stage 2 build && \ + python3 ../x.py --stage 2 test tests/run-make --test-args clang diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index 2b6366040490..6b6a3806666a 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -123,6 +123,9 @@ auto: - image: aarch64-gnu <<: *job-aarch64-linux + - image: aarch64-gnu-debug + <<: *job-aarch64-linux + - image: arm-android <<: *job-linux-4c diff --git a/tests/run-make/cross-lang-lto-clang/rmake.rs b/tests/run-make/cross-lang-lto-clang/rmake.rs index 1b15a54aacb0..3fed6ea20667 100644 --- a/tests/run-make/cross-lang-lto-clang/rmake.rs +++ b/tests/run-make/cross-lang-lto-clang/rmake.rs @@ -9,6 +9,24 @@ use run_make_support::{clang, env_var, llvm_ar, llvm_objdump, rustc, static_lib_name}; +#[cfg(any(target_arch = "aarch64", target_arch = "arm"))] +static RUST_ALWAYS_INLINED_PATTERN: &'static str = "bl.*"; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +static RUST_ALWAYS_INLINED_PATTERN: &'static str = "call.*rust_always_inlined"; +#[cfg(any(target_arch = "aarch64", target_arch = "arm"))] +static C_ALWAYS_INLINED_PATTERN: &'static str = "bl.*"; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +static C_ALWAYS_INLINED_PATTERN: &'static str = "call.*c_always_inlined"; + +#[cfg(any(target_arch = "aarch64", target_arch = "arm"))] +static RUST_NEVER_INLINED_PATTERN: &'static str = "bl.*"; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +static RUST_NEVER_INLINED_PATTERN: &'static str = "call.*rust_never_inlined"; +#[cfg(any(target_arch = "aarch64", target_arch = "arm"))] +static C_NEVER_INLINED_PATTERN: &'static str = "bl.*"; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +static C_NEVER_INLINED_PATTERN: &'static str = "call.*c_never_inlined"; + fn main() { rustc() .linker_plugin_lto("on") @@ -31,14 +49,14 @@ fn main() { .disassemble() .input("cmain") .run() - .assert_stdout_not_contains_regex("call.*rust_always_inlined"); + .assert_stdout_not_contains_regex(RUST_ALWAYS_INLINED_PATTERN); // As a sanity check, make sure we do find a call instruction to a // non-inlined function llvm_objdump() .disassemble() .input("cmain") .run() - .assert_stdout_contains_regex("call.*rust_never_inlined"); + .assert_stdout_contains_regex(RUST_NEVER_INLINED_PATTERN); clang().input("clib.c").lto("thin").arg("-c").out_exe("clib.o").arg("-O2").run(); llvm_ar().obj_to_ar().output_input(static_lib_name("xyz"), "clib.o").run(); rustc() @@ -53,10 +71,10 @@ fn main() { .disassemble() .input("rsmain") .run() - .assert_stdout_not_contains_regex("call.*c_always_inlined"); + .assert_stdout_not_contains_regex(C_ALWAYS_INLINED_PATTERN); llvm_objdump() .disassemble() .input("rsmain") .run() - .assert_stdout_contains_regex("call.*c_never_inlined"); + .assert_stdout_contains_regex(C_NEVER_INLINED_PATTERN); } From 352b505f800855a2c1829ffcd51e1f6bd5aad0ac Mon Sep 17 00:00:00 2001 From: David Wood Date: Fri, 27 Sep 2024 13:57:49 +0100 Subject: [PATCH 214/366] tests: add pac-ret + cross-language lto test Add a test confirming that `-Zbranch-protection=pac-ret` and cross-language LTO work together. --- .../rmake.rs | 36 +++++++++++++++++++ .../pointer-auth-link-with-c-lto-clang/test.c | 1 + .../test.rs | 10 ++++++ 3 files changed, 47 insertions(+) create mode 100644 tests/run-make/pointer-auth-link-with-c-lto-clang/rmake.rs create mode 100644 tests/run-make/pointer-auth-link-with-c-lto-clang/test.c create mode 100644 tests/run-make/pointer-auth-link-with-c-lto-clang/test.rs diff --git a/tests/run-make/pointer-auth-link-with-c-lto-clang/rmake.rs b/tests/run-make/pointer-auth-link-with-c-lto-clang/rmake.rs new file mode 100644 index 000000000000..cf6e3d863772 --- /dev/null +++ b/tests/run-make/pointer-auth-link-with-c-lto-clang/rmake.rs @@ -0,0 +1,36 @@ +// `-Z branch protection` is an unstable compiler feature which adds pointer-authentication +// code (PAC), a useful hashing measure for verifying that pointers have not been modified. +// This test checks that compilation and execution is successful when this feature is activated, +// with some of its possible extra arguments (bti, pac-ret, leaf) when doing LTO. +// See https://github.com/rust-lang/rust/pull/88354 + +//@ needs-force-clang-based-tests +//@ only-aarch64 +// Reason: branch protection is not supported on other architectures +//@ ignore-cross-compile +// Reason: the compiled binary is executed + +use run_make_support::{clang, env_var, llvm_ar, run, rustc, static_lib_name}; + +fn main() { + clang() + .arg("-v") + .lto("thin") + .arg("-mbranch-protection=bti+pac-ret+leaf") + .arg("-O2") + .arg("-c") + .out_exe("test.o") + .input("test.c") + .run(); + llvm_ar().obj_to_ar().output_input(static_lib_name("test"), "test.o").run(); + rustc() + .linker_plugin_lto("on") + .opt_level("2") + .linker(&env_var("CLANG")) + .link_arg("-fuse-ld=lld") + .arg("-Zbranch-protection=bti,pac-ret,leaf") + .input("test.rs") + .output("test.bin") + .run(); + run("test.bin"); +} diff --git a/tests/run-make/pointer-auth-link-with-c-lto-clang/test.c b/tests/run-make/pointer-auth-link-with-c-lto-clang/test.c new file mode 100644 index 000000000000..9fe07f82f9ed --- /dev/null +++ b/tests/run-make/pointer-auth-link-with-c-lto-clang/test.c @@ -0,0 +1 @@ +int foo() { return 0; } diff --git a/tests/run-make/pointer-auth-link-with-c-lto-clang/test.rs b/tests/run-make/pointer-auth-link-with-c-lto-clang/test.rs new file mode 100644 index 000000000000..1a3be80e898b --- /dev/null +++ b/tests/run-make/pointer-auth-link-with-c-lto-clang/test.rs @@ -0,0 +1,10 @@ +#[link(name = "test")] +extern "C" { + fn foo() -> i32; +} + +fn main() { + unsafe { + foo(); + } +} From 689101f8a3ea26f70902b10ab99b9860f565d9dc Mon Sep 17 00:00:00 2001 From: Laiho Date: Thu, 24 Oct 2024 19:08:41 +0300 Subject: [PATCH 215/366] provide default impl for as_utf8_pattern --- library/core/src/str/pattern.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index eb60effe8138..f68465c9bdac 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -162,7 +162,9 @@ pub trait Pattern: Sized { } /// Returns the pattern as utf-8 bytes if possible. - fn as_utf8_pattern(&self) -> Option>; + fn as_utf8_pattern(&self) -> Option> { + None + } } /// Result of calling [`Pattern::as_utf8_pattern()`]. /// Can be used for inspecting the contents of a [`Pattern`] in cases @@ -675,11 +677,6 @@ impl Pattern for MultiCharEqPattern { fn into_searcher(self, haystack: &str) -> MultiCharEqSearcher<'_, C> { MultiCharEqSearcher { haystack, char_eq: self.0, char_indices: haystack.char_indices() } } - - #[inline] - fn as_utf8_pattern(&self) -> Option> { - None - } } unsafe impl<'a, C: MultiCharEq> Searcher<'a> for MultiCharEqSearcher<'a, C> { @@ -770,11 +767,6 @@ macro_rules! pattern_methods { { ($pmap)(self).strip_suffix_of(haystack) } - - #[inline] - fn as_utf8_pattern(&self) -> Option> { - None - } }; } From 4e487689085ba8b490fbf735163250cc4edb05ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tau=20G=C3=A4rtli?= Date: Thu, 24 Oct 2024 18:50:55 +0200 Subject: [PATCH 216/366] rustdoc: Extend fake_variadic to "wrapped" tuples MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This allows impls such as `impl QueryData for OneOf<(T,)>` to be displayed as variadic: `impl QueryData for OneOf<(T₁, T₂, …, Tₙ)>`. See question on zulip: --- compiler/rustc_passes/src/check_attr.rs | 24 +++++++++++++++++------ src/librustdoc/html/format.rs | 18 +++++++++++++++++ tests/rustdoc/primitive-tuple-variadic.rs | 19 ++++++++++++++++++ 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 61e196bdebe6..62c502f95242 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -918,12 +918,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { }; match item_kind { Some(ItemKind::Impl(i)) => { - let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_])) - || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind { - bare_fn_ty.decl.inputs.len() == 1 - } else { - false - } + let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty) || if let Some(&[hir::GenericArg::Type(ty)]) = i .of_trait .as_ref() @@ -2630,3 +2625,20 @@ fn check_duplicates( }, } } + +fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool { + matches!(&self_ty.kind, hir::TyKind::Tup([_])) + || if let hir::TyKind::BareFn(bare_fn_ty) = &self_ty.kind { + bare_fn_ty.decl.inputs.len() == 1 + } else { + false + } + || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind + && let Some(&[hir::GenericArg::Type(ty)]) = + path.segments.last().map(|last| last.args().args) + { + doc_fake_variadic_is_allowed_self_ty(ty) + } else { + false + }) +} diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 5c599f20f9fd..ea2f930ab837 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1368,6 +1368,24 @@ impl clean::Impl { write!(f, " -> ")?; fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?; } + } else if let clean::Type::Path { path } = type_ + && let Some(generics) = path.generics() + && generics.len() == 1 + && self.kind.is_fake_variadic() + { + let ty = generics[0]; + let wrapper = anchor(path.def_id(), path.last(), cx); + if f.alternate() { + write!(f, "{wrapper:#}<")?; + } else { + write!(f, "{wrapper}<")?; + } + self.print_type(ty, f, use_absolute, cx)?; + if f.alternate() { + write!(f, ">")?; + } else { + write!(f, ">")?; + } } else { fmt_type(&type_, f, use_absolute, cx)?; } diff --git a/tests/rustdoc/primitive-tuple-variadic.rs b/tests/rustdoc/primitive-tuple-variadic.rs index b15e996f929a..d142729d2a8b 100644 --- a/tests/rustdoc/primitive-tuple-variadic.rs +++ b/tests/rustdoc/primitive-tuple-variadic.rs @@ -33,3 +33,22 @@ impl Baz<[T; 1]> for (T,) {} //@ has - '//section[@id="impl-Baz%3CT%3E-for-(T,)"]/h3' 'impl Baz for (T₁, T₂, …, Tₙ)' #[doc(fake_variadic)] impl Baz for (T,) {} + +pub trait Qux {} + +pub struct NewType(T); + +//@ has foo/trait.Qux.html +//@ has - '//section[@id="impl-Qux-for-NewType%3C(T,)%3E"]/h3' 'impl Qux for NewType<(T₁, T₂, …, Tₙ)>' +#[doc(fake_variadic)] +impl Qux for NewType<(T,)> {} + +//@ has foo/trait.Qux.html +//@ has - '//section[@id="impl-Qux-for-NewType%3CNewType%3C(T,)%3E%3E"]/h3' 'impl Qux for NewType>' +#[doc(fake_variadic)] +impl Qux for NewType> {} + +//@ has foo/trait.Qux.html +//@ has - '//section[@id="impl-Qux-for-NewType%3Cfn(T)+-%3E+Out%3E"]/h3' 'impl Qux for NewType Out>' +#[doc(fake_variadic)] +impl Qux for NewType Out> {} From 9832131fd54432f70166ac91f847ef21e6f11002 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Thu, 24 Oct 2024 20:29:07 +0300 Subject: [PATCH 217/366] Update changelog generation for merge queues --- src/tools/rust-analyzer/xtask/src/release/changelog.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/xtask/src/release/changelog.rs b/src/tools/rust-analyzer/xtask/src/release/changelog.rs index 086a4d463ea1..343a9efbbc81 100644 --- a/src/tools/rust-analyzer/xtask/src/release/changelog.rs +++ b/src/tools/rust-analyzer/xtask/src/release/changelog.rs @@ -128,9 +128,10 @@ fn unescape(s: &str) -> String { } fn parse_pr_number(s: &str) -> Option { - const BORS_PREFIX: &str = "Merge #"; + const GITHUB_PREFIX: &str = "Merge pull request #"; const HOMU_PREFIX: &str = "Auto merge of #"; - if let Some(s) = s.strip_prefix(BORS_PREFIX) { + if let Some(s) = s.strip_prefix(GITHUB_PREFIX) { + let s = if let Some(space) = s.find(' ') { &s[..space] } else { s }; s.parse().ok() } else if let Some(s) = s.strip_prefix(HOMU_PREFIX) { if let Some(space) = s.find(' ') { From 0e0a84ae4e656fda2becd9ba33428fff613b44cb Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 24 Oct 2024 15:02:58 +0200 Subject: [PATCH 218/366] Do not consider nested functions as `main` function even if named `main` in doctests --- src/librustdoc/doctest/make.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/doctest/make.rs b/src/librustdoc/doctest/make.rs index efbb332d12d8..3ae60938749e 100644 --- a/src/librustdoc/doctest/make.rs +++ b/src/librustdoc/doctest/make.rs @@ -289,7 +289,12 @@ fn parse_source( // Recurse through functions body. It is necessary because the doctest source code is // wrapped in a function to limit the number of AST errors. If we don't recurse into // functions, we would thing all top-level items (so basically nothing). - fn check_item(item: &ast::Item, info: &mut ParseSourceInfo, crate_name: &Option<&str>) { + fn check_item( + item: &ast::Item, + info: &mut ParseSourceInfo, + crate_name: &Option<&str>, + is_top_level: bool, + ) { if !info.has_global_allocator && item.attrs.iter().any(|attr| attr.name_or_empty() == sym::global_allocator) { @@ -297,13 +302,15 @@ fn parse_source( } match item.kind { ast::ItemKind::Fn(ref fn_item) if !info.has_main_fn => { - if item.ident.name == sym::main { + if item.ident.name == sym::main && is_top_level { info.has_main_fn = true; } if let Some(ref body) = fn_item.body { for stmt in &body.stmts { match stmt.kind { - ast::StmtKind::Item(ref item) => check_item(item, info, crate_name), + ast::StmtKind::Item(ref item) => { + check_item(item, info, crate_name, false) + } ast::StmtKind::MacCall(..) => info.found_macro = true, _ => {} } @@ -329,7 +336,7 @@ fn parse_source( loop { match parser.parse_item(ForceCollect::No) { Ok(Some(item)) => { - check_item(&item, info, crate_name); + check_item(&item, info, crate_name, true); if info.has_main_fn && info.found_extern_crate { break; From aab2b6747db09b8572f879bd74dbee701287536d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 24 Oct 2024 15:05:39 +0200 Subject: [PATCH 219/366] Add regression test for #131893 --- tests/rustdoc-ui/doctest/nested-main.rs | 24 +++++++++++++++++++++ tests/rustdoc-ui/doctest/nested-main.stdout | 7 ++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/rustdoc-ui/doctest/nested-main.rs create mode 100644 tests/rustdoc-ui/doctest/nested-main.stdout diff --git a/tests/rustdoc-ui/doctest/nested-main.rs b/tests/rustdoc-ui/doctest/nested-main.rs new file mode 100644 index 000000000000..e939ba81214c --- /dev/null +++ b/tests/rustdoc-ui/doctest/nested-main.rs @@ -0,0 +1,24 @@ +//@ check-pass +//@ compile-flags:--test --test-args=--test-threads=1 +//@ normalize-stdout-test: "tests/rustdoc-ui/doctest" -> "$$DIR" +//@ normalize-stdout-test: "finished in \d+\.\d+s" -> "finished in $$TIME" + +// Regression test for . +// It ensures that if a function called `main` is nested, it will not consider +// it as the `main` function. + +/// ``` +/// fn dox() { +/// fn main() {} +/// } +/// ``` +pub fn foo() {} + +// This one ensures that having a nested `main` doesn't prevent the +// actual `main` function to be detected. +/// ``` +/// fn main() { +/// fn main() {} +/// } +/// ``` +pub fn foo2() {} diff --git a/tests/rustdoc-ui/doctest/nested-main.stdout b/tests/rustdoc-ui/doctest/nested-main.stdout new file mode 100644 index 000000000000..af9a8f5e1d76 --- /dev/null +++ b/tests/rustdoc-ui/doctest/nested-main.stdout @@ -0,0 +1,7 @@ + +running 2 tests +test $DIR/nested-main.rs - foo (line 10) ... ok +test $DIR/nested-main.rs - foo2 (line 19) ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME + From 5368b120a1742893460c515bb198342d6f0a3800 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Thu, 24 Oct 2024 17:50:19 +0900 Subject: [PATCH 220/366] Avoid use imports in thread_local_inner! in statik Fixes #131863 for wasm targets All other macros were done in #131866, but this sub module is missed. --- library/std/src/sys/thread_local/statik.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/library/std/src/sys/thread_local/statik.rs b/library/std/src/sys/thread_local/statik.rs index ba94caa66902..4da01a84acf6 100644 --- a/library/std/src/sys/thread_local/statik.rs +++ b/library/std/src/sys/thread_local/statik.rs @@ -14,12 +14,11 @@ pub macro thread_local_inner { (@key $t:ty, const $init:expr) => {{ const __INIT: $t = $init; + // NOTE: Please update the shadowing test in `tests/thread.rs` if these types are renamed. unsafe { - use $crate::thread::LocalKey; - use $crate::thread::local_impl::EagerStorage; - - LocalKey::new(|_| { - static VAL: EagerStorage<$t> = EagerStorage { value: __INIT }; + $crate::thread::LocalKey::new(|_| { + static VAL: $crate::thread::local_impl::EagerStorage<$t> = + $crate::thread::local_impl::EagerStorage { value: __INIT }; &VAL.value }) } From f1114babebd82125bdcf6dfc8013563f32585def Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Thu, 24 Oct 2024 16:12:31 -0700 Subject: [PATCH 221/366] Apply suggestions from code review Co-authored-by: Michael Goulet --- compiler/stable_mir/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/stable_mir/README.md b/compiler/stable_mir/README.md index 89f610e110e7..5e37369e93c6 100644 --- a/compiler/stable_mir/README.md +++ b/compiler/stable_mir/README.md @@ -5,8 +5,8 @@ Until then, users will use this as any other rustc crate, via extern crate. ## Stable MIR Design -The stable-mir will follow a similar approach to proc-macro2. It’s -implementation is done using two main crates: +The stable-mir will follow a similar approach to proc-macro2. Its +implementation is split between two main crates: - `stable_mir`: Public crate, to be published on crates.io, which will contain the stable data structure as well as calls to `rustc_smir` APIs and From aa2f9681dbf7fc4ffcf5d4ecaa99fd3741d2ee33 Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Thu, 24 Oct 2024 16:19:55 -0700 Subject: [PATCH 222/366] Update README.md Clarify that the translation between unstable and stable items is currently done in the `rustc_smir` crate. --- compiler/stable_mir/README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/compiler/stable_mir/README.md b/compiler/stable_mir/README.md index 5e37369e93c6..ab2546e377ae 100644 --- a/compiler/stable_mir/README.md +++ b/compiler/stable_mir/README.md @@ -1,7 +1,11 @@ This crate is currently developed in-tree together with the compiler. Our goal is to start publishing `stable_mir` into crates.io. -Until then, users will use this as any other rustc crate, via extern crate. +Until then, users will use this as any other rustc crate, by installing +the rustup component `rustc-dev`, and declaring `stable-mir` as an external crate. + +See the StableMIR ["Getting Started"](https://rust-lang.github.io/project-stable-mir/getting-started.html) +guide for more information. ## Stable MIR Design @@ -9,12 +13,16 @@ The stable-mir will follow a similar approach to proc-macro2. Its implementation is split between two main crates: - `stable_mir`: Public crate, to be published on crates.io, which will contain -the stable data structure as well as calls to `rustc_smir` APIs and -translation between stable and internal constructs. +the stable data structure as well as calls to `rustc_smir` APIs. The +translation between stable and internal constructs will also be done in this crate, +however, this is currently implemented in the `rustc_smir` crate.[^translation]. - `rustc_smir`: This crate implements the public APIs to the compiler. It is responsible for gathering all the information requested, and providing the data in its unstable form. +[^translation]: This is currently implemented in the `rustc_smir` crate, +but we are working to change that. + I.e., tools will depend on `stable_mir` crate, which will invoke the compiler using APIs defined in `rustc_smir`. From 3bad5014c92686bc0e9914b03eb00e4855e48d99 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 22 Oct 2024 00:00:50 +0000 Subject: [PATCH 223/366] Add support for ~const item bounds --- .../src/solve/assembly/mod.rs | 11 ++++ .../src/solve/effect_goals.rs | 51 ++++++++++++++++++- .../src/solve/normalizes_to/mod.rs | 8 +++ .../src/solve/trait_goals.rs | 8 +++ .../assoc-type-const-bound-usage-0.rs | 2 +- .../assoc-type-const-bound-usage-0.stderr | 15 ------ .../assoc-type-const-bound-usage-1.stderr | 28 +++++++--- .../assoc-type-const-bound-usage-fail-2.rs | 35 +++++++++++++ ...assoc-type-const-bound-usage-fail-2.stderr | 15 ++++++ .../assoc-type-const-bound-usage-fail.rs | 28 ++++++++++ .../assoc-type-const-bound-usage-fail.stderr | 15 ++++++ 11 files changed, 191 insertions(+), 25 deletions(-) delete mode 100644 tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr create mode 100644 tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.rs create mode 100644 tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.stderr create mode 100644 tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.rs create mode 100644 tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.stderr diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index 5e604a5d74f5..f6a5f20a639e 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -100,6 +100,15 @@ where }) } + /// Assemble additional assumptions for an alias that are not included + /// in the item bounds of the alias. For now, this is limited to the + /// `implied_const_bounds` for an associated type. + fn consider_additional_alias_assumptions( + ecx: &mut EvalCtxt<'_, D>, + goal: Goal, + alias_ty: ty::AliasTy, + ) -> Vec>; + fn consider_impl_candidate( ecx: &mut EvalCtxt<'_, D>, goal: Goal, @@ -594,6 +603,8 @@ where )); } + candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty)); + if kind != ty::Projection { return; } diff --git a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs index 62b4bb0004ca..8d57ad8f2551 100644 --- a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs @@ -3,7 +3,7 @@ use rustc_type_ir::fast_reject::DeepRejectCtxt; use rustc_type_ir::inherent::*; -use rustc_type_ir::{self as ty, Interner}; +use rustc_type_ir::{self as ty, Interner, elaborate}; use tracing::instrument; use super::assembly::Candidate; @@ -70,6 +70,55 @@ where } } + /// Register additional assumptions for aliases corresponding to `~const` item bounds. + /// + /// Unlike item bounds, they are not simply implied by the well-formedness of the alias. + /// Instead, they only hold if the const conditons on the alias also hold. This is why + /// we also register the const conditions of the alias after matching the goal against + /// the assumption. + fn consider_additional_alias_assumptions( + ecx: &mut EvalCtxt<'_, D>, + goal: Goal, + alias_ty: ty::AliasTy, + ) -> Vec> { + let cx = ecx.cx(); + let mut candidates = vec![]; + + // FIXME(effects): We elaborate here because the implied const bounds + // aren't necessarily elaborated. We probably should prefix this query + // with `explicit_`... + for clause in elaborate::elaborate( + cx, + cx.implied_const_bounds(alias_ty.def_id) + .iter_instantiated(cx, alias_ty.args) + .map(|trait_ref| trait_ref.to_host_effect_clause(cx, goal.predicate.host)), + ) { + candidates.extend(Self::probe_and_match_goal_against_assumption( + ecx, + CandidateSource::AliasBound, + goal, + clause, + |ecx| { + // Const conditions must hold for the implied const bound to hold. + ecx.add_goals( + GoalSource::Misc, + cx.const_conditions(alias_ty.def_id) + .iter_instantiated(cx, alias_ty.args) + .map(|trait_ref| { + goal.with( + cx, + trait_ref.to_host_effect_clause(cx, goal.predicate.host), + ) + }), + ); + ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + }, + )); + } + + candidates + } + fn consider_impl_candidate( ecx: &mut EvalCtxt<'_, D>, goal: Goal, diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index c98fd8535514..7287cdf74bf4 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -193,6 +193,14 @@ where } } + fn consider_additional_alias_assumptions( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + _alias_ty: ty::AliasTy, + ) -> Vec> { + vec![] + } + fn consider_impl_candidate( ecx: &mut EvalCtxt<'_, D>, goal: Goal>, diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 6b26f960286f..08cc89d950e2 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -39,6 +39,14 @@ where self.def_id() } + fn consider_additional_alias_assumptions( + _ecx: &mut EvalCtxt<'_, D>, + _goal: Goal, + _alias_ty: ty::AliasTy, + ) -> Vec> { + vec![] + } + fn consider_impl_candidate( ecx: &mut EvalCtxt<'_, D>, goal: Goal>, diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs index 5a54e8eec91f..bbf889179051 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.rs @@ -1,5 +1,5 @@ //@ compile-flags: -Znext-solver -//@ known-bug: unknown +//@ check-pass #![allow(incomplete_features)] #![feature(const_trait_impl, effects)] diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr deleted file mode 100644 index 35069a5a52fc..000000000000 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-0.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0271]: type mismatch resolving `::Assoc == T` - --> $DIR/assoc-type-const-bound-usage-0.rs:14:5 - | -LL | T::Assoc::func() - | ^^^^^^^^^^^^^^^^ types differ - -error[E0271]: type mismatch resolving `::Assoc == T` - --> $DIR/assoc-type-const-bound-usage-0.rs:18:5 - | -LL | ::Assoc::func() - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr index ed9182c73342..b8768bd5541c 100644 --- a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-1.stderr @@ -6,18 +6,30 @@ LL | #![feature(const_trait_impl, effects, generic_const_exprs)] | = help: remove one of these features -error[E0271]: type mismatch resolving `::Assoc == T` - --> $DIR/assoc-type-const-bound-usage-1.rs:15:44 +error[E0284]: type annotations needed: cannot normalize `unqualified::{constant#0}` + --> $DIR/assoc-type-const-bound-usage-1.rs:15:37 | LL | fn unqualified() -> Type<{ T::Assoc::func() }> { - | ^^^^^^^^^^^^^^^^ types differ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot normalize `unqualified::{constant#0}` -error[E0271]: type mismatch resolving `::Assoc == T` - --> $DIR/assoc-type-const-bound-usage-1.rs:19:42 +error[E0284]: type annotations needed: cannot normalize `qualified::{constant#0}` + --> $DIR/assoc-type-const-bound-usage-1.rs:19:35 | LL | fn qualified() -> Type<{ ::Assoc::func() }> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot normalize `qualified::{constant#0}` -error: aborting due to 3 previous errors +error[E0284]: type annotations needed: cannot normalize `unqualified::{constant#0}` + --> $DIR/assoc-type-const-bound-usage-1.rs:16:5 + | +LL | Type + | ^^^^ cannot normalize `unqualified::{constant#0}` -For more information about this error, try `rustc --explain E0271`. +error[E0284]: type annotations needed: cannot normalize `qualified::{constant#0}` + --> $DIR/assoc-type-const-bound-usage-1.rs:20:5 + | +LL | Type + | ^^^^ cannot normalize `qualified::{constant#0}` + +error: aborting due to 5 previous errors + +For more information about this error, try `rustc --explain E0284`. diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.rs new file mode 100644 index 000000000000..5e873082781b --- /dev/null +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.rs @@ -0,0 +1,35 @@ +//@ compile-flags: -Znext-solver + +// Check that `~const` item bounds only hold if the where clauses on the +// associated type are also const. +// i.e. check that we validate the const conditions for the associated type +// when considering one of implied const bounds. + +#![allow(incomplete_features)] +#![feature(const_trait_impl, effects)] + +#[const_trait] +trait Trait { + type Assoc: ~const Trait + where + U: ~const Other; + + fn func(); +} + +#[const_trait] +trait Other {} + +const fn fails() { + T::Assoc::::func(); + //~^ ERROR the trait bound `::Assoc: ~const Trait` is not satisfied + ::Assoc::::func(); + //~^ ERROR the trait bound `::Assoc: ~const Trait` is not satisfied +} + +const fn works() { + T::Assoc::::func(); + ::Assoc::::func(); +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.stderr new file mode 100644 index 000000000000..1f6532c7a570 --- /dev/null +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail-2.stderr @@ -0,0 +1,15 @@ +error[E0277]: the trait bound `::Assoc: ~const Trait` is not satisfied + --> $DIR/assoc-type-const-bound-usage-fail-2.rs:24:5 + | +LL | T::Assoc::::func(); + | ^^^^^^^^^^^^^^^^^^^^^ + +error[E0277]: the trait bound `::Assoc: ~const Trait` is not satisfied + --> $DIR/assoc-type-const-bound-usage-fail-2.rs:26:5 + | +LL | ::Assoc::::func(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.rs b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.rs new file mode 100644 index 000000000000..73b3d142f7c8 --- /dev/null +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.rs @@ -0,0 +1,28 @@ +//@ compile-flags: -Znext-solver + +// Check that `~const` item bounds only hold if the parent trait is `~const`. +// i.e. check that we validate the const conditions for the associated type +// when considering one of implied const bounds. + +#![allow(incomplete_features)] +#![feature(const_trait_impl, effects)] + +#[const_trait] +trait Trait { + type Assoc: ~const Trait; + fn func(); +} + +const fn unqualified() { + T::Assoc::func(); + //~^ ERROR the trait bound `T: ~const Trait` is not satisfied + ::Assoc::func(); + //~^ ERROR the trait bound `T: ~const Trait` is not satisfied +} + +const fn works() { + T::Assoc::func(); + ::Assoc::func(); +} + +fn main() {} diff --git a/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.stderr b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.stderr new file mode 100644 index 000000000000..fb08e74eb7f4 --- /dev/null +++ b/tests/ui/traits/const-traits/assoc-type-const-bound-usage-fail.stderr @@ -0,0 +1,15 @@ +error[E0277]: the trait bound `T: ~const Trait` is not satisfied + --> $DIR/assoc-type-const-bound-usage-fail.rs:17:5 + | +LL | T::Assoc::func(); + | ^^^^^^^^^^^^^^^^ + +error[E0277]: the trait bound `T: ~const Trait` is not satisfied + --> $DIR/assoc-type-const-bound-usage-fail.rs:19:5 + | +LL | ::Assoc::func(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. From 9f8a6be22188b1ac666bae83fc6aaf7f84ba4522 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 24 Oct 2024 22:47:45 +1100 Subject: [PATCH 224/366] coverage: Consolidate creation of covmap/covfun records There is no need for this code to be split across multiple functions in multiple files. --- .../src/coverageinfo/mapgen.rs | 83 ++++++++++++++----- .../src/coverageinfo/mod.rs | 69 +-------------- 2 files changed, 64 insertions(+), 88 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 61e474031bb0..b69ca6234134 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -1,7 +1,10 @@ -use std::ffi::CStr; +use std::ffi::{CStr, CString}; use itertools::Itertools as _; -use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods}; +use rustc_abi::Align; +use rustc_codegen_ssa::traits::{ + BaseTypeCodegenMethods, ConstCodegenMethods, StaticCodegenMethods, +}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_index::IndexVec; @@ -10,6 +13,7 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, mir}; use rustc_span::Symbol; use rustc_span::def_id::DefIdSet; +use rustc_target::spec::HasTargetSpec; use tracing::debug; use crate::common::CodegenCx; @@ -78,8 +82,7 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { // Generate the coverage map header, which contains the filenames used by // this CGU's coverage mappings, and store it in a well-known global. - let cov_data_val = generate_coverage_map(cx, covmap_version, filenames_size, filenames_val); - coverageinfo::save_cov_data_to_mod(cx, cov_data_val); + generate_covmap_record(cx, covmap_version, filenames_size, filenames_val); let mut unused_function_names = Vec::new(); let covfun_section_name = coverageinfo::covfun_section_name(cx); @@ -111,7 +114,7 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { unused_function_names.push(mangled_function_name); } - save_function_record( + generate_covfun_record( cx, &covfun_section_name, mangled_function_name, @@ -308,15 +311,15 @@ fn encode_mappings_for_function( }) } -/// Construct coverage map header and the array of function records, and combine them into the -/// coverage map. Save the coverage map data into the LLVM IR as a static global using a -/// specific, well-known section and name. -fn generate_coverage_map<'ll>( +/// Generates the contents of the covmap record for this CGU, which mostly +/// consists of a header and a list of filenames. The record is then stored +/// as a global variable in the `__llvm_covmap` section. +fn generate_covmap_record<'ll>( cx: &CodegenCx<'ll, '_>, version: u32, filenames_size: usize, filenames_val: &'ll llvm::Value, -) -> &'ll llvm::Value { +) { debug!("cov map: filenames_size = {}, 0-based version = {}", filenames_size, version); // Create the coverage data header (Note, fields 0 and 2 are now always zero, @@ -331,13 +334,35 @@ fn generate_coverage_map<'ll>( ); // Create the complete LLVM coverage data value to add to the LLVM IR - cx.const_struct(&[cov_data_header_val, filenames_val], /*packed=*/ false) + let covmap_data = + cx.const_struct(&[cov_data_header_val, filenames_val], /*packed=*/ false); + + let covmap_var_name = CString::new(llvm::build_byte_buffer(|s| unsafe { + llvm::LLVMRustCoverageWriteMappingVarNameToString(s); + })) + .unwrap(); + debug!("covmap var name: {:?}", covmap_var_name); + + let covmap_section_name = CString::new(llvm::build_byte_buffer(|s| unsafe { + llvm::LLVMRustCoverageWriteMapSectionNameToString(cx.llmod, s); + })) + .expect("covmap section name should not contain NUL"); + debug!("covmap section name: {:?}", covmap_section_name); + + let llglobal = llvm::add_global(cx.llmod, cx.val_ty(covmap_data), &covmap_var_name); + llvm::set_initializer(llglobal, covmap_data); + llvm::set_global_constant(llglobal, true); + llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); + llvm::set_section(llglobal, &covmap_section_name); + // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. + llvm::set_alignment(llglobal, Align::EIGHT); + cx.add_used_global(llglobal); } -/// Construct a function record and combine it with the function's coverage mapping data. -/// Save the function record into the LLVM IR as a static global using a -/// specific, well-known section and name. -fn save_function_record( +/// Generates the contents of the covfun record for this function, which +/// contains the function's coverage mapping data. The record is then stored +/// as a global variable in the `__llvm_covfun` section. +fn generate_covfun_record( cx: &CodegenCx<'_, '_>, covfun_section_name: &CStr, mangled_function_name: &str, @@ -366,13 +391,27 @@ fn save_function_record( /*packed=*/ true, ); - coverageinfo::save_func_record_to_mod( - cx, - covfun_section_name, - func_name_hash, - func_record_val, - is_used, - ); + // Choose a variable name to hold this function's covfun data. + // Functions that are used have a suffix ("u") to distinguish them from + // unused copies of the same function (from different CGUs), so that if a + // linker sees both it won't discard the used copy's data. + let func_record_var_name = + CString::new(format!("__covrec_{:X}{}", func_name_hash, if is_used { "u" } else { "" })) + .unwrap(); + debug!("function record var name: {:?}", func_record_var_name); + + let llglobal = llvm::add_global(cx.llmod, cx.val_ty(func_record_val), &func_record_var_name); + llvm::set_initializer(llglobal, func_record_val); + llvm::set_global_constant(llglobal, true); + llvm::set_linkage(llglobal, llvm::Linkage::LinkOnceODRLinkage); + llvm::set_visibility(llglobal, llvm::Visibility::Hidden); + llvm::set_section(llglobal, covfun_section_name); + // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. + llvm::set_alignment(llglobal, Align::EIGHT); + if cx.target_spec().supports_comdat() { + llvm::set_comdat(cx.llmod, llglobal, &func_record_var_name); + } + cx.add_used_global(llglobal); } /// Each CGU will normally only emit coverage metadata for the functions that it actually generates. diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index b2956945911b..58607ce7497f 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -1,10 +1,9 @@ use std::cell::RefCell; -use std::ffi::{CStr, CString}; +use std::ffi::CString; use libc::c_uint; use rustc_codegen_ssa::traits::{ - BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, CoverageInfoBuilderMethods, - MiscCodegenMethods, StaticCodegenMethods, + BuilderMethods, ConstCodegenMethods, CoverageInfoBuilderMethods, MiscCodegenMethods, }; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_llvm::RustString; @@ -12,8 +11,7 @@ use rustc_middle::bug; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::ty::Instance; use rustc_middle::ty::layout::HasTyCtxt; -use rustc_target::abi::{Align, Size}; -use rustc_target::spec::HasTargetSpec; +use rustc_target::abi::Size; use tracing::{debug, instrument}; use crate::builder::Builder; @@ -290,67 +288,6 @@ pub(crate) fn mapping_version() -> u32 { unsafe { llvm::LLVMRustCoverageMappingVersion() } } -pub(crate) fn save_cov_data_to_mod<'ll, 'tcx>( - cx: &CodegenCx<'ll, 'tcx>, - cov_data_val: &'ll llvm::Value, -) { - let covmap_var_name = CString::new(llvm::build_byte_buffer(|s| unsafe { - llvm::LLVMRustCoverageWriteMappingVarNameToString(s); - })) - .unwrap(); - debug!("covmap var name: {:?}", covmap_var_name); - - let covmap_section_name = CString::new(llvm::build_byte_buffer(|s| unsafe { - llvm::LLVMRustCoverageWriteMapSectionNameToString(cx.llmod, s); - })) - .expect("covmap section name should not contain NUL"); - debug!("covmap section name: {:?}", covmap_section_name); - - let llglobal = llvm::add_global(cx.llmod, cx.val_ty(cov_data_val), &covmap_var_name); - llvm::set_initializer(llglobal, cov_data_val); - llvm::set_global_constant(llglobal, true); - llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); - llvm::set_section(llglobal, &covmap_section_name); - // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. - llvm::set_alignment(llglobal, Align::EIGHT); - cx.add_used_global(llglobal); -} - -pub(crate) fn save_func_record_to_mod<'ll, 'tcx>( - cx: &CodegenCx<'ll, 'tcx>, - covfun_section_name: &CStr, - func_name_hash: u64, - func_record_val: &'ll llvm::Value, - is_used: bool, -) { - // Assign a name to the function record. This is used to merge duplicates. - // - // In LLVM, a "translation unit" (effectively, a `Crate` in Rust) can describe functions that - // are included-but-not-used. If (or when) Rust generates functions that are - // included-but-not-used, note that a dummy description for a function included-but-not-used - // in a Crate can be replaced by full description provided by a different Crate. The two kinds - // of descriptions play distinct roles in LLVM IR; therefore, assign them different names (by - // appending "u" to the end of the function record var name, to prevent `linkonce_odr` merging. - let func_record_var_name = - CString::new(format!("__covrec_{:X}{}", func_name_hash, if is_used { "u" } else { "" })) - .unwrap(); - debug!("function record var name: {:?}", func_record_var_name); - debug!("function record section name: {:?}", covfun_section_name); - - let llglobal = llvm::add_global(cx.llmod, cx.val_ty(func_record_val), &func_record_var_name); - llvm::set_initializer(llglobal, func_record_val); - llvm::set_global_constant(llglobal, true); - llvm::set_linkage(llglobal, llvm::Linkage::LinkOnceODRLinkage); - llvm::set_visibility(llglobal, llvm::Visibility::Hidden); - llvm::set_section(llglobal, covfun_section_name); - // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. - llvm::set_alignment(llglobal, Align::EIGHT); - if cx.target_spec().supports_comdat() { - llvm::set_comdat(cx.llmod, llglobal, &func_record_var_name); - } - cx.add_used_global(llglobal); -} - /// Returns the section name string to pass through to the linker when embedding /// per-function coverage information in the object file, according to the target /// platform's object file format. From 0a96176533ad5c0f8dc3b42c64bf907fb9c27f0b Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 24 Oct 2024 22:23:13 +1100 Subject: [PATCH 225/366] coverage: Make obtaining the codegen coverage context infallible In all the situations where this context is needed, it should always be available. --- compiler/rustc_codegen_llvm/src/context.rs | 8 ++--- .../src/coverageinfo/mapgen.rs | 12 ++------ .../src/coverageinfo/mod.rs | 29 +++++++------------ 3 files changed, 16 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 2f830d6f941e..7faa005abd29 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -80,6 +80,7 @@ pub(crate) struct CodegenCx<'ll, 'tcx> { pub isize_ty: &'ll Type, + /// Extra codegen state needed when coverage instrumentation is enabled. pub coverage_cx: Option>, pub dbg_cx: Option>, @@ -592,11 +593,10 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { &self.statics_to_rauw } + /// Extra state that is only available when coverage instrumentation is enabled. #[inline] - pub(crate) fn coverage_context( - &self, - ) -> Option<&coverageinfo::CrateCoverageContext<'ll, 'tcx>> { - self.coverage_cx.as_ref() + pub(crate) fn coverage_cx(&self) -> &coverageinfo::CrateCoverageContext<'ll, 'tcx> { + self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled") } pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) { diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index b69ca6234134..7a2a802eb4eb 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -54,11 +54,7 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { add_unused_functions(cx); } - let function_coverage_map = match cx.coverage_context() { - Some(ctx) => ctx.take_function_coverage_map(), - None => return, - }; - + let function_coverage_map = cx.coverage_cx().take_function_coverage_map(); if function_coverage_map.is_empty() { // This module has no functions with coverage instrumentation return; @@ -543,9 +539,5 @@ fn add_unused_function_coverage<'tcx>( // zero, because none of its counters/expressions are marked as seen. let function_coverage = FunctionCoverageCollector::unused(instance, function_coverage_info); - if let Some(coverage_context) = cx.coverage_context() { - coverage_context.function_coverage_map.borrow_mut().insert(instance, function_coverage); - } else { - bug!("Could not get the `coverage_context`"); - } + cx.coverage_cx().function_coverage_map.borrow_mut().insert(instance, function_coverage); } diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index 58607ce7497f..eaf720cc769e 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -7,7 +7,6 @@ use rustc_codegen_ssa::traits::{ }; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_llvm::RustString; -use rustc_middle::bug; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::ty::Instance; use rustc_middle::ty::layout::HasTyCtxt; @@ -76,15 +75,11 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// `instrprof.increment()`. The `Value` is only created once per instance. /// Multiple invocations with the same instance return the same `Value`. fn get_pgo_func_name_var(&self, instance: Instance<'tcx>) -> &'ll llvm::Value { - if let Some(coverage_context) = self.coverage_context() { - debug!("getting pgo_func_name_var for instance={:?}", instance); - let mut pgo_func_name_var_map = coverage_context.pgo_func_name_var_map.borrow_mut(); - pgo_func_name_var_map - .entry(instance) - .or_insert_with(|| create_pgo_func_name_var(self, instance)) - } else { - bug!("Could not get the `coverage_context`"); - } + debug!("getting pgo_func_name_var for instance={:?}", instance); + let mut pgo_func_name_var_map = self.coverage_cx().pgo_func_name_var_map.borrow_mut(); + pgo_func_name_var_map + .entry(instance) + .or_insert_with(|| create_pgo_func_name_var(self, instance)) } } @@ -118,11 +113,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { cond_bitmaps.push(cond_bitmap); } - self.coverage_context() - .expect("always present when coverage is enabled") - .mcdc_condition_bitmap_map - .borrow_mut() - .insert(instance, cond_bitmaps); + self.coverage_cx().mcdc_condition_bitmap_map.borrow_mut().insert(instance, cond_bitmaps); } #[instrument(level = "debug", skip(self))] @@ -143,8 +134,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { return; }; - let Some(coverage_context) = bx.coverage_context() else { return }; - let mut coverage_map = coverage_context.function_coverage_map.borrow_mut(); + let mut coverage_map = bx.coverage_cx().function_coverage_map.borrow_mut(); let func_coverage = coverage_map .entry(instance) .or_insert_with(|| FunctionCoverageCollector::new(instance, function_coverage_info)); @@ -186,7 +176,8 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { } CoverageKind::CondBitmapUpdate { index, decision_depth } => { drop(coverage_map); - let cond_bitmap = coverage_context + let cond_bitmap = bx + .coverage_cx() .try_get_mcdc_condition_bitmap(&instance, decision_depth) .expect("mcdc cond bitmap should have been allocated for updating"); let cond_index = bx.const_i32(index as i32); @@ -194,7 +185,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { } CoverageKind::TestVectorBitmapUpdate { bitmap_idx, decision_depth } => { drop(coverage_map); - let cond_bitmap = coverage_context + let cond_bitmap = bx.coverage_cx() .try_get_mcdc_condition_bitmap(&instance, decision_depth) .expect("mcdc cond bitmap should have been allocated for merging into the global bitmap"); assert!( From 0356908cf5e5ead075608709663a38b51c584872 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 24 Oct 2024 22:05:42 +1100 Subject: [PATCH 226/366] coverage: Store `covfun_section_name` in the codegen context Adding an extra `OnceCell` to `CrateCoverageContext` is much nicer than trying to thread this string through multiple layers of function calls that already have access to the context. --- .../src/coverageinfo/mapgen.rs | 7 +-- .../src/coverageinfo/mod.rs | 44 +++++++++---------- 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 7a2a802eb4eb..5b39d078e0d7 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -1,4 +1,4 @@ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use itertools::Itertools as _; use rustc_abi::Align; @@ -81,7 +81,6 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { generate_covmap_record(cx, covmap_version, filenames_size, filenames_val); let mut unused_function_names = Vec::new(); - let covfun_section_name = coverageinfo::covfun_section_name(cx); // Encode coverage mappings and generate function records for (instance, function_coverage) in function_coverage_entries { @@ -112,7 +111,6 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { generate_covfun_record( cx, - &covfun_section_name, mangled_function_name, source_hash, filenames_ref, @@ -360,7 +358,6 @@ fn generate_covmap_record<'ll>( /// as a global variable in the `__llvm_covfun` section. fn generate_covfun_record( cx: &CodegenCx<'_, '_>, - covfun_section_name: &CStr, mangled_function_name: &str, source_hash: u64, filenames_ref: u64, @@ -401,7 +398,7 @@ fn generate_covfun_record( llvm::set_global_constant(llglobal, true); llvm::set_linkage(llglobal, llvm::Linkage::LinkOnceODRLinkage); llvm::set_visibility(llglobal, llvm::Visibility::Hidden); - llvm::set_section(llglobal, covfun_section_name); + llvm::set_section(llglobal, cx.covfun_section_name()); // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. llvm::set_alignment(llglobal, Align::EIGHT); if cx.target_spec().supports_comdat() { diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index eaf720cc769e..e4f78dd877e9 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -1,5 +1,5 @@ -use std::cell::RefCell; -use std::ffi::CString; +use std::cell::{OnceCell, RefCell}; +use std::ffi::{CStr, CString}; use libc::c_uint; use rustc_codegen_ssa::traits::{ @@ -29,6 +29,8 @@ pub(crate) struct CrateCoverageContext<'ll, 'tcx> { RefCell, FunctionCoverageCollector<'tcx>>>, pub(crate) pgo_func_name_var_map: RefCell, &'ll llvm::Value>>, pub(crate) mcdc_condition_bitmap_map: RefCell, Vec<&'ll llvm::Value>>>, + + covfun_section_name: OnceCell, } impl<'ll, 'tcx> CrateCoverageContext<'ll, 'tcx> { @@ -37,6 +39,7 @@ impl<'ll, 'tcx> CrateCoverageContext<'ll, 'tcx> { function_coverage_map: Default::default(), pgo_func_name_var_map: Default::default(), mcdc_condition_bitmap_map: Default::default(), + covfun_section_name: Default::default(), } } @@ -63,13 +66,28 @@ impl<'ll, 'tcx> CrateCoverageContext<'ll, 'tcx> { } } -// These methods used to be part of trait `CoverageInfoMethods`, which no longer -// exists after most coverage code was moved out of SSA. impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { pub(crate) fn coverageinfo_finalize(&self) { mapgen::finalize(self) } + /// Returns the section name to use when embedding per-function coverage information + /// in the object file, according to the target's object file format. LLVM's coverage + /// tools use information from this section when producing coverage reports. + /// + /// Typical values are: + /// - `__llvm_covfun` on Linux + /// - `__LLVM_COV,__llvm_covfun` on macOS (includes `__LLVM_COV,` segment prefix) + /// - `.lcovfun$M` on Windows (includes `$M` sorting suffix) + fn covfun_section_name(&self) -> &CStr { + self.coverage_cx().covfun_section_name.get_or_init(|| { + CString::new(llvm::build_byte_buffer(|s| unsafe { + llvm::LLVMRustCoverageWriteFuncSectionNameToString(self.llmod, s); + })) + .expect("covfun section name should not contain NUL") + }) + } + /// For LLVM codegen, returns a function-specific `Value` for a global /// string, to hold the function name passed to LLVM intrinsic /// `instrprof.increment()`. The `Value` is only created once per instance. @@ -278,21 +296,3 @@ pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 { pub(crate) fn mapping_version() -> u32 { unsafe { llvm::LLVMRustCoverageMappingVersion() } } - -/// Returns the section name string to pass through to the linker when embedding -/// per-function coverage information in the object file, according to the target -/// platform's object file format. -/// -/// LLVM's coverage tools read coverage mapping details from this section when -/// producing coverage reports. -/// -/// Typical values are: -/// - `__llvm_covfun` on Linux -/// - `__LLVM_COV,__llvm_covfun` on macOS (includes `__LLVM_COV,` segment prefix) -/// - `.lcovfun$M` on Windows (includes `$M` sorting suffix) -pub(crate) fn covfun_section_name(cx: &CodegenCx<'_, '_>) -> CString { - CString::new(llvm::build_byte_buffer(|s| unsafe { - llvm::LLVMRustCoverageWriteFuncSectionNameToString(cx.llmod, s); - })) - .expect("covfun section name should not contain NUL") -} From 3528149f735e801eb5710585d5f3b4fa73d6e1e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Thu, 24 Oct 2024 23:53:08 +0800 Subject: [PATCH 227/366] Introduce `Enabled{Lang,Lib}Feature` Instead of passing around random n-tuples of e.g. `(gate_name, attr_sp, since)`. --- compiler/rustc_ast_passes/src/feature_gate.rs | 23 ++++----- compiler/rustc_expand/src/config.rs | 21 ++++++--- compiler/rustc_feature/src/lib.rs | 4 +- compiler/rustc_feature/src/unstable.rs | 47 +++++++++++++------ compiler/rustc_lint/src/builtin.rs | 16 ++++--- compiler/rustc_passes/src/stability.rs | 24 +++++----- .../src/ich/impls_syntax.rs | 17 +++++++ 7 files changed, 101 insertions(+), 51 deletions(-) diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 348a602fd59d..d646150a620c 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -623,8 +623,9 @@ fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) let stable_since = features .enabled_lang_features() .iter() - .flat_map(|&(feature, _, since)| if feature == name { since } else { None }) - .next(); + .find(|feat| feat.gate_name == name) + .map(|feat| feat.stable_since) + .flatten(); if let Some(since) = stable_since { err.stable_features.push(errors::StableFeature { name, since }); } else { @@ -642,16 +643,15 @@ fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) } fn check_incompatible_features(sess: &Session, features: &Features) { - let enabled_features = features - .enabled_lang_features() - .iter() - .copied() - .map(|(name, span, _)| (name, span)) - .chain(features.enabled_lib_features().iter().copied()); + let enabled_lang_features = + features.enabled_lang_features().iter().map(|feat| (feat.gate_name, feat.attr_sp)); + let enabled_lib_features = + features.enabled_lib_features().iter().map(|feat| (feat.gate_name, feat.attr_sp)); + let enabled_features = enabled_lang_features.chain(enabled_lib_features); for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES .iter() - .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2)) + .filter(|(f1, f2)| features.enabled(*f1) && features.enabled(*f2)) { if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1) { if let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2) @@ -673,10 +673,11 @@ fn check_new_solver_banned_features(sess: &Session, features: &Features) { } // Ban GCE with the new solver, because it does not implement GCE correctly. - if let Some(&(_, gce_span, _)) = features + if let Some(gce_span) = features .enabled_lang_features() .iter() - .find(|&&(feat, _, _)| feat == sym::generic_const_exprs) + .find(|feat| feat.gate_name == sym::generic_const_exprs) + .map(|feat| feat.attr_sp) { sess.dcx().emit_err(errors::IncompatibleFeatures { spans: vec![gce_span], diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 5bd9e2fbcb9b..dc6aa110f459 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -11,8 +11,8 @@ use rustc_ast::{ use rustc_attr as attr; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_feature::{ - ACCEPTED_LANG_FEATURES, AttributeSafety, Features, REMOVED_LANG_FEATURES, - UNSTABLE_LANG_FEATURES, + ACCEPTED_LANG_FEATURES, AttributeSafety, EnabledLangFeature, EnabledLibFeature, Features, + REMOVED_LANG_FEATURES, UNSTABLE_LANG_FEATURES, }; use rustc_lint_defs::BuiltinLintDiag; use rustc_parse::validate_attr; @@ -88,8 +88,11 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - // If the enabled feature is stable, record it. if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| name == f.name) { - let since = Some(Symbol::intern(f.since)); - features.set_enabled_lang_feature(name, mi.span(), since); + features.set_enabled_lang_feature(EnabledLangFeature { + gate_name: name, + attr_sp: mi.span(), + stable_since: Some(Symbol::intern(f.since)), + }); continue; } @@ -115,13 +118,19 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - { sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed); } - features.set_enabled_lang_feature(name, mi.span(), None); + + features.set_enabled_lang_feature(EnabledLangFeature { + gate_name: name, + attr_sp: mi.span(), + stable_since: None, + }); continue; } // Otherwise, the feature is unknown. Enable it as a lib feature. // It will be checked later whether the feature really exists. - features.set_enabled_lib_feature(name, mi.span()); + features + .set_enabled_lib_feature(EnabledLibFeature { gate_name: name, attr_sp: mi.span() }); // Similar to above, detect internal lib features to suppress // the ICE message that asks for a report. diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index 216793485e55..9f42d3ec45cd 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -135,4 +135,6 @@ pub use builtin_attrs::{ is_valid_for_get_attr, }; pub use removed::REMOVED_LANG_FEATURES; -pub use unstable::{Features, INCOMPATIBLE_FEATURES, UNSTABLE_LANG_FEATURES}; +pub use unstable::{ + EnabledLangFeature, EnabledLibFeature, Features, INCOMPATIBLE_FEATURES, UNSTABLE_LANG_FEATURES, +}; diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 8182eb1e9735..f29bae611242 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -36,35 +36,54 @@ macro_rules! status_to_enum { #[derive(Clone, Default, Debug)] pub struct Features { /// `#![feature]` attrs for language features, for error reporting. - enabled_lang_features: Vec<(Symbol, Span, Option)>, + enabled_lang_features: Vec, /// `#![feature]` attrs for non-language (library) features. - enabled_lib_features: Vec<(Symbol, Span)>, + enabled_lib_features: Vec, /// `enabled_lang_features` + `enabled_lib_features`. enabled_features: FxHashSet, } +/// Information about an enabled language feature. +#[derive(Debug, Copy, Clone)] +pub struct EnabledLangFeature { + /// Name of the feature gate guarding the language feature. + pub gate_name: Symbol, + /// Span of the `#[feature(...)]` attribute. + pub attr_sp: Span, + /// If the lang feature is stable, the version number when it was stabilized. + pub stable_since: Option, +} + +/// Information abhout an enabled library feature. +#[derive(Debug, Copy, Clone)] +pub struct EnabledLibFeature { + pub gate_name: Symbol, + pub attr_sp: Span, +} + impl Features { /// `since` should be set for stable features that are nevertheless enabled with a `#[feature]` /// attribute, indicating since when they are stable. - pub fn set_enabled_lang_feature(&mut self, name: Symbol, span: Span, since: Option) { - self.enabled_lang_features.push((name, span, since)); - self.enabled_features.insert(name); + pub fn set_enabled_lang_feature(&mut self, lang_feat: EnabledLangFeature) { + self.enabled_lang_features.push(lang_feat); + self.enabled_features.insert(lang_feat.gate_name); } - pub fn set_enabled_lib_feature(&mut self, name: Symbol, span: Span) { - self.enabled_lib_features.push((name, span)); - self.enabled_features.insert(name); + pub fn set_enabled_lib_feature(&mut self, lib_feat: EnabledLibFeature) { + self.enabled_lib_features.push(lib_feat); + self.enabled_features.insert(lib_feat.gate_name); } - /// Returns a list of triples with: - /// - feature gate name - /// - the span of the `#[feature]` attribute - /// - (for already stable features) the version since which it is stable - pub fn enabled_lang_features(&self) -> &Vec<(Symbol, Span, Option)> { + /// Returns a list of [`EnabledLangFeature`] with info about: + /// + /// - Feature gate name. + /// - The span of the `#[feature]` attribute. + /// - For stable language features, version info for when it was stabilized. + pub fn enabled_lang_features(&self) -> &Vec { &self.enabled_lang_features } - pub fn enabled_lib_features(&self) -> &Vec<(Symbol, Span)> { + pub fn enabled_lib_features(&self) -> &Vec { &self.enabled_lib_features } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 5c5cd99345ef..601aaaa96ada 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2287,13 +2287,15 @@ declare_lint_pass!( impl EarlyLintPass for IncompleteInternalFeatures { fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { let features = cx.builder.features(); - features - .enabled_lang_features() - .iter() - .map(|(name, span, _)| (name, span)) - .chain(features.enabled_lib_features().iter().map(|(name, span)| (name, span))) - .filter(|(&name, _)| features.incomplete(name) || features.internal(name)) - .for_each(|(&name, &span)| { + let lang_features = + features.enabled_lang_features().iter().map(|feat| (feat.gate_name, feat.attr_sp)); + let lib_features = + features.enabled_lib_features().iter().map(|feat| (feat.gate_name, feat.attr_sp)); + + lang_features + .chain(lib_features) + .filter(|(name, _)| features.incomplete(*name) || features.internal(*name)) + .for_each(|(name, span)| { if features.incomplete(name) { let note = rustc_feature::find_feature_issue(name, GateIssue::Language) .map(|n| BuiltinFeatureIssueNote { n }); diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index a176b2bb1ad4..b1a056883c1c 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -10,7 +10,7 @@ use rustc_attr::{ }; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet}; -use rustc_feature::ACCEPTED_LANG_FEATURES; +use rustc_feature::{ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId}; @@ -937,25 +937,25 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { let enabled_lang_features = tcx.features().enabled_lang_features(); let mut lang_features = UnordSet::default(); - for &(feature, span, since) in enabled_lang_features { - if let Some(since) = since { + for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features { + if let Some(version) = stable_since { // Warn if the user has enabled an already-stable lang feature. - unnecessary_stable_feature_lint(tcx, span, feature, since); + unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version); } - if !lang_features.insert(feature) { + if !lang_features.insert(gate_name) { // Warn if the user enables a lang feature multiple times. - tcx.dcx().emit_err(errors::DuplicateFeatureErr { span, feature }); + tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *attr_sp, feature: *gate_name }); } } let enabled_lib_features = tcx.features().enabled_lib_features(); let mut remaining_lib_features = FxIndexMap::default(); - for (feature, span) in enabled_lib_features { - if remaining_lib_features.contains_key(&feature) { + for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features { + if remaining_lib_features.contains_key(gate_name) { // Warn if the user enables a lib feature multiple times. - tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *span, feature: *feature }); + tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *attr_sp, feature: *gate_name }); } - remaining_lib_features.insert(feature, *span); + remaining_lib_features.insert(*gate_name, *attr_sp); } // `stdbuild` has special handling for `libc`, so we need to // recognise the feature when building std. @@ -987,7 +987,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { /// time, less loading from metadata is performed and thus compiler performance is improved. fn check_features<'tcx>( tcx: TyCtxt<'tcx>, - remaining_lib_features: &mut FxIndexMap<&Symbol, Span>, + remaining_lib_features: &mut FxIndexMap, remaining_implications: &mut UnordMap, defined_features: &LibFeatures, all_implications: &UnordMap, @@ -1057,7 +1057,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { } for (feature, span) in remaining_lib_features { - tcx.dcx().emit_err(errors::UnknownFeature { span, feature: *feature }); + tcx.dcx().emit_err(errors::UnknownFeature { span, feature }); } for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() { diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 0665401df8e8..5a72e80a0a5c 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -116,3 +116,20 @@ impl<'tcx> HashStable> for rustc_feature::Features { self.enabled_lib_features().hash_stable(hcx, hasher); } } + +impl<'tcx> HashStable> for rustc_feature::EnabledLangFeature { + fn hash_stable(&self, hcx: &mut StableHashingContext<'tcx>, hasher: &mut StableHasher) { + let rustc_feature::EnabledLangFeature { gate_name, attr_sp, stable_since } = self; + gate_name.hash_stable(hcx, hasher); + attr_sp.hash_stable(hcx, hasher); + stable_since.hash_stable(hcx, hasher); + } +} + +impl<'tcx> HashStable> for rustc_feature::EnabledLibFeature { + fn hash_stable(&self, hcx: &mut StableHashingContext<'tcx>, hasher: &mut StableHasher) { + let rustc_feature::EnabledLibFeature { gate_name, attr_sp } = self; + gate_name.hash_stable(hcx, hasher); + attr_sp.hash_stable(hcx, hasher); + } +} From 4923e856be61bfb8faac18eaf1f2b0d8e70ea3be Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 13:06:57 +1100 Subject: [PATCH 228/366] coverage: Emit `llvm.instrprof.increment` using the normal helper method --- compiler/rustc_codegen_llvm/src/builder.rs | 26 ++----------------- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 1 - .../rustc_llvm/llvm-wrapper/RustWrapper.cpp | 11 -------- 3 files changed, 2 insertions(+), 36 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index dbf5298d64ba..8e718226a9a3 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1165,6 +1165,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size); } + #[instrument(level = "debug", skip(self))] fn instrprof_increment( &mut self, fn_name: &'ll Value, @@ -1172,30 +1173,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { num_counters: &'ll Value, index: &'ll Value, ) { - debug!( - "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})", - fn_name, hash, num_counters, index - ); - - let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) }; - let llty = self.cx.type_func( - &[self.cx.type_ptr(), self.cx.type_i64(), self.cx.type_i32(), self.cx.type_i32()], - self.cx.type_void(), - ); - let args = &[fn_name, hash, num_counters, index]; - let args = self.check_call("call", llty, llfn, args); - - unsafe { - let _ = llvm::LLVMRustBuildCall( - self.llbuilder, - llty, - llfn, - args.as_ptr() as *const &llvm::Value, - args.len() as c_uint, - [].as_ptr(), - 0 as c_uint, - ); - } + self.call_intrinsic("llvm.instrprof.increment", &[fn_name, hash, num_counters, index]); } fn call( diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 50e6c1494a8d..a52004bacd92 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1615,7 +1615,6 @@ unsafe extern "C" { pub fn LLVMRustSetAllowReassoc(Instr: &Value); // Miscellaneous instructions - pub fn LLVMRustGetInstrProfIncrementIntrinsic(M: &Module) -> &Value; pub fn LLVMRustGetInstrProfMCDCParametersIntrinsic(M: &Module) -> &Value; pub fn LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(M: &Module) -> &Value; diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 910c27da9546..ed9db2059332 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1531,17 +1531,6 @@ extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, ArrayRef(OpBundles))); } -extern "C" LLVMValueRef -LLVMRustGetInstrProfIncrementIntrinsic(LLVMModuleRef M) { -#if LLVM_VERSION_GE(20, 0) - return wrap(llvm::Intrinsic::getOrInsertDeclaration( - unwrap(M), llvm::Intrinsic::instrprof_increment)); -#else - return wrap(llvm::Intrinsic::getDeclaration( - unwrap(M), llvm::Intrinsic::instrprof_increment)); -#endif -} - extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRef M) { #if LLVM_VERSION_LT(19, 0) From b3d65852c3addf4e8e6be96965ead86c2d4fb8be Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 13:25:19 +1100 Subject: [PATCH 229/366] coverage: Emit MC/DC intrinsics using the normal helper method --- compiler/rustc_codegen_llvm/src/builder.rs | 55 +++---------------- compiler/rustc_codegen_llvm/src/context.rs | 4 ++ .../src/coverageinfo/mod.rs | 1 + compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 3 - .../rustc_llvm/llvm-wrapper/RustWrapper.cpp | 28 ---------- 5 files changed, 14 insertions(+), 77 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 8e718226a9a3..f4463e037c94 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1654,40 +1654,21 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { /// /// [`CodeGenPGO::emitMCDCParameters`]: /// https://github.com/rust-lang/llvm-project/blob/5399a24/clang/lib/CodeGen/CodeGenPGO.cpp#L1124 + #[instrument(level = "debug", skip(self))] pub(crate) fn mcdc_parameters( &mut self, fn_name: &'ll Value, hash: &'ll Value, bitmap_bits: &'ll Value, ) { - debug!("mcdc_parameters() with args ({:?}, {:?}, {:?})", fn_name, hash, bitmap_bits); - assert!( crate::llvm_util::get_version() >= (19, 0, 0), "MCDC intrinsics require LLVM 19 or later" ); - - let llfn = unsafe { llvm::LLVMRustGetInstrProfMCDCParametersIntrinsic(self.cx().llmod) }; - let llty = self.cx.type_func( - &[self.cx.type_ptr(), self.cx.type_i64(), self.cx.type_i32()], - self.cx.type_void(), - ); - let args = &[fn_name, hash, bitmap_bits]; - let args = self.check_call("call", llty, llfn, args); - - unsafe { - let _ = llvm::LLVMRustBuildCall( - self.llbuilder, - llty, - llfn, - args.as_ptr() as *const &llvm::Value, - args.len() as c_uint, - [].as_ptr(), - 0 as c_uint, - ); - } + self.call_intrinsic("llvm.instrprof.mcdc.parameters", &[fn_name, hash, bitmap_bits]); } + #[instrument(level = "debug", skip(self))] pub(crate) fn mcdc_tvbitmap_update( &mut self, fn_name: &'ll Value, @@ -1695,39 +1676,21 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { bitmap_index: &'ll Value, mcdc_temp: &'ll Value, ) { - debug!( - "mcdc_tvbitmap_update() with args ({:?}, {:?}, {:?}, {:?})", - fn_name, hash, bitmap_index, mcdc_temp - ); assert!( crate::llvm_util::get_version() >= (19, 0, 0), "MCDC intrinsics require LLVM 19 or later" ); - - let llfn = - unsafe { llvm::LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(self.cx().llmod) }; - let llty = self.cx.type_func( - &[self.cx.type_ptr(), self.cx.type_i64(), self.cx.type_i32(), self.cx.type_ptr()], - self.cx.type_void(), - ); let args = &[fn_name, hash, bitmap_index, mcdc_temp]; - let args = self.check_call("call", llty, llfn, args); - unsafe { - let _ = llvm::LLVMRustBuildCall( - self.llbuilder, - llty, - llfn, - args.as_ptr() as *const &llvm::Value, - args.len() as c_uint, - [].as_ptr(), - 0 as c_uint, - ); - } + self.call_intrinsic("llvm.instrprof.mcdc.tvbitmap.update", args); + } + + #[instrument(level = "debug", skip(self))] + pub(crate) fn mcdc_condbitmap_reset(&mut self, mcdc_temp: &'ll Value) { self.store(self.const_i32(0), mcdc_temp, self.tcx.data_layout.i32_align.abi); } + #[instrument(level = "debug", skip(self))] pub(crate) fn mcdc_condbitmap_update(&mut self, cond_index: &'ll Value, mcdc_temp: &'ll Value) { - debug!("mcdc_condbitmap_update() with args ({:?}, {:?})", cond_index, mcdc_temp); assert!( crate::llvm_util::get_version() >= (19, 0, 0), "MCDC intrinsics require LLVM 19 or later" diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 2f830d6f941e..fb845c0087b1 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -1099,6 +1099,10 @@ impl<'ll> CodegenCx<'ll, '_> { if self.sess().instrument_coverage() { ifn!("llvm.instrprof.increment", fn(ptr, t_i64, t_i32, t_i32) -> void); + if crate::llvm_util::get_version() >= (19, 0, 0) { + ifn!("llvm.instrprof.mcdc.parameters", fn(ptr, t_i64, t_i32) -> void); + ifn!("llvm.instrprof.mcdc.tvbitmap.update", fn(ptr, t_i64, t_i32, ptr) -> void); + } } ifn!("llvm.type.test", fn(ptr, t_metadata) -> i1); diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index b2956945911b..36b1747f2fdc 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -208,6 +208,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { let hash = bx.const_u64(function_coverage_info.function_source_hash); let bitmap_index = bx.const_u32(bitmap_idx); bx.mcdc_tvbitmap_update(fn_name, hash, bitmap_index, cond_bitmap); + bx.mcdc_condbitmap_reset(cond_bitmap); } } } diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index a52004bacd92..10e55a4f7f65 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1615,9 +1615,6 @@ unsafe extern "C" { pub fn LLVMRustSetAllowReassoc(Instr: &Value); // Miscellaneous instructions - pub fn LLVMRustGetInstrProfMCDCParametersIntrinsic(M: &Module) -> &Value; - pub fn LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(M: &Module) -> &Value; - pub fn LLVMRustBuildCall<'a>( B: &Builder<'a>, Ty: &'a Type, diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index ed9db2059332..cb75888abd76 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1531,34 +1531,6 @@ extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, ArrayRef(OpBundles))); } -extern "C" LLVMValueRef -LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRef M) { -#if LLVM_VERSION_LT(19, 0) - report_fatal_error("LLVM 19.0 is required for mcdc intrinsic functions"); -#endif -#if LLVM_VERSION_GE(20, 0) - return wrap(llvm::Intrinsic::getOrInsertDeclaration( - unwrap(M), llvm::Intrinsic::instrprof_mcdc_parameters)); -#else - return wrap(llvm::Intrinsic::getDeclaration( - unwrap(M), llvm::Intrinsic::instrprof_mcdc_parameters)); -#endif -} - -extern "C" LLVMValueRef -LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModuleRef M) { -#if LLVM_VERSION_LT(19, 0) - report_fatal_error("LLVM 19.0 is required for mcdc intrinsic functions"); -#endif -#if LLVM_VERSION_GE(20, 0) - return wrap(llvm::Intrinsic::getOrInsertDeclaration( - unwrap(M), llvm::Intrinsic::instrprof_mcdc_tvbitmap_update)); -#else - return wrap(llvm::Intrinsic::getDeclaration( - unwrap(M), llvm::Intrinsic::instrprof_mcdc_tvbitmap_update)); -#endif -} - extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, LLVMValueRef Src, unsigned SrcAlign, From a05b16bdb5452a284914fa9ce23f849317af2b8d Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Fri, 6 Sep 2024 16:25:22 +0300 Subject: [PATCH 230/366] Build source map for `hir_def::TypeRef`s So that given a `TypeRef` we will be able to trace it back to source code. This is necessary to be able to provide diagnostics for lowering to chalk tys, since the input to that is `TypeRef`. This means that `TypeRef`s now have an identity, which means storing them in arena and not interning them, which is an unfortunate (but necessary) loss but also a pretty massive change. Luckily, because of the separation layer we have for IDE and HIR, this change never crosses the IDE boundary. --- .../rust-analyzer/crates/hir-def/src/body.rs | 17 + .../crates/hir-def/src/body/lower.rs | 54 ++- .../crates/hir-def/src/body/lower/asm.rs | 4 +- .../crates/hir-def/src/body/pretty.rs | 27 +- .../rust-analyzer/crates/hir-def/src/data.rs | 42 +- .../crates/hir-def/src/data/adt.rs | 46 ++- .../rust-analyzer/crates/hir-def/src/db.rs | 26 +- .../crates/hir-def/src/expander.rs | 32 +- .../crates/hir-def/src/generics.rs | 318 ++++++++++++--- .../rust-analyzer/crates/hir-def/src/hir.rs | 15 +- .../crates/hir-def/src/hir/type_ref.rs | 167 +++++--- .../crates/hir-def/src/item_tree.rs | 195 +++++++-- .../crates/hir-def/src/item_tree/lower.rs | 377 ++++++++++++------ .../crates/hir-def/src/item_tree/pretty.rs | 100 +++-- .../rust-analyzer/crates/hir-def/src/lib.rs | 8 - .../rust-analyzer/crates/hir-def/src/lower.rs | 62 ++- .../hir-def/src/nameres/tests/incremental.rs | 5 +- .../rust-analyzer/crates/hir-def/src/path.rs | 28 +- .../crates/hir-def/src/path/lower.rs | 31 +- .../crates/hir-def/src/pretty.rs | 60 +-- .../crates/hir-def/src/resolver.rs | 21 +- .../crates/hir-ty/src/chalk_db.rs | 5 +- .../hir-ty/src/diagnostics/decl_check.rs | 4 +- .../hir-ty/src/diagnostics/match_check.rs | 2 +- .../crates/hir-ty/src/display.rs | 154 +++++-- .../crates/hir-ty/src/generics.rs | 17 +- .../rust-analyzer/crates/hir-ty/src/infer.rs | 67 +++- .../crates/hir-ty/src/infer/closure.rs | 14 +- .../crates/hir-ty/src/infer/expr.rs | 11 +- .../crates/hir-ty/src/infer/path.rs | 45 +-- .../rust-analyzer/crates/hir-ty/src/lower.rs | 306 ++++++++------ .../crates/hir-ty/src/mir/eval.rs | 3 +- .../crates/hir-ty/src/mir/lower.rs | 30 +- .../hir-ty/src/mir/lower/pattern_matching.rs | 5 +- .../rust-analyzer/crates/hir-ty/src/utils.rs | 10 +- .../rust-analyzer/crates/hir/src/display.rs | 95 ++--- src/tools/rust-analyzer/crates/hir/src/lib.rs | 6 +- .../rust-analyzer/crates/hir/src/semantics.rs | 23 +- .../crates/hir/src/source_analyzer.rs | 47 ++- .../rust-analyzer/crates/hir/src/symbols.rs | 11 +- 40 files changed, 1712 insertions(+), 778 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body.rs b/src/tools/rust-analyzer/crates/hir-def/src/body.rs index 1bfd7d2b7319..5a386f6cf8d1 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body.rs @@ -30,6 +30,7 @@ use crate::{ nameres::DefMap, path::{ModPath, Path}, src::HasSource, + type_ref::{TypeRef, TypeRefId, TypesMap, TypesSourceMap}, BlockId, DefWithBodyId, HasModule, Lookup, }; @@ -69,6 +70,7 @@ pub struct Body { pub self_param: Option, /// The `ExprId` of the actual body expression. pub body_expr: ExprId, + pub types: TypesMap, /// Block expressions in this body that may contain inner items. block_scopes: Vec, @@ -139,6 +141,8 @@ pub struct BodySourceMap { field_map_back: FxHashMap, pat_field_map_back: FxHashMap, + types: TypesSourceMap, + // FIXME: Make this a sane struct. template_map: Option< Box<( @@ -304,6 +308,7 @@ impl Body { binding_hygiene, expr_hygiene, pat_hygiene, + types, } = self; block_scopes.shrink_to_fit(); exprs.shrink_to_fit(); @@ -314,6 +319,7 @@ impl Body { binding_hygiene.shrink_to_fit(); expr_hygiene.shrink_to_fit(); pat_hygiene.shrink_to_fit(); + types.shrink_to_fit(); } pub fn walk_bindings_in_pat(&self, pat_id: PatId, mut f: impl FnMut(BindingId)) { @@ -542,6 +548,7 @@ impl Default for Body { binding_hygiene: Default::default(), expr_hygiene: Default::default(), pat_hygiene: Default::default(), + types: Default::default(), } } } @@ -578,6 +585,14 @@ impl Index for Body { } } +impl Index for Body { + type Output = TypeRef; + + fn index(&self, b: TypeRefId) -> &TypeRef { + &self.types[b] + } +} + // FIXME: Change `node_` prefix to something more reasonable. // Perhaps `expr_syntax` and `expr_id`? impl BodySourceMap { @@ -691,6 +706,7 @@ impl BodySourceMap { template_map, diagnostics, binding_definitions, + types, } = self; if let Some(template_map) = template_map { template_map.0.shrink_to_fit(); @@ -707,5 +723,6 @@ impl BodySourceMap { expansions.shrink_to_fit(); diagnostics.shrink_to_fit(); binding_definitions.shrink_to_fit(); + types.shrink_to_fit(); } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index b87e94f9c51d..3ecb9576b7f4 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -12,7 +12,7 @@ use hir_expand::{ span_map::{ExpansionSpanMap, SpanMap}, InFile, MacroDefId, }; -use intern::{sym, Interned, Symbol}; +use intern::{sym, Symbol}; use rustc_hash::FxHashMap; use span::AstIdMap; use stdx::never; @@ -274,8 +274,8 @@ impl ExprCollector<'_> { (self.body, self.source_map) } - fn ctx(&self) -> LowerCtx<'_> { - self.expander.ctx(self.db) + fn ctx(&mut self) -> LowerCtx<'_> { + self.expander.ctx(self.db, &mut self.body.types, &mut self.source_map.types) } fn collect_expr(&mut self, expr: ast::Expr) -> ExprId { @@ -436,7 +436,7 @@ impl ExprCollector<'_> { } ast::Expr::PathExpr(e) => { let (path, hygiene) = self - .collect_expr_path(&e) + .collect_expr_path(e) .map(|(path, hygiene)| (Expr::Path(path), hygiene)) .unwrap_or((Expr::Missing, HygieneId::ROOT)); let expr_id = self.alloc_expr(path, syntax_ptr); @@ -486,8 +486,7 @@ impl ExprCollector<'_> { self.alloc_expr(Expr::Yeet { expr }, syntax_ptr) } ast::Expr::RecordExpr(e) => { - let path = - e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); + let path = e.path().and_then(|path| self.parse_path(path)).map(Box::new); let record_lit = if let Some(nfl) = e.record_expr_field_list() { let fields = nfl .fields() @@ -534,7 +533,7 @@ impl ExprCollector<'_> { ast::Expr::TryExpr(e) => self.collect_try_operator(syntax_ptr, e), ast::Expr::CastExpr(e) => { let expr = self.collect_expr_opt(e.expr()); - let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty())); + let type_ref = TypeRef::from_ast_opt(&self.ctx(), e.ty()); self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr) } ast::Expr::RefExpr(e) => { @@ -573,16 +572,13 @@ impl ExprCollector<'_> { arg_types.reserve_exact(num_params); for param in pl.params() { let pat = this.collect_pat_top(param.pat()); - let type_ref = - param.ty().map(|it| Interned::new(TypeRef::from_ast(&this.ctx(), it))); + let type_ref = param.ty().map(|it| TypeRef::from_ast(&this.ctx(), it)); args.push(pat); arg_types.push(type_ref); } } - let ret_type = e - .ret_type() - .and_then(|r| r.ty()) - .map(|it| Interned::new(TypeRef::from_ast(&this.ctx(), it))); + let ret_type = + e.ret_type().and_then(|r| r.ty()).map(|it| TypeRef::from_ast(&this.ctx(), it)); let prev_is_lowering_coroutine = mem::take(&mut this.is_lowering_coroutine); let prev_try_block_label = this.current_try_block_label.take(); @@ -709,7 +705,7 @@ impl ExprCollector<'_> { ast::Expr::UnderscoreExpr(_) => self.alloc_expr(Expr::Underscore, syntax_ptr), ast::Expr::AsmExpr(e) => self.lower_inline_asm(e, syntax_ptr), ast::Expr::OffsetOfExpr(e) => { - let container = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty())); + let container = TypeRef::from_ast_opt(&self.ctx(), e.ty()); let fields = e.fields().map(|it| it.as_name()).collect(); self.alloc_expr(Expr::OffsetOf(OffsetOf { container, fields }), syntax_ptr) } @@ -717,9 +713,13 @@ impl ExprCollector<'_> { }) } - fn collect_expr_path(&mut self, e: &ast::PathExpr) -> Option<(Path, HygieneId)> { + fn parse_path(&mut self, path: ast::Path) -> Option { + self.expander.parse_path(self.db, path, &mut self.body.types, &mut self.source_map.types) + } + + fn collect_expr_path(&mut self, e: ast::PathExpr) -> Option<(Path, HygieneId)> { e.path().and_then(|path| { - let path = self.expander.parse_path(self.db, path)?; + let path = self.parse_path(path)?; let Path::Normal { type_anchor, mod_path, generic_args } = &path else { panic!("path parsing produced a non-normal path"); }; @@ -790,16 +790,13 @@ impl ExprCollector<'_> { } ast::Expr::CallExpr(e) => { let path = collect_path(self, e.expr()?)?; - let path = path - .path() - .and_then(|path| self.expander.parse_path(self.db, path)) - .map(Box::new); + let path = path.path().and_then(|path| self.parse_path(path)).map(Box::new); let (ellipsis, args) = collect_tuple(self, e.arg_list()?.args()); self.alloc_pat_from_expr(Pat::TupleStruct { path, args, ellipsis }, syntax_ptr) } ast::Expr::PathExpr(e) => { let (path, hygiene) = self - .collect_expr_path(e) + .collect_expr_path(e.clone()) .map(|(path, hygiene)| (Pat::Path(Box::new(path)), hygiene)) .unwrap_or((Pat::Missing, HygieneId::ROOT)); let pat_id = self.alloc_pat_from_expr(path, syntax_ptr); @@ -819,8 +816,7 @@ impl ExprCollector<'_> { id } ast::Expr::RecordExpr(e) => { - let path = - e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); + let path = e.path().and_then(|path| self.parse_path(path)).map(Box::new); let record_field_list = e.record_expr_field_list()?; let ellipsis = record_field_list.dotdot_token().is_some(); // FIXME: Report an error here if `record_field_list.spread().is_some()`. @@ -1325,8 +1321,7 @@ impl ExprCollector<'_> { return; } let pat = self.collect_pat_top(stmt.pat()); - let type_ref = - stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it))); + let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it)); let initializer = stmt.initializer().map(|e| self.collect_expr(e)); let else_branch = stmt .let_else() @@ -1552,8 +1547,7 @@ impl ExprCollector<'_> { return pat; } ast::Pat::TupleStructPat(p) => { - let path = - p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); + let path = p.path().and_then(|path| self.parse_path(path)).map(Box::new); let (args, ellipsis) = self.collect_tuple_pat( p.fields(), comma_follows_token(p.l_paren_token()), @@ -1567,8 +1561,7 @@ impl ExprCollector<'_> { Pat::Ref { pat, mutability } } ast::Pat::PathPat(p) => { - let path = - p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); + let path = p.path().and_then(|path| self.parse_path(path)).map(Box::new); path.map(Pat::Path).unwrap_or(Pat::Missing) } ast::Pat::OrPat(p) => 'b: { @@ -1611,8 +1604,7 @@ impl ExprCollector<'_> { } ast::Pat::WildcardPat(_) => Pat::Wild, ast::Pat::RecordPat(p) => { - let path = - p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new); + let path = p.path().and_then(|path| self.parse_path(path)).map(Box::new); let record_pat_field_list = &p.record_pat_field_list().expect("every struct should have a field list"); let args = record_pat_field_list diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs index 4213370ac195..c1b58dbdd0cb 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs @@ -158,9 +158,7 @@ impl ExprCollector<'_> { AsmOperand::Const(self.collect_expr_opt(c.expr())) } ast::AsmOperand::AsmSym(s) => { - let Some(path) = - s.path().and_then(|p| self.expander.parse_path(self.db, p)) - else { + let Some(path) = s.path().and_then(|p| self.parse_path(p)) else { continue; }; AsmOperand::Sym(path) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs index 591bb64af5a8..f8b6eef34222 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs @@ -11,7 +11,6 @@ use crate::{ Statement, }, pretty::{print_generic_args, print_path, print_type_ref}, - type_ref::TypeRef, }; use super::*; @@ -69,20 +68,20 @@ pub(super) fn print_body_hir( }; if let DefWithBodyId::FunctionId(it) = owner { p.buf.push('('); - let function_data = &db.function_data(it); + let function_data = db.function_data(it); let (mut params, ret_type) = (function_data.params.iter(), &function_data.ret_type); if let Some(self_param) = body.self_param { p.print_binding(self_param); p.buf.push_str(": "); if let Some(ty) = params.next() { - p.print_type_ref(ty); + p.print_type_ref(*ty, &function_data.types_map); p.buf.push_str(", "); } } body.params.iter().zip(params).for_each(|(¶m, ty)| { p.print_pat(param); p.buf.push_str(": "); - p.print_type_ref(ty); + p.print_type_ref(*ty, &function_data.types_map); p.buf.push_str(", "); }); // remove the last ", " in param list @@ -92,7 +91,7 @@ pub(super) fn print_body_hir( p.buf.push(')'); // return type p.buf.push_str(" -> "); - p.print_type_ref(ret_type); + p.print_type_ref(*ret_type, &function_data.types_map); p.buf.push(' '); } p.print_expr(body.body_expr); @@ -242,7 +241,7 @@ impl Printer<'_> { Expr::InlineAsm(_) => w!(self, "builtin#asm(_)"), Expr::OffsetOf(offset_of) => { w!(self, "builtin#offset_of("); - self.print_type_ref(&offset_of.container); + self.print_type_ref(offset_of.container, &self.body.types); let edition = self.edition; w!( self, @@ -296,7 +295,7 @@ impl Printer<'_> { if let Some(args) = generic_args { w!(self, "::<"); let edition = self.edition; - print_generic_args(self.db, args, self, edition).unwrap(); + print_generic_args(self.db, args, &self.body.types, self, edition).unwrap(); w!(self, ">"); } w!(self, "("); @@ -405,7 +404,7 @@ impl Printer<'_> { Expr::Cast { expr, type_ref } => { self.print_expr(*expr); w!(self, " as "); - self.print_type_ref(type_ref); + self.print_type_ref(*type_ref, &self.body.types); } Expr::Ref { expr, rawness, mutability } => { w!(self, "&"); @@ -493,13 +492,13 @@ impl Printer<'_> { self.print_pat(*pat); if let Some(ty) = ty { w!(self, ": "); - self.print_type_ref(ty); + self.print_type_ref(*ty, &self.body.types); } } w!(self, "|"); if let Some(ret_ty) = ret_type { w!(self, " -> "); - self.print_type_ref(ret_ty); + self.print_type_ref(*ret_ty, &self.body.types); } self.whitespace(); self.print_expr(*body); @@ -734,7 +733,7 @@ impl Printer<'_> { self.print_pat(*pat); if let Some(ty) = type_ref { w!(self, ": "); - self.print_type_ref(ty); + self.print_type_ref(*ty, &self.body.types); } if let Some(init) = initializer { w!(self, " = "); @@ -792,14 +791,14 @@ impl Printer<'_> { } } - fn print_type_ref(&mut self, ty: &TypeRef) { + fn print_type_ref(&mut self, ty: TypeRefId, map: &TypesMap) { let edition = self.edition; - print_type_ref(self.db, ty, self, edition).unwrap(); + print_type_ref(self.db, ty, map, self, edition).unwrap(); } fn print_path(&mut self, path: &Path) { let edition = self.edition; - print_path(self.db, path, self, edition).unwrap(); + print_path(self.db, path, &self.body.types, self, edition).unwrap(); } fn print_binding(&mut self, id: BindingId) { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/data.rs b/src/tools/rust-analyzer/crates/hir-def/src/data.rs index 263fad51d78e..f49018eaf381 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/data.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/data.rs @@ -6,7 +6,7 @@ use base_db::CrateId; use hir_expand::{ name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefKind, }; -use intern::{sym, Interned, Symbol}; +use intern::{sym, Symbol}; use la_arena::{Idx, RawIdx}; use smallvec::SmallVec; use syntax::{ast, Parse}; @@ -25,7 +25,7 @@ use crate::{ DefMap, MacroSubNs, }, path::ImportAlias, - type_ref::{TraitRef, TypeBound, TypeRef}, + type_ref::{TraitRef, TypeBound, TypeRefId, TypesMap}, visibility::RawVisibility, AssocItemId, AstIdWithPath, ConstId, ConstLoc, ExternCrateId, FunctionId, FunctionLoc, HasModule, ImplId, Intern, ItemContainerId, ItemLoc, Lookup, Macro2Id, MacroRulesId, ModuleId, @@ -35,13 +35,14 @@ use crate::{ #[derive(Debug, Clone, PartialEq, Eq)] pub struct FunctionData { pub name: Name, - pub params: Box<[Interned]>, - pub ret_type: Interned, + pub params: Box<[TypeRefId]>, + pub ret_type: TypeRefId, pub attrs: Attrs, pub visibility: RawVisibility, pub abi: Option, pub legacy_const_generics_indices: Option>>, pub rustc_allow_incoherent_impl: bool, + pub types_map: Arc, flags: FnFlags, } @@ -110,13 +111,14 @@ impl FunctionData { .filter(|&(idx, _)| { item_tree.attrs(db, krate, attr_owner(idx)).is_cfg_enabled(cfg_options) }) - .filter_map(|(_, param)| param.type_ref.clone()) + .filter_map(|(_, param)| param.type_ref) .collect(), - ret_type: func.ret_type.clone(), + ret_type: func.ret_type, attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()), visibility, abi: func.abi.clone(), legacy_const_generics_indices, + types_map: func.types_map.clone(), flags, rustc_allow_incoherent_impl, }) @@ -182,13 +184,14 @@ fn parse_rustc_legacy_const_generics(tt: &crate::tt::Subtree) -> Box<[u32]> { #[derive(Debug, Clone, PartialEq, Eq)] pub struct TypeAliasData { pub name: Name, - pub type_ref: Option>, + pub type_ref: Option, pub visibility: RawVisibility, pub is_extern: bool, pub rustc_has_incoherent_inherent_impls: bool, pub rustc_allow_incoherent_impl: bool, /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl). - pub bounds: Box<[Interned]>, + pub bounds: Box<[TypeBound]>, + pub types_map: Arc, } impl TypeAliasData { @@ -216,12 +219,13 @@ impl TypeAliasData { Arc::new(TypeAliasData { name: typ.name.clone(), - type_ref: typ.type_ref.clone(), + type_ref: typ.type_ref, visibility, is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)), rustc_has_incoherent_inherent_impls, rustc_allow_incoherent_impl, bounds: typ.bounds.clone(), + types_map: typ.types_map.clone(), }) } } @@ -343,13 +347,14 @@ impl TraitAliasData { #[derive(Debug, PartialEq, Eq)] pub struct ImplData { - pub target_trait: Option>, - pub self_ty: Interned, + pub target_trait: Option, + pub self_ty: TypeRefId, pub items: Box<[AssocItemId]>, pub is_negative: bool, pub is_unsafe: bool, // box it as the vec is usually empty anyways pub macro_calls: Option, MacroCallId)>>>, + pub types_map: Arc, } impl ImplData { @@ -368,7 +373,7 @@ impl ImplData { let item_tree = tree_id.item_tree(db); let impl_def = &item_tree[tree_id.value]; let target_trait = impl_def.target_trait.clone(); - let self_ty = impl_def.self_ty.clone(); + let self_ty = impl_def.self_ty; let is_negative = impl_def.is_negative; let is_unsafe = impl_def.is_unsafe; @@ -387,6 +392,7 @@ impl ImplData { is_negative, is_unsafe, macro_calls, + types_map: impl_def.types_map.clone(), }), DefDiagnostics::new(diagnostics), ) @@ -532,10 +538,11 @@ impl ExternCrateDeclData { pub struct ConstData { /// `None` for `const _: () = ();` pub name: Option, - pub type_ref: Interned, + pub type_ref: TypeRefId, pub visibility: RawVisibility, pub rustc_allow_incoherent_impl: bool, pub has_body: bool, + pub types_map: Arc, } impl ConstData { @@ -556,10 +563,11 @@ impl ConstData { Arc::new(ConstData { name: konst.name.clone(), - type_ref: konst.type_ref.clone(), + type_ref: konst.type_ref, visibility, rustc_allow_incoherent_impl, has_body: konst.has_body, + types_map: konst.types_map.clone(), }) } } @@ -567,12 +575,13 @@ impl ConstData { #[derive(Debug, Clone, PartialEq, Eq)] pub struct StaticData { pub name: Name, - pub type_ref: Interned, + pub type_ref: TypeRefId, pub visibility: RawVisibility, pub mutable: bool, pub is_extern: bool, pub has_safe_kw: bool, pub has_unsafe_kw: bool, + pub types_map: Arc, } impl StaticData { @@ -583,12 +592,13 @@ impl StaticData { Arc::new(StaticData { name: statik.name.clone(), - type_ref: statik.type_ref.clone(), + type_ref: statik.type_ref, visibility: item_tree[statik.visibility].clone(), mutable: statik.mutable, is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)), has_safe_kw: statik.has_safe_kw, has_unsafe_kw: statik.has_unsafe_kw, + types_map: statik.types_map.clone(), }) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/data/adt.rs b/src/tools/rust-analyzer/crates/hir-def/src/data/adt.rs index ba54451e594f..068ebb3b7e91 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/data/adt.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/data/adt.rs @@ -6,7 +6,7 @@ use cfg::CfgOptions; use either::Either; use hir_expand::name::Name; -use intern::{sym, Interned}; +use intern::sym; use la_arena::Arena; use rustc_abi::{Align, Integer, IntegerType, ReprFlags, ReprOptions}; use triomphe::Arc; @@ -21,7 +21,7 @@ use crate::{ lang_item::LangItem, nameres::diagnostics::{DefDiagnostic, DefDiagnostics}, tt::{Delimiter, DelimiterKind, Leaf, Subtree, TokenTree}, - type_ref::TypeRef, + type_ref::{TypeRefId, TypesMap}, visibility::RawVisibility, EnumId, EnumVariantId, LocalFieldId, LocalModuleId, Lookup, StructId, UnionId, VariantId, }; @@ -73,8 +73,8 @@ pub struct EnumVariantData { #[derive(Debug, Clone, PartialEq, Eq)] pub enum VariantData { - Record(Arena), - Tuple(Arena), + Record { fields: Arena, types_map: Arc }, + Tuple { fields: Arena, types_map: Arc }, Unit, } @@ -82,7 +82,7 @@ pub enum VariantData { #[derive(Debug, Clone, PartialEq, Eq)] pub struct FieldData { pub name: Name, - pub type_ref: Interned, + pub type_ref: TypeRefId, pub visibility: RawVisibility, } @@ -208,7 +208,7 @@ impl StructData { } let strukt = &item_tree[loc.id.value]; - let (data, diagnostics) = lower_fields( + let (fields, diagnostics) = lower_fields( db, krate, loc.container.local_id, @@ -219,12 +219,13 @@ impl StructData { &strukt.fields, None, ); + let types_map = strukt.types_map.clone(); ( Arc::new(StructData { name: strukt.name.clone(), variant_data: Arc::new(match strukt.shape { - FieldsShape::Record => VariantData::Record(data), - FieldsShape::Tuple => VariantData::Tuple(data), + FieldsShape::Record => VariantData::Record { fields, types_map }, + FieldsShape::Tuple => VariantData::Tuple { fields, types_map }, FieldsShape::Unit => VariantData::Unit, }), repr, @@ -258,7 +259,7 @@ impl StructData { } let union = &item_tree[loc.id.value]; - let (data, diagnostics) = lower_fields( + let (fields, diagnostics) = lower_fields( db, krate, loc.container.local_id, @@ -269,10 +270,11 @@ impl StructData { &union.fields, None, ); + let types_map = union.types_map.clone(); ( Arc::new(StructData { name: union.name.clone(), - variant_data: Arc::new(VariantData::Record(data)), + variant_data: Arc::new(VariantData::Record { fields, types_map }), repr, visibility: item_tree[union.visibility].clone(), flags, @@ -360,7 +362,7 @@ impl EnumVariantData { let item_tree = loc.id.item_tree(db); let variant = &item_tree[loc.id.value]; - let (data, diagnostics) = lower_fields( + let (fields, diagnostics) = lower_fields( db, krate, container.local_id, @@ -371,13 +373,14 @@ impl EnumVariantData { &variant.fields, Some(item_tree[loc.parent.lookup(db).id.value].visibility), ); + let types_map = variant.types_map.clone(); ( Arc::new(EnumVariantData { name: variant.name.clone(), variant_data: Arc::new(match variant.shape { - FieldsShape::Record => VariantData::Record(data), - FieldsShape::Tuple => VariantData::Tuple(data), + FieldsShape::Record => VariantData::Record { fields, types_map }, + FieldsShape::Tuple => VariantData::Tuple { fields, types_map }, FieldsShape::Unit => VariantData::Unit, }), }), @@ -390,11 +393,20 @@ impl VariantData { pub fn fields(&self) -> &Arena { const EMPTY: &Arena = &Arena::new(); match &self { - VariantData::Record(fields) | VariantData::Tuple(fields) => fields, + VariantData::Record { fields, .. } | VariantData::Tuple { fields, .. } => fields, _ => EMPTY, } } + pub fn types_map(&self) -> &TypesMap { + match &self { + VariantData::Record { types_map, .. } | VariantData::Tuple { types_map, .. } => { + types_map + } + VariantData::Unit => TypesMap::EMPTY, + } + } + // FIXME: Linear lookup pub fn field(&self, name: &Name) -> Option { self.fields().iter().find_map(|(id, data)| if &data.name == name { Some(id) } else { None }) @@ -402,8 +414,8 @@ impl VariantData { pub fn kind(&self) -> StructKind { match self { - VariantData::Record(_) => StructKind::Record, - VariantData::Tuple(_) => StructKind::Tuple, + VariantData::Record { .. } => StructKind::Record, + VariantData::Tuple { .. } => StructKind::Tuple, VariantData::Unit => StructKind::Unit, } } @@ -463,7 +475,7 @@ fn lower_field( ) -> FieldData { FieldData { name: field.name.clone(), - type_ref: field.type_ref.clone(), + type_ref: field.type_ref, visibility: item_tree[override_visibility.unwrap_or(field.visibility)].clone(), } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/db.rs b/src/tools/rust-analyzer/crates/hir-def/src/db.rs index aeda302f35c5..d7e83ce33e89 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/db.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/db.rs @@ -2,7 +2,7 @@ use base_db::{ra_salsa, CrateId, SourceDatabase, Upcast}; use either::Either; use hir_expand::{db::ExpandDatabase, HirFileId, MacroDefId}; -use intern::{sym, Interned}; +use intern::sym; use la_arena::ArenaMap; use span::{EditionedFileId, MacroCallId}; use syntax::{ast, AstPtr}; @@ -18,9 +18,10 @@ use crate::{ }, generics::GenericParams, import_map::ImportMap, - item_tree::{AttrOwner, ItemTree}, + item_tree::{AttrOwner, ItemTree, ItemTreeSourceMaps}, lang_item::{self, LangItem, LangItemTarget, LangItems}, nameres::{diagnostics::DefDiagnostics, DefMap}, + type_ref::TypesSourceMap, visibility::{self, Visibility}, AttrDefId, BlockId, BlockLoc, ConstBlockId, ConstBlockLoc, ConstId, ConstLoc, DefWithBodyId, EnumId, EnumLoc, EnumVariantId, EnumVariantLoc, ExternBlockId, ExternBlockLoc, ExternCrateId, @@ -91,6 +92,18 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + Upcast Arc; + #[ra_salsa::invoke(ItemTree::file_item_tree_with_source_map_query)] + fn file_item_tree_with_source_map( + &self, + file_id: HirFileId, + ) -> (Arc, Arc); + + #[ra_salsa::invoke(ItemTree::block_item_tree_with_source_map_query)] + fn block_item_tree_with_source_map( + &self, + block_id: BlockId, + ) -> (Arc, Arc); + #[ra_salsa::invoke(DefMap::crate_def_map_query)] fn crate_def_map(&self, krate: CrateId) -> Arc; @@ -187,7 +200,14 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + Upcast Arc; #[ra_salsa::invoke(GenericParams::generic_params_query)] - fn generic_params(&self, def: GenericDefId) -> Interned; + fn generic_params(&self, def: GenericDefId) -> Arc; + + /// If this returns `None` for the source map, that means it is the same as with the item tree. + #[ra_salsa::invoke(GenericParams::generic_params_with_source_map_query)] + fn generic_params_with_source_map( + &self, + def: GenericDefId, + ) -> (Arc, Option>); // region:attrs diff --git a/src/tools/rust-analyzer/crates/hir-def/src/expander.rs b/src/tools/rust-analyzer/crates/hir-def/src/expander.rs index 6f200021baa9..d430733fcadf 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/expander.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/expander.rs @@ -14,6 +14,7 @@ use span::SyntaxContextId; use syntax::{ast, Parse}; use triomphe::Arc; +use crate::type_ref::{TypesMap, TypesSourceMap}; use crate::{ attr::Attrs, db::DefDatabase, lower::LowerCtx, path::Path, AsMacroCall, MacroId, ModuleId, UnresolvedMacro, @@ -114,8 +115,19 @@ impl Expander { mark.bomb.defuse(); } - pub fn ctx<'a>(&self, db: &'a dyn DefDatabase) -> LowerCtx<'a> { - LowerCtx::with_span_map_cell(db, self.current_file_id, self.span_map.clone()) + pub fn ctx<'a>( + &self, + db: &'a dyn DefDatabase, + types_map: &'a mut TypesMap, + types_source_map: &'a mut TypesSourceMap, + ) -> LowerCtx<'a> { + LowerCtx::with_span_map_cell( + db, + self.current_file_id, + self.span_map.clone(), + types_map, + types_source_map, + ) } pub(crate) fn in_file(&self, value: T) -> InFile { @@ -142,8 +154,20 @@ impl Expander { self.current_file_id } - pub(crate) fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option { - let ctx = LowerCtx::with_span_map_cell(db, self.current_file_id, self.span_map.clone()); + pub(crate) fn parse_path( + &mut self, + db: &dyn DefDatabase, + path: ast::Path, + types_map: &mut TypesMap, + types_source_map: &mut TypesSourceMap, + ) -> Option { + let ctx = LowerCtx::with_span_map_cell( + db, + self.current_file_id, + self.span_map.clone(), + types_map, + types_source_map, + ); Path::from_src(&ctx, path) } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs index 6c34ee086aa9..f30a2edda908 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs @@ -10,7 +10,6 @@ use hir_expand::{ name::{AsName, Name}, ExpandResult, }; -use intern::Interned; use la_arena::{Arena, RawIdx}; use stdx::impl_from; use syntax::ast::{self, HasGenericParams, HasName, HasTypeBounds}; @@ -22,7 +21,8 @@ use crate::{ item_tree::{AttrOwner, FileItemTreeId, GenericModItem, GenericsItemTreeNode, ItemTree}, lower::LowerCtx, nameres::{DefMap, MacroSubNs}, - type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRef}, + path::{AssociatedTypeBinding, GenericArg, GenericArgs, Path}, + type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRef, TypeRefId, TypesMap, TypesSourceMap}, AdtId, ConstParamId, GenericDefId, HasModule, ItemTreeLoc, LifetimeParamId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId, }; @@ -37,7 +37,7 @@ pub struct TypeParamData { /// [`None`] only if the type ref is an [`TypeRef::ImplTrait`]. FIXME: Might be better to just /// make it always be a value, giving impl trait a special name. pub name: Option, - pub default: Option>, + pub default: Option, pub provenance: TypeParamProvenance, } @@ -51,7 +51,7 @@ pub struct LifetimeParamData { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct ConstParamData { pub name: Name, - pub ty: Interned, + pub ty: TypeRefId, pub default: Option, } @@ -161,6 +161,7 @@ pub struct GenericParams { type_or_consts: Arena, lifetimes: Arena, where_predicates: Box<[WherePredicate]>, + pub types_map: TypesMap, } impl ops::Index for GenericParams { @@ -183,24 +184,14 @@ impl ops::Index for GenericParams { /// associated type bindings like `Iterator`. #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub enum WherePredicate { - TypeBound { - target: WherePredicateTypeTarget, - bound: Interned, - }, - Lifetime { - target: LifetimeRef, - bound: LifetimeRef, - }, - ForLifetime { - lifetimes: Box<[Name]>, - target: WherePredicateTypeTarget, - bound: Interned, - }, + TypeBound { target: WherePredicateTypeTarget, bound: TypeBound }, + Lifetime { target: LifetimeRef, bound: LifetimeRef }, + ForLifetime { lifetimes: Box<[Name]>, target: WherePredicateTypeTarget, bound: TypeBound }, } #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub enum WherePredicateTypeTarget { - TypeRef(Interned), + TypeRef(TypeRefId), /// For desugared where predicates that can directly refer to a type param. TypeOrConstParam(LocalTypeOrConstParamId), } @@ -300,7 +291,14 @@ impl GenericParams { pub(crate) fn generic_params_query( db: &dyn DefDatabase, def: GenericDefId, - ) -> Interned { + ) -> Arc { + db.generic_params_with_source_map(def).0 + } + + pub(crate) fn generic_params_with_source_map_query( + db: &dyn DefDatabase, + def: GenericDefId, + ) -> (Arc, Option>) { let _p = tracing::info_span!("generic_params_query").entered(); let krate = def.krate(db); @@ -309,7 +307,7 @@ impl GenericParams { // Returns the generic parameters that are enabled under the current `#[cfg]` options let enabled_params = - |params: &Interned, item_tree: &ItemTree, parent: GenericModItem| { + |params: &Arc, item_tree: &ItemTree, parent: GenericModItem| { let enabled = |param| item_tree.attrs(db, krate, param).is_cfg_enabled(cfg_options); let attr_owner_ct = |param| AttrOwner::TypeOrConstParamData(parent, param); let attr_owner_lt = |param| AttrOwner::LifetimeParamData(parent, param); @@ -325,7 +323,7 @@ impl GenericParams { if all_type_or_consts_enabled && all_lifetimes_enabled { params.clone() } else { - Interned::new(GenericParams { + Arc::new(GenericParams { type_or_consts: all_type_or_consts_enabled .then(|| params.type_or_consts.clone()) .unwrap_or_else(|| { @@ -347,6 +345,7 @@ impl GenericParams { .collect() }), where_predicates: params.where_predicates.clone(), + types_map: params.types_map.clone(), }) } }; @@ -357,18 +356,18 @@ impl GenericParams { Data = impl ItemTreeLoc, >, enabled_params: impl Fn( - &Interned, + &Arc, &ItemTree, GenericModItem, - ) -> Interned, - ) -> Interned + ) -> Arc, + ) -> (Arc, Option>) where FileItemTreeId: Into, { let id = id.lookup(db).item_tree_id(); let tree = id.item_tree(db); let item = &tree[id.value]; - enabled_params(item.generic_params(), &tree, id.value.into()) + (enabled_params(item.generic_params(), &tree, id.value.into()), None) } match def { @@ -383,28 +382,37 @@ impl GenericParams { let module = loc.container.module(db); let func_data = db.function_data(id); if func_data.params.is_empty() { - enabled_params + (enabled_params, None) } else { + let source_maps = loc.id.item_tree_with_source_map(db).1; + let item_source_maps = &source_maps[loc.id.value]; let mut generic_params = GenericParamsCollector { type_or_consts: enabled_params.type_or_consts.clone(), lifetimes: enabled_params.lifetimes.clone(), where_predicates: enabled_params.where_predicates.clone().into(), }; + let (mut types_map, mut types_source_maps) = + (enabled_params.types_map.clone(), item_source_maps.generics.clone()); // Don't create an `Expander` if not needed since this // could cause a reparse after the `ItemTree` has been created due to the spanmap. let mut expander = None; - for param in func_data.params.iter() { + for ¶m in func_data.params.iter() { generic_params.fill_implicit_impl_trait_args( db, + &mut types_map, + &mut types_source_maps, &mut expander, &mut || { (module.def_map(db), Expander::new(db, loc.id.file_id(), module)) }, param, + &item.types_map, + &item_source_maps.item, ); } - Interned::new(generic_params.finish()) + let generics = generic_params.finish(types_map, &mut types_source_maps); + (Arc::new(generics), Some(Arc::new(types_source_maps))) } } GenericDefId::AdtId(AdtId::StructId(id)) => id_to_generics(db, id, enabled_params), @@ -414,11 +422,15 @@ impl GenericParams { GenericDefId::TraitAliasId(id) => id_to_generics(db, id, enabled_params), GenericDefId::TypeAliasId(id) => id_to_generics(db, id, enabled_params), GenericDefId::ImplId(id) => id_to_generics(db, id, enabled_params), - GenericDefId::ConstId(_) => Interned::new(GenericParams { - type_or_consts: Default::default(), - lifetimes: Default::default(), - where_predicates: Default::default(), - }), + GenericDefId::ConstId(_) => ( + Arc::new(GenericParams { + type_or_consts: Default::default(), + lifetimes: Default::default(), + where_predicates: Default::default(), + types_map: Default::default(), + }), + None, + ), } } } @@ -452,7 +464,7 @@ impl GenericParamsCollector { &mut self, lower_ctx: &LowerCtx<'_>, type_bounds: Option, - target: Either, + target: Either, ) { for bound in type_bounds.iter().flat_map(|type_bound_list| type_bound_list.bounds()) { self.add_where_predicate_from_bound(lower_ctx, bound, None, target.clone()); @@ -473,16 +485,15 @@ impl GenericParamsCollector { ast::TypeOrConstParam::Type(type_param) => { let name = type_param.name().map_or_else(Name::missing, |it| it.as_name()); // FIXME: Use `Path::from_src` - let default = type_param - .default_type() - .map(|it| Interned::new(TypeRef::from_ast(lower_ctx, it))); + let default = + type_param.default_type().map(|it| TypeRef::from_ast(lower_ctx, it)); let param = TypeParamData { name: Some(name.clone()), default, provenance: TypeParamProvenance::TypeParamList, }; let idx = self.type_or_consts.alloc(param.into()); - let type_ref = TypeRef::Path(name.into()); + let type_ref = lower_ctx.alloc_type_ref_desugared(TypeRef::Path(name.into())); self.fill_bounds( lower_ctx, type_param.type_bound_list(), @@ -492,12 +503,10 @@ impl GenericParamsCollector { } ast::TypeOrConstParam::Const(const_param) => { let name = const_param.name().map_or_else(Name::missing, |it| it.as_name()); - let ty = const_param - .ty() - .map_or(TypeRef::Error, |it| TypeRef::from_ast(lower_ctx, it)); + let ty = TypeRef::from_ast_opt(lower_ctx, const_param.ty()); let param = ConstParamData { name, - ty: Interned::new(ty), + ty, default: ConstRef::from_const_param(lower_ctx, &const_param), }; let idx = self.type_or_consts.alloc(param.into()); @@ -557,7 +566,7 @@ impl GenericParamsCollector { lower_ctx: &LowerCtx<'_>, bound: ast::TypeBound, hrtb_lifetimes: Option<&[Name]>, - target: Either, + target: Either, ) { let bound = TypeBound::from_ast(lower_ctx, bound); self.fill_impl_trait_bounds(lower_ctx.take_impl_traits_bounds()); @@ -565,12 +574,12 @@ impl GenericParamsCollector { (Either::Left(type_ref), bound) => match hrtb_lifetimes { Some(hrtb_lifetimes) => WherePredicate::ForLifetime { lifetimes: hrtb_lifetimes.to_vec().into_boxed_slice(), - target: WherePredicateTypeTarget::TypeRef(Interned::new(type_ref)), - bound: Interned::new(bound), + target: WherePredicateTypeTarget::TypeRef(type_ref), + bound, }, None => WherePredicate::TypeBound { - target: WherePredicateTypeTarget::TypeRef(Interned::new(type_ref)), - bound: Interned::new(bound), + target: WherePredicateTypeTarget::TypeRef(type_ref), + bound, }, }, (Either::Right(lifetime), TypeBound::Lifetime(bound)) => { @@ -581,7 +590,7 @@ impl GenericParamsCollector { self.where_predicates.push(predicate); } - fn fill_impl_trait_bounds(&mut self, impl_bounds: Vec>>) { + fn fill_impl_trait_bounds(&mut self, impl_bounds: Vec>) { for bounds in impl_bounds { let param = TypeParamData { name: None, @@ -601,12 +610,16 @@ impl GenericParamsCollector { fn fill_implicit_impl_trait_args( &mut self, db: &dyn DefDatabase, + generics_types_map: &mut TypesMap, + generics_types_source_map: &mut TypesSourceMap, // FIXME: Change this back to `LazyCell` if https://github.com/rust-lang/libs-team/issues/429 is accepted. exp: &mut Option<(Arc, Expander)>, exp_fill: &mut dyn FnMut() -> (Arc, Expander), - type_ref: &TypeRef, + type_ref: TypeRefId, + types_map: &TypesMap, + types_source_map: &TypesSourceMap, ) { - type_ref.walk(&mut |type_ref| { + TypeRef::walk(type_ref, types_map, &mut |type_ref| { if let TypeRef::ImplTrait(bounds) = type_ref { let param = TypeParamData { name: None, @@ -615,12 +628,20 @@ impl GenericParamsCollector { }; let param_id = self.type_or_consts.alloc(param.into()); for bound in bounds { + let bound = copy_type_bound( + bound, + types_map, + types_source_map, + generics_types_map, + generics_types_source_map, + ); self.where_predicates.push(WherePredicate::TypeBound { target: WherePredicateTypeTarget::TypeOrConstParam(param_id), - bound: bound.clone(), + bound, }); } } + if let TypeRef::Macro(mc) = type_ref { let macro_call = mc.to_node(db.upcast()); let (def_map, expander) = exp.get_or_insert_with(&mut *exp_fill); @@ -641,23 +662,210 @@ impl GenericParamsCollector { if let Ok(ExpandResult { value: Some((mark, expanded)), .. }) = expander.enter_expand(db, macro_call, resolver) { - let ctx = expander.ctx(db); + let (mut macro_types_map, mut macro_types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = expander.ctx(db, &mut macro_types_map, &mut macro_types_source_map); let type_ref = TypeRef::from_ast(&ctx, expanded.tree()); - self.fill_implicit_impl_trait_args(db, &mut *exp, exp_fill, &type_ref); + self.fill_implicit_impl_trait_args( + db, + generics_types_map, + generics_types_source_map, + &mut *exp, + exp_fill, + type_ref, + ¯o_types_map, + ¯o_types_source_map, + ); exp.get_or_insert_with(&mut *exp_fill).1.exit(mark); } } }); } - pub(crate) fn finish(self) -> GenericParams { - let Self { mut lifetimes, mut type_or_consts, where_predicates } = self; + pub(crate) fn finish( + self, + mut generics_types_map: TypesMap, + generics_types_source_map: &mut TypesSourceMap, + ) -> GenericParams { + let Self { mut lifetimes, mut type_or_consts, mut where_predicates } = self; lifetimes.shrink_to_fit(); type_or_consts.shrink_to_fit(); + where_predicates.shrink_to_fit(); + generics_types_map.shrink_to_fit(); + generics_types_source_map.shrink_to_fit(); GenericParams { type_or_consts, lifetimes, where_predicates: where_predicates.into_boxed_slice(), + types_map: generics_types_map, } } } + +/// Copies a `TypeRef` from a `TypesMap` (accompanied with `TypesSourceMap`) into another `TypesMap` +/// (and `TypesSourceMap`). +fn copy_type_ref( + type_ref: TypeRefId, + from: &TypesMap, + from_source_map: &TypesSourceMap, + to: &mut TypesMap, + to_source_map: &mut TypesSourceMap, +) -> TypeRefId { + let result = match &from[type_ref] { + &TypeRef::Fn { ref params, is_varargs, is_unsafe, ref abi } => { + let params = params + .iter() + .map(|(name, param_type)| { + ( + name.clone(), + copy_type_ref(*param_type, from, from_source_map, to, to_source_map), + ) + }) + .collect(); + TypeRef::Fn { params, is_varargs, is_unsafe, abi: abi.clone() } + } + TypeRef::Tuple(types) => TypeRef::Tuple( + types + .iter() + .map(|&t| copy_type_ref(t, from, from_source_map, to, to_source_map)) + .collect(), + ), + &TypeRef::RawPtr(type_ref, mutbl) => TypeRef::RawPtr( + copy_type_ref(type_ref, from, from_source_map, to, to_source_map), + mutbl, + ), + TypeRef::Reference(type_ref, lifetime, mutbl) => TypeRef::Reference( + copy_type_ref(*type_ref, from, from_source_map, to, to_source_map), + lifetime.clone(), + *mutbl, + ), + TypeRef::Array(type_ref, len) => TypeRef::Array( + copy_type_ref(*type_ref, from, from_source_map, to, to_source_map), + len.clone(), + ), + &TypeRef::Slice(type_ref) => { + TypeRef::Slice(copy_type_ref(type_ref, from, from_source_map, to, to_source_map)) + } + TypeRef::ImplTrait(bounds) => TypeRef::ImplTrait( + copy_type_bounds(bounds, from, from_source_map, to, to_source_map).into(), + ), + TypeRef::DynTrait(bounds) => TypeRef::DynTrait( + copy_type_bounds(bounds, from, from_source_map, to, to_source_map).into(), + ), + TypeRef::Path(path) => { + TypeRef::Path(copy_path(path, from, from_source_map, to, to_source_map)) + } + TypeRef::Never => TypeRef::Never, + TypeRef::Placeholder => TypeRef::Placeholder, + TypeRef::Macro(macro_call) => TypeRef::Macro(*macro_call), + TypeRef::Error => TypeRef::Error, + }; + let id = to.types.alloc(result); + if let Some(&ptr) = from_source_map.types_map_back.get(id) { + to_source_map.types_map_back.insert(id, ptr); + } + id +} + +fn copy_path( + path: &Path, + from: &TypesMap, + from_source_map: &TypesSourceMap, + to: &mut TypesMap, + to_source_map: &mut TypesSourceMap, +) -> Path { + match path { + Path::Normal { type_anchor, mod_path, generic_args } => { + let type_anchor = type_anchor + .map(|type_ref| copy_type_ref(type_ref, from, from_source_map, to, to_source_map)); + let mod_path = mod_path.clone(); + let generic_args = generic_args.as_ref().map(|generic_args| { + generic_args + .iter() + .map(|generic_args| { + copy_generic_args(generic_args, from, from_source_map, to, to_source_map) + }) + .collect() + }); + Path::Normal { type_anchor, mod_path, generic_args } + } + Path::LangItem(lang_item, name) => Path::LangItem(*lang_item, name.clone()), + } +} + +fn copy_generic_args( + generic_args: &Option, + from: &TypesMap, + from_source_map: &TypesSourceMap, + to: &mut TypesMap, + to_source_map: &mut TypesSourceMap, +) -> Option { + generic_args.as_ref().map(|generic_args| { + let args = generic_args + .args + .iter() + .map(|arg| match arg { + &GenericArg::Type(ty) => { + GenericArg::Type(copy_type_ref(ty, from, from_source_map, to, to_source_map)) + } + GenericArg::Lifetime(lifetime) => GenericArg::Lifetime(lifetime.clone()), + GenericArg::Const(konst) => GenericArg::Const(konst.clone()), + }) + .collect(); + let bindings = generic_args + .bindings + .iter() + .map(|binding| { + let name = binding.name.clone(); + let args = + copy_generic_args(&binding.args, from, from_source_map, to, to_source_map); + let type_ref = binding.type_ref.map(|type_ref| { + copy_type_ref(type_ref, from, from_source_map, to, to_source_map) + }); + let bounds = + copy_type_bounds(&binding.bounds, from, from_source_map, to, to_source_map); + AssociatedTypeBinding { name, args, type_ref, bounds } + }) + .collect(); + GenericArgs { + args, + has_self_type: generic_args.has_self_type, + bindings, + desugared_from_fn: generic_args.desugared_from_fn, + } + }) +} + +fn copy_type_bounds( + bounds: &[TypeBound], + from: &TypesMap, + from_source_map: &TypesSourceMap, + to: &mut TypesMap, + to_source_map: &mut TypesSourceMap, +) -> Box<[TypeBound]> { + bounds + .iter() + .map(|bound| copy_type_bound(bound, from, from_source_map, to, to_source_map)) + .collect() +} + +fn copy_type_bound( + bound: &TypeBound, + from: &TypesMap, + from_source_map: &TypesSourceMap, + to: &mut TypesMap, + to_source_map: &mut TypesSourceMap, +) -> TypeBound { + match bound { + TypeBound::Path(path, modifier) => { + TypeBound::Path(copy_path(path, from, from_source_map, to, to_source_map), *modifier) + } + TypeBound::ForLifetime(lifetimes, path) => TypeBound::ForLifetime( + lifetimes.clone(), + copy_path(path, from, from_source_map, to, to_source_map), + ), + TypeBound::Lifetime(lifetime) => TypeBound::Lifetime(lifetime.clone()), + TypeBound::Use(use_args) => TypeBound::Use(use_args.clone()), + TypeBound::Error => TypeBound::Error, + } +} diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs index c1d3e255bb5b..df1e10323062 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs @@ -18,15 +18,16 @@ pub mod type_ref; use std::fmt; use hir_expand::{name::Name, MacroDefId}; -use intern::{Interned, Symbol}; +use intern::Symbol; use la_arena::{Idx, RawIdx}; use rustc_apfloat::ieee::{Half as f16, Quad as f128}; use syntax::ast; +use type_ref::TypeRefId; use crate::{ builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint}, path::{GenericArgs, Path}, - type_ref::{Mutability, Rawness, TypeRef}, + type_ref::{Mutability, Rawness}, BlockId, ConstBlockId, }; @@ -264,7 +265,7 @@ pub enum Expr { }, Cast { expr: ExprId, - type_ref: Interned, + type_ref: TypeRefId, }, Ref { expr: ExprId, @@ -300,8 +301,8 @@ pub enum Expr { }, Closure { args: Box<[PatId]>, - arg_types: Box<[Option>]>, - ret_type: Option>, + arg_types: Box<[Option]>, + ret_type: Option, body: ExprId, closure_kind: ClosureKind, capture_by: CaptureBy, @@ -318,7 +319,7 @@ pub enum Expr { #[derive(Debug, Clone, PartialEq, Eq)] pub struct OffsetOf { - pub container: Interned, + pub container: TypeRefId, pub fields: Box<[Name]>, } @@ -484,7 +485,7 @@ pub struct RecordLitField { pub enum Statement { Let { pat: PatId, - type_ref: Option>, + type_ref: Option, initializer: Option, else_branch: Option, }, diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs index 5fba20669323..b9f47ffdd01b 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs @@ -2,22 +2,26 @@ //! be directly created from an ast::TypeRef, without further queries. use core::fmt; -use std::fmt::Write; +use std::{fmt::Write, ops::Index}; use hir_expand::{ db::ExpandDatabase, name::{AsName, Name}, - AstId, + AstId, InFile, }; -use intern::{sym, Interned, Symbol}; +use intern::{sym, Symbol}; +use la_arena::{Arena, ArenaMap, Idx}; use span::Edition; -use syntax::ast::{self, HasGenericArgs, HasName, IsString}; +use syntax::{ + ast::{self, HasGenericArgs, HasName, IsString}, + AstPtr, +}; use crate::{ builtin_type::{BuiltinInt, BuiltinType, BuiltinUint}, hir::Literal, lower::LowerCtx, - path::Path, + path::{GenericArg, Path}, }; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] @@ -105,34 +109,69 @@ impl TraitRef { } /// Compare ty::Ty -/// -/// Note: Most users of `TypeRef` that end up in the salsa database intern it using -/// `Interned` to save space. But notably, nested `TypeRef`s are not interned, since that -/// does not seem to save any noticeable amount of memory. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum TypeRef { Never, Placeholder, - Tuple(Vec), + Tuple(Vec), Path(Path), - RawPtr(Box, Mutability), - Reference(Box, Option, Mutability), - // FIXME: This should be Array(Box, Ast), - Array(Box, ConstRef), - Slice(Box), + RawPtr(TypeRefId, Mutability), + Reference(TypeRefId, Option, Mutability), + // FIXME: This should be Array(TypeRefId, Ast), + Array(TypeRefId, ConstRef), + Slice(TypeRefId), /// A fn pointer. Last element of the vector is the return type. - Fn( - Box<[(Option, TypeRef)]>, - bool, /*varargs*/ - bool, /*is_unsafe*/ - Option, /* abi */ - ), - ImplTrait(Vec>), - DynTrait(Vec>), + Fn { + params: Box<[(Option, TypeRefId)]>, + is_varargs: bool, + is_unsafe: bool, + abi: Option, + }, + ImplTrait(Vec), + DynTrait(Vec), Macro(AstId), Error, } +pub type TypeRefId = Idx; + +#[derive(Default, Clone, PartialEq, Eq, Debug, Hash)] +pub struct TypesMap { + pub(crate) types: Arena, +} + +impl TypesMap { + pub const EMPTY: &TypesMap = &TypesMap { types: Arena::new() }; + + pub(crate) fn shrink_to_fit(&mut self) { + let TypesMap { types } = self; + types.shrink_to_fit(); + } +} + +impl Index for TypesMap { + type Output = TypeRef; + + fn index(&self, index: TypeRefId) -> &Self::Output { + &self.types[index] + } +} + +pub type TypePtr = AstPtr; +pub type TypeSource = InFile; + +#[derive(Default, Clone, PartialEq, Eq, Debug, Hash)] +pub struct TypesSourceMap { + pub(crate) types_map_back: ArenaMap, +} + +impl TypesSourceMap { + pub(crate) fn shrink_to_fit(&mut self) { + let TypesSourceMap { types_map_back } = self; + types_map_back.shrink_to_fit(); + } +} + #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct LifetimeRef { pub name: Name, @@ -162,7 +201,7 @@ pub enum TypeBound { } #[cfg(target_pointer_width = "64")] -const _: [(); 56] = [(); ::std::mem::size_of::()]; +const _: [(); 48] = [(); ::std::mem::size_of::()]; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum UseArgRef { @@ -172,7 +211,7 @@ pub enum UseArgRef { /// A modifier on a bound, currently this is only used for `?Sized`, where the /// modifier is `Maybe`. -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum TraitBoundModifier { None, Maybe, @@ -180,9 +219,9 @@ pub enum TraitBoundModifier { impl TypeRef { /// Converts an `ast::TypeRef` to a `hir::TypeRef`. - pub fn from_ast(ctx: &LowerCtx<'_>, node: ast::Type) -> Self { - match node { - ast::Type::ParenType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()), + pub fn from_ast(ctx: &LowerCtx<'_>, node: ast::Type) -> TypeRefId { + let ty = match &node { + ast::Type::ParenType(inner) => return TypeRef::from_ast_opt(ctx, inner.ty()), ast::Type::TupleType(inner) => { TypeRef::Tuple(inner.fields().map(|it| TypeRef::from_ast(ctx, it)).collect()) } @@ -198,20 +237,18 @@ impl TypeRef { ast::Type::PtrType(inner) => { let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty()); let mutability = Mutability::from_mutable(inner.mut_token().is_some()); - TypeRef::RawPtr(Box::new(inner_ty), mutability) + TypeRef::RawPtr(inner_ty, mutability) } ast::Type::ArrayType(inner) => { let len = ConstRef::from_const_arg(ctx, inner.const_arg()); - TypeRef::Array(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())), len) - } - ast::Type::SliceType(inner) => { - TypeRef::Slice(Box::new(TypeRef::from_ast_opt(ctx, inner.ty()))) + TypeRef::Array(TypeRef::from_ast_opt(ctx, inner.ty()), len) } + ast::Type::SliceType(inner) => TypeRef::Slice(TypeRef::from_ast_opt(ctx, inner.ty())), ast::Type::RefType(inner) => { let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty()); let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(<)); let mutability = Mutability::from_mutable(inner.mut_token().is_some()); - TypeRef::Reference(Box::new(inner_ty), lifetime, mutability) + TypeRef::Reference(inner_ty, lifetime, mutability) } ast::Type::InferType(_inner) => TypeRef::Placeholder, ast::Type::FnPtrType(inner) => { @@ -219,7 +256,7 @@ impl TypeRef { .ret_type() .and_then(|rt| rt.ty()) .map(|it| TypeRef::from_ast(ctx, it)) - .unwrap_or_else(|| TypeRef::Tuple(Vec::new())); + .unwrap_or_else(|| ctx.alloc_type_ref_desugared(TypeRef::Tuple(Vec::new()))); let mut is_varargs = false; let mut params = if let Some(pl) = inner.param_list() { if let Some(param) = pl.params().last() { @@ -251,10 +288,15 @@ impl TypeRef { let abi = inner.abi().map(lower_abi); params.push((None, ret_ty)); - TypeRef::Fn(params.into(), is_varargs, inner.unsafe_token().is_some(), abi) + TypeRef::Fn { + params: params.into(), + is_varargs, + is_unsafe: inner.unsafe_token().is_some(), + abi, + } } // for types are close enough for our purposes to the inner type for now... - ast::Type::ForType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()), + ast::Type::ForType(inner) => return TypeRef::from_ast_opt(ctx, inner.ty()), ast::Type::ImplTraitType(inner) => { if ctx.outer_impl_trait() { // Disallow nested impl traits @@ -271,13 +313,14 @@ impl TypeRef { Some(mc) => TypeRef::Macro(ctx.ast_id(&mc)), None => TypeRef::Error, }, - } + }; + ctx.alloc_type_ref(ty, AstPtr::new(&node)) } - pub(crate) fn from_ast_opt(ctx: &LowerCtx<'_>, node: Option) -> Self { + pub(crate) fn from_ast_opt(ctx: &LowerCtx<'_>, node: Option) -> TypeRefId { match node { Some(node) => TypeRef::from_ast(ctx, node), - None => TypeRef::Error, + None => ctx.alloc_error_type(), } } @@ -285,58 +328,58 @@ impl TypeRef { TypeRef::Tuple(Vec::new()) } - pub fn walk(&self, f: &mut impl FnMut(&TypeRef)) { - go(self, f); + pub fn walk(this: TypeRefId, map: &TypesMap, f: &mut impl FnMut(&TypeRef)) { + go(this, f, map); - fn go(type_ref: &TypeRef, f: &mut impl FnMut(&TypeRef)) { + fn go(type_ref: TypeRefId, f: &mut impl FnMut(&TypeRef), map: &TypesMap) { + let type_ref = &map[type_ref]; f(type_ref); match type_ref { - TypeRef::Fn(params, _, _, _) => { - params.iter().for_each(|(_, param_type)| go(param_type, f)) + TypeRef::Fn { params, is_varargs: _, is_unsafe: _, abi: _ } => { + params.iter().for_each(|&(_, param_type)| go(param_type, f, map)) } - TypeRef::Tuple(types) => types.iter().for_each(|t| go(t, f)), + TypeRef::Tuple(types) => types.iter().for_each(|&t| go(t, f, map)), TypeRef::RawPtr(type_ref, _) | TypeRef::Reference(type_ref, ..) | TypeRef::Array(type_ref, _) - | TypeRef::Slice(type_ref) => go(type_ref, f), + | TypeRef::Slice(type_ref) => go(*type_ref, f, map), TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => { for bound in bounds { - match bound.as_ref() { + match bound { TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => { - go_path(path, f) + go_path(path, f, map) } TypeBound::Lifetime(_) | TypeBound::Error | TypeBound::Use(_) => (), } } } - TypeRef::Path(path) => go_path(path, f), + TypeRef::Path(path) => go_path(path, f, map), TypeRef::Never | TypeRef::Placeholder | TypeRef::Macro(_) | TypeRef::Error => {} }; } - fn go_path(path: &Path, f: &mut impl FnMut(&TypeRef)) { + fn go_path(path: &Path, f: &mut impl FnMut(&TypeRef), map: &TypesMap) { if let Some(type_ref) = path.type_anchor() { - go(type_ref, f); + go(type_ref, f, map); } for segment in path.segments().iter() { if let Some(args_and_bindings) = segment.args_and_bindings { for arg in args_and_bindings.args.iter() { match arg { - crate::path::GenericArg::Type(type_ref) => { - go(type_ref, f); + GenericArg::Type(type_ref) => { + go(*type_ref, f, map); } - crate::path::GenericArg::Const(_) - | crate::path::GenericArg::Lifetime(_) => {} + GenericArg::Const(_) | GenericArg::Lifetime(_) => {} } } for binding in args_and_bindings.bindings.iter() { - if let Some(type_ref) = &binding.type_ref { - go(type_ref, f); + if let Some(type_ref) = binding.type_ref { + go(type_ref, f, map); } for bound in binding.bounds.iter() { - match bound.as_ref() { + match bound { TypeBound::Path(path, _) | TypeBound::ForLifetime(_, path) => { - go_path(path, f) + go_path(path, f, map) } TypeBound::Lifetime(_) | TypeBound::Error | TypeBound::Use(_) => (), } @@ -351,9 +394,9 @@ impl TypeRef { pub(crate) fn type_bounds_from_ast( lower_ctx: &LowerCtx<'_>, type_bounds_opt: Option, -) -> Vec> { +) -> Vec { if let Some(type_bounds) = type_bounds_opt { - type_bounds.bounds().map(|it| Interned::new(TypeBound::from_ast(lower_ctx, it))).collect() + type_bounds.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)).collect() } else { vec![] } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs index 91a8cbab1a29..74500fd76e6d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs @@ -61,7 +61,7 @@ use crate::{ db::DefDatabase, generics::GenericParams, path::{GenericArgs, ImportAlias, ModPath, Path, PathKind}, - type_ref::{Mutability, TraitRef, TypeBound, TypeRef}, + type_ref::{Mutability, TraitRef, TypeBound, TypeRefId, TypesMap, TypesSourceMap}, visibility::{RawVisibility, VisibilityExplicitness}, BlockId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, }; @@ -100,13 +100,20 @@ pub struct ItemTree { impl ItemTree { pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc { + db.file_item_tree_with_source_map(file_id).0 + } + + pub(crate) fn file_item_tree_with_source_map_query( + db: &dyn DefDatabase, + file_id: HirFileId, + ) -> (Arc, Arc) { let _p = tracing::info_span!("file_item_tree_query", ?file_id).entered(); - static EMPTY: OnceLock> = OnceLock::new(); + static EMPTY: OnceLock<(Arc, Arc)> = OnceLock::new(); let ctx = lower::Ctx::new(db, file_id); let syntax = db.parse_or_expand(file_id); let mut top_attrs = None; - let mut item_tree = match_ast! { + let (mut item_tree, mut source_maps) = match_ast! { match syntax { ast::SourceFile(file) => { top_attrs = Some(RawAttrs::new(db.upcast(), &file, ctx.span_map())); @@ -136,42 +143,57 @@ impl ItemTree { { EMPTY .get_or_init(|| { - Arc::new(ItemTree { - top_level: SmallVec::new_const(), - attrs: FxHashMap::default(), - data: None, - }) + ( + Arc::new(ItemTree { + top_level: SmallVec::new_const(), + attrs: FxHashMap::default(), + data: None, + }), + Arc::default(), + ) }) .clone() } else { item_tree.shrink_to_fit(); - Arc::new(item_tree) + source_maps.shrink_to_fit(); + (Arc::new(item_tree), Arc::new(source_maps)) } } pub(crate) fn block_item_tree_query(db: &dyn DefDatabase, block: BlockId) -> Arc { + db.block_item_tree_with_source_map(block).0 + } + + pub(crate) fn block_item_tree_with_source_map_query( + db: &dyn DefDatabase, + block: BlockId, + ) -> (Arc, Arc) { let _p = tracing::info_span!("block_item_tree_query", ?block).entered(); - static EMPTY: OnceLock> = OnceLock::new(); + static EMPTY: OnceLock<(Arc, Arc)> = OnceLock::new(); let loc = block.lookup(db); let block = loc.ast_id.to_node(db.upcast()); let ctx = lower::Ctx::new(db, loc.ast_id.file_id); - let mut item_tree = ctx.lower_block(&block); + let (mut item_tree, mut source_maps) = ctx.lower_block(&block); if item_tree.data.is_none() && item_tree.top_level.is_empty() && item_tree.attrs.is_empty() { EMPTY .get_or_init(|| { - Arc::new(ItemTree { - top_level: SmallVec::new_const(), - attrs: FxHashMap::default(), - data: None, - }) + ( + Arc::new(ItemTree { + top_level: SmallVec::new_const(), + attrs: FxHashMap::default(), + data: None, + }), + Arc::default(), + ) }) .clone() } else { item_tree.shrink_to_fit(); - Arc::new(item_tree) + source_maps.shrink_to_fit(); + (Arc::new(item_tree), Arc::new(source_maps)) } } @@ -308,6 +330,82 @@ struct ItemTreeData { vis: ItemVisibilities, } +#[derive(Default, Debug, Eq, PartialEq)] +pub struct GenericItemSourceMap { + pub item: TypesSourceMap, + pub generics: TypesSourceMap, +} + +#[derive(Default, Debug, Eq, PartialEq)] +pub struct ItemTreeSourceMaps { + functions: Vec, + structs: Vec, + unions: Vec, + enum_generics: Vec, + variants: Vec, + consts: Vec, + statics: Vec, + trait_generics: Vec, + trait_alias_generics: Vec, + impls: Vec, + type_aliases: Vec, +} + +impl ItemTreeSourceMaps { + fn shrink_to_fit(&mut self) { + let ItemTreeSourceMaps { + functions, + structs, + unions, + enum_generics, + variants, + consts, + statics, + trait_generics, + trait_alias_generics, + impls, + type_aliases, + } = self; + functions.shrink_to_fit(); + structs.shrink_to_fit(); + unions.shrink_to_fit(); + enum_generics.shrink_to_fit(); + variants.shrink_to_fit(); + consts.shrink_to_fit(); + statics.shrink_to_fit(); + trait_generics.shrink_to_fit(); + trait_alias_generics.shrink_to_fit(); + impls.shrink_to_fit(); + type_aliases.shrink_to_fit(); + } +} + +macro_rules! index_source_maps { + ( $( $field:ident[$tree_id:ident] = $result:ident, )* ) => { + $( + impl Index> for ItemTreeSourceMaps { + type Output = $result; + fn index(&self, index: FileItemTreeId<$tree_id>) -> &Self::Output { + &self.$field[index.0.into_raw().into_u32() as usize] + } + } + )* + }; +} +index_source_maps! { + functions[Function] = GenericItemSourceMap, + structs[Struct] = GenericItemSourceMap, + unions[Union] = GenericItemSourceMap, + enum_generics[Enum] = TypesSourceMap, + variants[Variant] = TypesSourceMap, + consts[Const] = TypesSourceMap, + statics[Static] = TypesSourceMap, + trait_generics[Trait] = TypesSourceMap, + trait_alias_generics[TraitAlias] = TypesSourceMap, + impls[Impl] = GenericItemSourceMap, + type_aliases[TypeAlias] = GenericItemSourceMap, +} + #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum AttrOwner { /// Attributes on an item. @@ -363,7 +461,7 @@ pub trait ItemTreeNode: Clone { fn attr_owner(id: FileItemTreeId) -> AttrOwner; } pub trait GenericsItemTreeNode: ItemTreeNode { - fn generic_params(&self) -> &Interned; + fn generic_params(&self) -> &Arc; } pub struct FileItemTreeId(Idx); @@ -428,6 +526,16 @@ impl TreeId { } } + pub fn item_tree_with_source_map( + &self, + db: &dyn DefDatabase, + ) -> (Arc, Arc) { + match self.block { + Some(block) => db.block_item_tree_with_source_map(block), + None => db.file_item_tree_with_source_map(self.file), + } + } + pub fn file_id(self) -> HirFileId { self.file } @@ -460,6 +568,13 @@ impl ItemTreeId { self.tree.item_tree(db) } + pub fn item_tree_with_source_map( + self, + db: &dyn DefDatabase, + ) -> (Arc, Arc) { + self.tree.item_tree_with_source_map(db) + } + pub fn resolved(self, db: &dyn DefDatabase, cb: impl FnOnce(&N) -> R) -> R where ItemTree: Index, Output = N>, @@ -592,7 +707,7 @@ macro_rules! mod_items { $( impl GenericsItemTreeNode for $typ { - fn generic_params(&self) -> &Interned { + fn generic_params(&self) -> &Arc { &self.$generic_params } } @@ -730,17 +845,18 @@ pub struct ExternBlock { pub struct Function { pub name: Name, pub visibility: RawVisibilityId, - pub explicit_generic_params: Interned, + pub explicit_generic_params: Arc, pub abi: Option, pub params: Box<[Param]>, - pub ret_type: Interned, + pub ret_type: TypeRefId, pub ast_id: FileAstId, + pub types_map: Arc, pub(crate) flags: FnFlags, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Param { - pub type_ref: Option>, + pub type_ref: Option, } bitflags::bitflags! { @@ -761,26 +877,28 @@ bitflags::bitflags! { pub struct Struct { pub name: Name, pub visibility: RawVisibilityId, - pub generic_params: Interned, + pub generic_params: Arc, pub fields: Box<[Field]>, pub shape: FieldsShape, pub ast_id: FileAstId, + pub types_map: Arc, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Union { pub name: Name, pub visibility: RawVisibilityId, - pub generic_params: Interned, + pub generic_params: Arc, pub fields: Box<[Field]>, pub ast_id: FileAstId, + pub types_map: Arc, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Enum { pub name: Name, pub visibility: RawVisibilityId, - pub generic_params: Interned, + pub generic_params: Arc, pub variants: Range>, pub ast_id: FileAstId, } @@ -791,6 +909,7 @@ pub struct Variant { pub fields: Box<[Field]>, pub shape: FieldsShape, pub ast_id: FileAstId, + pub types_map: Arc, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -804,7 +923,7 @@ pub enum FieldsShape { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Field { pub name: Name, - pub type_ref: Interned, + pub type_ref: TypeRefId, pub visibility: RawVisibilityId, } @@ -813,9 +932,10 @@ pub struct Const { /// `None` for `const _: () = ();` pub name: Option, pub visibility: RawVisibilityId, - pub type_ref: Interned, + pub type_ref: TypeRefId, pub ast_id: FileAstId, pub has_body: bool, + pub types_map: Arc, } #[derive(Debug, Clone, Eq, PartialEq)] @@ -826,15 +946,16 @@ pub struct Static { pub mutable: bool, pub has_safe_kw: bool, pub has_unsafe_kw: bool, - pub type_ref: Interned, + pub type_ref: TypeRefId, pub ast_id: FileAstId, + pub types_map: Arc, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Trait { pub name: Name, pub visibility: RawVisibilityId, - pub generic_params: Interned, + pub generic_params: Arc, pub is_auto: bool, pub is_unsafe: bool, pub items: Box<[AssocItem]>, @@ -845,19 +966,20 @@ pub struct Trait { pub struct TraitAlias { pub name: Name, pub visibility: RawVisibilityId, - pub generic_params: Interned, + pub generic_params: Arc, pub ast_id: FileAstId, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Impl { - pub generic_params: Interned, - pub target_trait: Option>, - pub self_ty: Interned, + pub generic_params: Arc, + pub target_trait: Option, + pub self_ty: TypeRefId, pub is_negative: bool, pub is_unsafe: bool, pub items: Box<[AssocItem]>, pub ast_id: FileAstId, + pub types_map: Arc, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -865,10 +987,11 @@ pub struct TypeAlias { pub name: Name, pub visibility: RawVisibilityId, /// Bounds on the type alias itself. Only valid in trait declarations, eg. `type Assoc: Copy;`. - pub bounds: Box<[Interned]>, - pub generic_params: Interned, - pub type_ref: Option>, + pub bounds: Box<[TypeBound]>, + pub generic_params: Arc, + pub type_ref: Option, pub ast_id: FileAstId, + pub types_map: Arc, } #[derive(Debug, Clone, Eq, PartialEq)] diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index 431a7f66f405..c42c849c3b9b 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -1,8 +1,13 @@ //! AST -> `ItemTree` lowering code. -use std::collections::hash_map::Entry; +use std::{cell::OnceCell, collections::hash_map::Entry}; -use hir_expand::{mod_path::path, name::AsName, span_map::SpanMapRef, HirFileId}; +use hir_expand::{ + mod_path::path, + name::AsName, + span_map::{SpanMap, SpanMapRef}, + HirFileId, +}; use intern::{sym, Symbol}; use la_arena::Arena; use rustc_hash::FxHashMap; @@ -18,14 +23,18 @@ use crate::{ generics::{GenericParams, GenericParamsCollector, TypeParamData, TypeParamProvenance}, item_tree::{ AssocItem, AttrOwner, Const, Either, Enum, ExternBlock, ExternCrate, Field, FieldParent, - FieldsShape, FileItemTreeId, FnFlags, Function, GenericArgs, GenericModItem, Idx, Impl, - ImportAlias, Interned, ItemTree, ItemTreeData, Macro2, MacroCall, MacroRules, Mod, ModItem, - ModKind, ModPath, Mutability, Name, Param, Path, Range, RawAttrs, RawIdx, RawVisibilityId, - Static, Struct, StructKind, Trait, TraitAlias, TypeAlias, Union, Use, UseTree, UseTreeKind, - Variant, + FieldsShape, FileItemTreeId, FnFlags, Function, GenericArgs, GenericItemSourceMap, + GenericModItem, Idx, Impl, ImportAlias, Interned, ItemTree, ItemTreeData, + ItemTreeSourceMaps, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, ModPath, + Mutability, Name, Param, Path, Range, RawAttrs, RawIdx, RawVisibilityId, Static, Struct, + StructKind, Trait, TraitAlias, TypeAlias, Union, Use, UseTree, UseTreeKind, Variant, }, + lower::LowerCtx, path::AssociatedTypeBinding, - type_ref::{LifetimeRef, TraitBoundModifier, TraitRef, TypeBound, TypeRef}, + type_ref::{ + LifetimeRef, TraitBoundModifier, TraitRef, TypeBound, TypeRef, TypeRefId, TypesMap, + TypesSourceMap, + }, visibility::RawVisibility, LocalLifetimeParamId, LocalTypeOrConstParamId, }; @@ -40,7 +49,9 @@ pub(super) struct Ctx<'a> { source_ast_id_map: Arc, generic_param_attr_buffer: FxHashMap, RawAttrs>, - body_ctx: crate::lower::LowerCtx<'a>, + span_map: OnceCell, + file: HirFileId, + source_maps: ItemTreeSourceMaps, } impl<'a> Ctx<'a> { @@ -50,22 +61,49 @@ impl<'a> Ctx<'a> { tree: ItemTree::default(), generic_param_attr_buffer: FxHashMap::default(), source_ast_id_map: db.ast_id_map(file), - body_ctx: crate::lower::LowerCtx::new(db, file), + file, + span_map: OnceCell::new(), + source_maps: ItemTreeSourceMaps::default(), } } pub(super) fn span_map(&self) -> SpanMapRef<'_> { - self.body_ctx.span_map() + self.span_map.get_or_init(|| self.db.span_map(self.file)).as_ref() } - pub(super) fn lower_module_items(mut self, item_owner: &dyn HasModuleItem) -> ItemTree { + fn body_ctx<'b, 'c>( + &self, + types_map: &'b mut TypesMap, + types_source_map: &'b mut TypesSourceMap, + ) -> LowerCtx<'c> + where + 'a: 'c, + 'b: 'c, + { + // FIXME: This seems a bit wasteful that if `LowerCtx` will initialize the span map we won't benefit. + LowerCtx::with_span_map_cell( + self.db, + self.file, + self.span_map.clone(), + types_map, + types_source_map, + ) + } + + pub(super) fn lower_module_items( + mut self, + item_owner: &dyn HasModuleItem, + ) -> (ItemTree, ItemTreeSourceMaps) { self.tree.top_level = item_owner.items().flat_map(|item| self.lower_mod_item(&item)).collect(); assert!(self.generic_param_attr_buffer.is_empty()); - self.tree + (self.tree, self.source_maps) } - pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree { + pub(super) fn lower_macro_stmts( + mut self, + stmts: ast::MacroStmts, + ) -> (ItemTree, ItemTreeSourceMaps) { self.tree.top_level = stmts .statements() .filter_map(|stmt| { @@ -96,10 +134,10 @@ impl<'a> Ctx<'a> { } assert!(self.generic_param_attr_buffer.is_empty()); - self.tree + (self.tree, self.source_maps) } - pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> ItemTree { + pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> (ItemTree, ItemTreeSourceMaps) { self.tree .attrs .insert(AttrOwner::TopLevel, RawAttrs::new(self.db.upcast(), block, self.span_map())); @@ -125,7 +163,7 @@ impl<'a> Ctx<'a> { } assert!(self.generic_param_attr_buffer.is_empty()); - self.tree + (self.tree, self.source_maps) } fn data(&mut self) -> &mut ItemTreeData { @@ -144,7 +182,7 @@ impl<'a> Ctx<'a> { ast::Item::Module(ast) => self.lower_module(ast)?.into(), ast::Item::Trait(ast) => self.lower_trait(ast)?.into(), ast::Item::TraitAlias(ast) => self.lower_trait_alias(ast)?.into(), - ast::Item::Impl(ast) => self.lower_impl(ast)?.into(), + ast::Item::Impl(ast) => self.lower_impl(ast).into(), ast::Item::Use(ast) => self.lower_use(ast)?.into(), ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?.into(), ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?.into(), @@ -190,13 +228,30 @@ impl<'a> Ctx<'a> { } fn lower_struct(&mut self, strukt: &ast::Struct) -> Option> { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); let visibility = self.lower_visibility(strukt); let name = strukt.name()?.as_name(); let ast_id = self.source_ast_id_map.ast_id(strukt); - let (fields, kind, attrs) = self.lower_fields(&strukt.kind()); - let generic_params = self.lower_generic_params(HasImplicitSelf::No, strukt); - let res = Struct { name, visibility, generic_params, fields, shape: kind, ast_id }; + let (fields, kind, attrs) = self.lower_fields(&strukt.kind(), &body_ctx); + let (generic_params, generics_source_map) = + self.lower_generic_params(HasImplicitSelf::No, strukt); + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = Struct { + name, + visibility, + generic_params, + fields, + shape: kind, + ast_id, + types_map: Arc::new(types_map), + }; let id = id(self.data().structs.alloc(res)); + self.source_maps + .structs + .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); for (idx, attr) in attrs { self.add_attrs( AttrOwner::Field( @@ -213,6 +268,7 @@ impl<'a> Ctx<'a> { fn lower_fields( &mut self, strukt_kind: &ast::StructKind, + body_ctx: &LowerCtx<'_>, ) -> (Box<[Field]>, FieldsShape, Vec<(usize, RawAttrs)>) { match strukt_kind { ast::StructKind::Record(it) => { @@ -220,7 +276,7 @@ impl<'a> Ctx<'a> { let mut attrs = vec![]; for (i, field) in it.fields().enumerate() { - let data = self.lower_record_field(&field); + let data = self.lower_record_field(&field, body_ctx); fields.push(data); let attr = RawAttrs::new(self.db.upcast(), &field, self.span_map()); if !attr.is_empty() { @@ -234,7 +290,7 @@ impl<'a> Ctx<'a> { let mut attrs = vec![]; for (i, field) in it.fields().enumerate() { - let data = self.lower_tuple_field(i, &field); + let data = self.lower_tuple_field(i, &field, body_ctx); fields.push(data); let attr = RawAttrs::new(self.db.upcast(), &field, self.span_map()); if !attr.is_empty() { @@ -247,35 +303,58 @@ impl<'a> Ctx<'a> { } } - fn lower_record_field(&mut self, field: &ast::RecordField) -> Field { + fn lower_record_field(&mut self, field: &ast::RecordField, body_ctx: &LowerCtx<'_>) -> Field { let name = match field.name() { Some(name) => name.as_name(), None => Name::missing(), }; let visibility = self.lower_visibility(field); - let type_ref = self.lower_type_ref_opt(field.ty()); + let type_ref = TypeRef::from_ast_opt(body_ctx, field.ty()); Field { name, type_ref, visibility } } - fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field { + fn lower_tuple_field( + &mut self, + idx: usize, + field: &ast::TupleField, + body_ctx: &LowerCtx<'_>, + ) -> Field { let name = Name::new_tuple_field(idx); let visibility = self.lower_visibility(field); - let type_ref = self.lower_type_ref_opt(field.ty()); + let type_ref = TypeRef::from_ast_opt(body_ctx, field.ty()); Field { name, type_ref, visibility } } fn lower_union(&mut self, union: &ast::Union) -> Option> { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); let visibility = self.lower_visibility(union); let name = union.name()?.as_name(); let ast_id = self.source_ast_id_map.ast_id(union); let (fields, _, attrs) = match union.record_field_list() { - Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)), + Some(record_field_list) => { + self.lower_fields(&StructKind::Record(record_field_list), &body_ctx) + } None => (Box::default(), FieldsShape::Record, Vec::default()), }; - let generic_params = self.lower_generic_params(HasImplicitSelf::No, union); - let res = Union { name, visibility, generic_params, fields, ast_id }; + let (generic_params, generics_source_map) = + self.lower_generic_params(HasImplicitSelf::No, union); + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = Union { + name, + visibility, + generic_params, + fields, + ast_id, + types_map: Arc::new(types_map), + }; let id = id(self.data().unions.alloc(res)); + self.source_maps + .unions + .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); for (idx, attr) in attrs { self.add_attrs( AttrOwner::Field( @@ -299,9 +378,11 @@ impl<'a> Ctx<'a> { FileItemTreeId(self.next_variant_idx())..FileItemTreeId(self.next_variant_idx()) } }; - let generic_params = self.lower_generic_params(HasImplicitSelf::No, enum_); + let (generic_params, generics_source_map) = + self.lower_generic_params(HasImplicitSelf::No, enum_); let res = Enum { name, visibility, generic_params, variants, ast_id }; let id = id(self.data().enums.alloc(res)); + self.source_maps.enum_generics.push(generics_source_map); self.write_generic_params_attributes(id.into()); Some(id) } @@ -320,14 +401,20 @@ impl<'a> Ctx<'a> { } fn lower_variant(&mut self, variant: &ast::Variant) -> Idx { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); let name = match variant.name() { Some(name) => name.as_name(), None => Name::missing(), }; - let (fields, kind, attrs) = self.lower_fields(&variant.kind()); + let (fields, kind, attrs) = self.lower_fields(&variant.kind(), &body_ctx); let ast_id = self.source_ast_id_map.ast_id(variant); - let res = Variant { name, fields, shape: kind, ast_id }; + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = Variant { name, fields, shape: kind, ast_id, types_map: Arc::new(types_map) }; let id = self.data().variants.alloc(res); + self.source_maps.variants.push(types_source_map); for (idx, attr) in attrs { self.add_attrs( AttrOwner::Field( @@ -341,6 +428,10 @@ impl<'a> Ctx<'a> { } fn lower_function(&mut self, func: &ast::Fn) -> Option> { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); + let visibility = self.lower_visibility(func); let name = func.name()?.as_name(); @@ -360,27 +451,31 @@ impl<'a> Ctx<'a> { RawAttrs::new(self.db.upcast(), &self_param, self.span_map()), ); let self_type = match self_param.ty() { - Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref), + Some(type_ref) => TypeRef::from_ast(&body_ctx, type_ref), None => { - let self_type = - TypeRef::Path(Name::new_symbol_root(sym::Self_.clone()).into()); + let self_type = body_ctx.alloc_type_ref_desugared(TypeRef::Path( + Name::new_symbol_root(sym::Self_.clone()).into(), + )); match self_param.kind() { ast::SelfParamKind::Owned => self_type, - ast::SelfParamKind::Ref => TypeRef::Reference( - Box::new(self_type), - self_param.lifetime().as_ref().map(LifetimeRef::new), - Mutability::Shared, - ), - ast::SelfParamKind::MutRef => TypeRef::Reference( - Box::new(self_type), - self_param.lifetime().as_ref().map(LifetimeRef::new), - Mutability::Mut, - ), + ast::SelfParamKind::Ref => { + body_ctx.alloc_type_ref_desugared(TypeRef::Reference( + self_type, + self_param.lifetime().as_ref().map(LifetimeRef::new), + Mutability::Shared, + )) + } + ast::SelfParamKind::MutRef => { + body_ctx.alloc_type_ref_desugared(TypeRef::Reference( + self_type, + self_param.lifetime().as_ref().map(LifetimeRef::new), + Mutability::Mut, + )) + } } } }; - let type_ref = Interned::new(self_type); - params.push(Param { type_ref: Some(type_ref) }); + params.push(Param { type_ref: Some(self_type) }); has_self_param = true; } for param in param_list.params() { @@ -391,9 +486,8 @@ impl<'a> Ctx<'a> { Param { type_ref: None } } None => { - let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty()); - let ty = Interned::new(type_ref); - Param { type_ref: Some(ty) } + let type_ref = TypeRef::from_ast_opt(&body_ctx, param.ty()); + Param { type_ref: Some(type_ref) } } }; params.push(param); @@ -402,17 +496,17 @@ impl<'a> Ctx<'a> { let ret_type = match func.ret_type() { Some(rt) => match rt.ty() { - Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref), - None if rt.thin_arrow_token().is_some() => TypeRef::Error, - None => TypeRef::unit(), + Some(type_ref) => TypeRef::from_ast(&body_ctx, type_ref), + None if rt.thin_arrow_token().is_some() => body_ctx.alloc_error_type(), + None => body_ctx.alloc_type_ref_desugared(TypeRef::unit()), }, - None => TypeRef::unit(), + None => body_ctx.alloc_type_ref_desugared(TypeRef::unit()), }; let ret_type = if func.async_token().is_some() { let future_impl = desugar_future_path(ret_type); - let ty_bound = Interned::new(TypeBound::Path(future_impl, TraitBoundModifier::None)); - TypeRef::ImplTrait(vec![ty_bound]) + let ty_bound = TypeBound::Path(future_impl, TraitBoundModifier::None); + body_ctx.alloc_type_ref_desugared(TypeRef::ImplTrait(vec![ty_bound])) } else { ret_type }; @@ -447,18 +541,26 @@ impl<'a> Ctx<'a> { flags |= FnFlags::IS_VARARGS; } + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let (generic_params, generics_source_map) = + self.lower_generic_params(HasImplicitSelf::No, func); let res = Function { name, visibility, - explicit_generic_params: self.lower_generic_params(HasImplicitSelf::No, func), + explicit_generic_params: generic_params, abi, params: params.into_boxed_slice(), - ret_type: Interned::new(ret_type), + ret_type, ast_id, + types_map: Arc::new(types_map), flags, }; let id = id(self.data().functions.alloc(res)); + self.source_maps + .functions + .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); for (idx, attr) in attrs { self.add_attrs(AttrOwner::Param(id, Idx::from_raw(RawIdx::from_u32(idx as u32))), attr); } @@ -470,37 +572,81 @@ impl<'a> Ctx<'a> { &mut self, type_alias: &ast::TypeAlias, ) -> Option> { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); let name = type_alias.name()?.as_name(); - let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it)); + let type_ref = type_alias.ty().map(|it| TypeRef::from_ast(&body_ctx, it)); let visibility = self.lower_visibility(type_alias); - let bounds = self.lower_type_bounds(type_alias); + let bounds = self.lower_type_bounds(type_alias, &body_ctx); let ast_id = self.source_ast_id_map.ast_id(type_alias); - let generic_params = self.lower_generic_params(HasImplicitSelf::No, type_alias); - let res = TypeAlias { name, visibility, bounds, generic_params, type_ref, ast_id }; + let (generic_params, generics_source_map) = + self.lower_generic_params(HasImplicitSelf::No, type_alias); + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = TypeAlias { + name, + visibility, + bounds, + generic_params, + type_ref, + ast_id, + types_map: Arc::new(types_map), + }; let id = id(self.data().type_aliases.alloc(res)); + self.source_maps + .type_aliases + .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); self.write_generic_params_attributes(id.into()); Some(id) } fn lower_static(&mut self, static_: &ast::Static) -> Option> { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); let name = static_.name()?.as_name(); - let type_ref = self.lower_type_ref_opt(static_.ty()); + let type_ref = TypeRef::from_ast_opt(&body_ctx, static_.ty()); let visibility = self.lower_visibility(static_); let mutable = static_.mut_token().is_some(); let has_safe_kw = static_.safe_token().is_some(); let has_unsafe_kw = static_.unsafe_token().is_some(); let ast_id = self.source_ast_id_map.ast_id(static_); - let res = - Static { name, visibility, mutable, type_ref, ast_id, has_safe_kw, has_unsafe_kw }; + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = Static { + name, + visibility, + mutable, + type_ref, + ast_id, + has_safe_kw, + has_unsafe_kw, + types_map: Arc::new(types_map), + }; + self.source_maps.statics.push(types_source_map); Some(id(self.data().statics.alloc(res))) } fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); let name = konst.name().map(|it| it.as_name()); - let type_ref = self.lower_type_ref_opt(konst.ty()); + let type_ref = TypeRef::from_ast_opt(&body_ctx, konst.ty()); let visibility = self.lower_visibility(konst); let ast_id = self.source_ast_id_map.ast_id(konst); - let res = Const { name, visibility, type_ref, ast_id, has_body: konst.body().is_some() }; + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = Const { + name, + visibility, + type_ref, + ast_id, + has_body: konst.body().is_some(), + types_map: Arc::new(types_map), + }; + self.source_maps.consts.push(types_source_map); id(self.data().consts.alloc(res)) } @@ -539,10 +685,11 @@ impl<'a> Ctx<'a> { .filter_map(|item_node| self.lower_assoc_item(&item_node)) .collect(); - let generic_params = + let (generic_params, generics_source_map) = self.lower_generic_params(HasImplicitSelf::Yes(trait_def.type_bound_list()), trait_def); let def = Trait { name, visibility, generic_params, is_auto, is_unsafe, items, ast_id }; let id = id(self.data().traits.alloc(def)); + self.source_maps.trait_generics.push(generics_source_map); self.write_generic_params_attributes(id.into()); Some(id) } @@ -554,24 +701,29 @@ impl<'a> Ctx<'a> { let name = trait_alias_def.name()?.as_name(); let visibility = self.lower_visibility(trait_alias_def); let ast_id = self.source_ast_id_map.ast_id(trait_alias_def); - let generic_params = self.lower_generic_params( + let (generic_params, generics_source_map) = self.lower_generic_params( HasImplicitSelf::Yes(trait_alias_def.type_bound_list()), trait_alias_def, ); let alias = TraitAlias { name, visibility, generic_params, ast_id }; let id = id(self.data().trait_aliases.alloc(alias)); + self.source_maps.trait_alias_generics.push(generics_source_map); self.write_generic_params_attributes(id.into()); Some(id) } - fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option> { + fn lower_impl(&mut self, impl_def: &ast::Impl) -> FileItemTreeId { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); + let ast_id = self.source_ast_id_map.ast_id(impl_def); // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only // equals itself. - let self_ty = self.lower_type_ref(&impl_def.self_ty()?); - let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr)); + let self_ty = TypeRef::from_ast_opt(&body_ctx, impl_def.self_ty()); + let target_trait = impl_def.trait_().and_then(|tr| TraitRef::from_ast(&body_ctx, tr)); let is_negative = impl_def.excl_token().is_some(); let is_unsafe = impl_def.unsafe_token().is_some(); @@ -584,12 +736,26 @@ impl<'a> Ctx<'a> { .collect(); // Note that trait impls don't get implicit `Self` unlike traits, because here they are a // type alias rather than a type parameter, so this is handled by the resolver. - let generic_params = self.lower_generic_params(HasImplicitSelf::No, impl_def); - let res = - Impl { generic_params, target_trait, self_ty, is_negative, is_unsafe, items, ast_id }; + let (generic_params, generics_source_map) = + self.lower_generic_params(HasImplicitSelf::No, impl_def); + types_map.shrink_to_fit(); + types_source_map.shrink_to_fit(); + let res = Impl { + generic_params, + target_trait, + self_ty, + is_negative, + is_unsafe, + items, + ast_id, + types_map: Arc::new(types_map), + }; let id = id(self.data().impls.alloc(res)); + self.source_maps + .impls + .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); self.write_generic_params_attributes(id.into()); - Some(id) + id } fn lower_use(&mut self, use_item: &ast::Use) -> Option> { @@ -692,14 +858,17 @@ impl<'a> Ctx<'a> { &mut self, has_implicit_self: HasImplicitSelf, node: &dyn ast::HasGenericParams, - ) -> Interned { + ) -> (Arc, TypesSourceMap) { + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let body_ctx = self.body_ctx(&mut types_map, &mut types_source_map); debug_assert!(self.generic_param_attr_buffer.is_empty(),); let add_param_attrs = |item: Either, param| { - let attrs = RawAttrs::new(self.db.upcast(), ¶m, self.body_ctx.span_map()); + let attrs = RawAttrs::new(self.db.upcast(), ¶m, body_ctx.span_map()); debug_assert!(self.generic_param_attr_buffer.insert(item, attrs).is_none()); }; - self.body_ctx.take_impl_traits_bounds(); + body_ctx.take_impl_traits_bounds(); let mut generics = GenericParamsCollector::default(); if let HasImplicitSelf::Yes(bounds) = has_implicit_self { @@ -715,23 +884,29 @@ impl<'a> Ctx<'a> { // add super traits as bounds on Self // i.e., `trait Foo: Bar` is equivalent to `trait Foo where Self: Bar` generics.fill_bounds( - &self.body_ctx, + &body_ctx, bounds, - Either::Left(TypeRef::Path(Name::new_symbol_root(sym::Self_.clone()).into())), + Either::Left(body_ctx.alloc_type_ref_desugared(TypeRef::Path( + Name::new_symbol_root(sym::Self_.clone()).into(), + ))), ); } - generics.fill(&self.body_ctx, node, add_param_attrs); + generics.fill(&body_ctx, node, add_param_attrs); - Interned::new(generics.finish()) + let generics = generics.finish(types_map, &mut types_source_map); + (Arc::new(generics), types_source_map) } - fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Box<[Interned]> { + fn lower_type_bounds( + &mut self, + node: &dyn ast::HasTypeBounds, + body_ctx: &LowerCtx<'_>, + ) -> Box<[TypeBound]> { match node.type_bound_list() { - Some(bound_list) => bound_list - .bounds() - .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it))) - .collect(), + Some(bound_list) => { + bound_list.bounds().map(|it| TypeBound::from_ast(body_ctx, it)).collect() + } None => Box::default(), } } @@ -743,23 +918,6 @@ impl<'a> Ctx<'a> { self.data().vis.alloc(vis) } - fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option> { - let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?; - Some(Interned::new(trait_ref)) - } - - fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned { - let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone()); - Interned::new(tyref) - } - - fn lower_type_ref_opt(&mut self, type_ref: Option) -> Interned { - match type_ref.map(|ty| self.lower_type_ref(&ty)) { - Some(it) => it, - None => Interned::new(TypeRef::Error), - } - } - fn next_variant_idx(&self) -> Idx { Idx::from_raw(RawIdx::from( self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32), @@ -767,7 +925,7 @@ impl<'a> Ctx<'a> { } } -fn desugar_future_path(orig: TypeRef) -> Path { +fn desugar_future_path(orig: TypeRefId) -> Path { let path = path![core::future::Future]; let mut generic_args: Vec<_> = std::iter::repeat(None).take(path.segments().len() - 1).collect(); @@ -777,10 +935,7 @@ fn desugar_future_path(orig: TypeRef) -> Path { type_ref: Some(orig), bounds: Box::default(), }; - generic_args.push(Some(Interned::new(GenericArgs { - bindings: Box::new([binding]), - ..GenericArgs::empty() - }))); + generic_args.push(Some(GenericArgs { bindings: Box::new([binding]), ..GenericArgs::empty() })); Path::from_known_path(path, generic_args) } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs index 9dce28b2e492..b6816a1f9684 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/pretty.rs @@ -10,11 +10,12 @@ use crate::{ item_tree::{ AttrOwner, Const, DefDatabase, Enum, ExternBlock, ExternCrate, Field, FieldParent, FieldsShape, FileItemTreeId, FnFlags, Function, GenericModItem, GenericParams, Impl, - Interned, ItemTree, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, Param, Path, - RawAttrs, RawVisibilityId, Static, Struct, Trait, TraitAlias, TypeAlias, TypeBound, - TypeRef, Union, Use, UseTree, UseTreeKind, Variant, + ItemTree, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, Param, Path, RawAttrs, + RawVisibilityId, Static, Struct, Trait, TraitAlias, TypeAlias, TypeBound, Union, Use, + UseTree, UseTreeKind, Variant, }, pretty::{print_path, print_type_bounds, print_type_ref}, + type_ref::{TypeRefId, TypesMap}, visibility::RawVisibility, }; @@ -121,7 +122,13 @@ impl Printer<'_> { }; } - fn print_fields(&mut self, parent: FieldParent, kind: FieldsShape, fields: &[Field]) { + fn print_fields( + &mut self, + parent: FieldParent, + kind: FieldsShape, + fields: &[Field], + map: &TypesMap, + ) { let edition = self.edition; match kind { FieldsShape::Record => { @@ -135,7 +142,7 @@ impl Printer<'_> { ); this.print_visibility(*visibility); w!(this, "{}: ", name.display(self.db.upcast(), edition)); - this.print_type_ref(type_ref); + this.print_type_ref(*type_ref, map); wln!(this, ","); } }); @@ -151,7 +158,7 @@ impl Printer<'_> { ); this.print_visibility(*visibility); w!(this, "{}: ", name.display(self.db.upcast(), edition)); - this.print_type_ref(type_ref); + this.print_type_ref(*type_ref, map); wln!(this, ","); } }); @@ -167,20 +174,21 @@ impl Printer<'_> { kind: FieldsShape, fields: &[Field], params: &GenericParams, + map: &TypesMap, ) { match kind { FieldsShape::Record => { if self.print_where_clause(params) { wln!(self); } - self.print_fields(parent, kind, fields); + self.print_fields(parent, kind, fields, map); } FieldsShape::Unit => { self.print_where_clause(params); - self.print_fields(parent, kind, fields); + self.print_fields(parent, kind, fields, map); } FieldsShape::Tuple => { - self.print_fields(parent, kind, fields); + self.print_fields(parent, kind, fields, map); self.print_where_clause(params); } } @@ -262,6 +270,7 @@ impl Printer<'_> { params, ret_type, ast_id, + types_map, flags, } = &self.tree[it]; self.print_ast_id(ast_id.erase()); @@ -298,7 +307,7 @@ impl Printer<'_> { w!(this, "self: "); } if let Some(type_ref) = type_ref { - this.print_type_ref(type_ref); + this.print_type_ref(*type_ref, types_map); } else { wln!(this, "..."); } @@ -307,7 +316,7 @@ impl Printer<'_> { }); } w!(self, ") -> "); - self.print_type_ref(ret_type); + self.print_type_ref(*ret_type, types_map); self.print_where_clause(explicit_generic_params); if flags.contains(FnFlags::HAS_BODY) { wln!(self, " {{ ... }}"); @@ -316,8 +325,15 @@ impl Printer<'_> { } } ModItem::Struct(it) => { - let Struct { visibility, name, fields, shape: kind, generic_params, ast_id } = - &self.tree[it]; + let Struct { + visibility, + name, + fields, + shape: kind, + generic_params, + ast_id, + types_map, + } = &self.tree[it]; self.print_ast_id(ast_id.erase()); self.print_visibility(*visibility); w!(self, "struct {}", name.display(self.db.upcast(), self.edition)); @@ -327,6 +343,7 @@ impl Printer<'_> { *kind, fields, generic_params, + types_map, ); if matches!(kind, FieldsShape::Record) { wln!(self); @@ -335,7 +352,8 @@ impl Printer<'_> { } } ModItem::Union(it) => { - let Union { name, visibility, fields, generic_params, ast_id } = &self.tree[it]; + let Union { name, visibility, fields, generic_params, ast_id, types_map } = + &self.tree[it]; self.print_ast_id(ast_id.erase()); self.print_visibility(*visibility); w!(self, "union {}", name.display(self.db.upcast(), self.edition)); @@ -345,6 +363,7 @@ impl Printer<'_> { FieldsShape::Record, fields, generic_params, + types_map, ); wln!(self); } @@ -358,18 +377,20 @@ impl Printer<'_> { let edition = self.edition; self.indented(|this| { for variant in FileItemTreeId::range_iter(variants.clone()) { - let Variant { name, fields, shape: kind, ast_id } = &this.tree[variant]; + let Variant { name, fields, shape: kind, ast_id, types_map } = + &this.tree[variant]; this.print_ast_id(ast_id.erase()); this.print_attrs_of(variant, "\n"); w!(this, "{}", name.display(self.db.upcast(), edition)); - this.print_fields(FieldParent::Variant(variant), *kind, fields); + this.print_fields(FieldParent::Variant(variant), *kind, fields, types_map); wln!(this, ","); } }); wln!(self, "}}"); } ModItem::Const(it) => { - let Const { name, visibility, type_ref, ast_id, has_body: _ } = &self.tree[it]; + let Const { name, visibility, type_ref, ast_id, has_body: _, types_map } = + &self.tree[it]; self.print_ast_id(ast_id.erase()); self.print_visibility(*visibility); w!(self, "const "); @@ -378,7 +399,7 @@ impl Printer<'_> { None => w!(self, "_"), } w!(self, ": "); - self.print_type_ref(type_ref); + self.print_type_ref(*type_ref, types_map); wln!(self, " = _;"); } ModItem::Static(it) => { @@ -390,6 +411,7 @@ impl Printer<'_> { ast_id, has_safe_kw, has_unsafe_kw, + types_map, } = &self.tree[it]; self.print_ast_id(ast_id.erase()); self.print_visibility(*visibility); @@ -404,7 +426,7 @@ impl Printer<'_> { w!(self, "mut "); } w!(self, "{}: ", name.display(self.db.upcast(), self.edition)); - self.print_type_ref(type_ref); + self.print_type_ref(*type_ref, types_map); w!(self, " = _;"); wln!(self); } @@ -449,6 +471,7 @@ impl Printer<'_> { items, generic_params, ast_id, + types_map, } = &self.tree[it]; self.print_ast_id(ast_id.erase()); if *is_unsafe { @@ -461,10 +484,10 @@ impl Printer<'_> { w!(self, "!"); } if let Some(tr) = target_trait { - self.print_path(&tr.path); + self.print_path(&tr.path, types_map); w!(self, " for "); } - self.print_type_ref(self_ty); + self.print_type_ref(*self_ty, types_map); self.print_where_clause_and_opening_brace(generic_params); self.indented(|this| { for item in &**items { @@ -474,19 +497,26 @@ impl Printer<'_> { wln!(self, "}}"); } ModItem::TypeAlias(it) => { - let TypeAlias { name, visibility, bounds, type_ref, generic_params, ast_id } = - &self.tree[it]; + let TypeAlias { + name, + visibility, + bounds, + type_ref, + generic_params, + ast_id, + types_map, + } = &self.tree[it]; self.print_ast_id(ast_id.erase()); self.print_visibility(*visibility); w!(self, "type {}", name.display(self.db.upcast(), self.edition)); self.print_generic_params(generic_params, it.into()); if !bounds.is_empty() { w!(self, ": "); - self.print_type_bounds(bounds); + self.print_type_bounds(bounds, types_map); } if let Some(ty) = type_ref { w!(self, " = "); - self.print_type_ref(ty); + self.print_type_ref(*ty, types_map); } self.print_where_clause(generic_params); w!(self, ";"); @@ -543,19 +573,19 @@ impl Printer<'_> { self.blank(); } - fn print_type_ref(&mut self, type_ref: &TypeRef) { + fn print_type_ref(&mut self, type_ref: TypeRefId, map: &TypesMap) { let edition = self.edition; - print_type_ref(self.db, type_ref, self, edition).unwrap(); + print_type_ref(self.db, type_ref, map, self, edition).unwrap(); } - fn print_type_bounds(&mut self, bounds: &[Interned]) { + fn print_type_bounds(&mut self, bounds: &[TypeBound], map: &TypesMap) { let edition = self.edition; - print_type_bounds(self.db, bounds, self, edition).unwrap(); + print_type_bounds(self.db, bounds, map, self, edition).unwrap(); } - fn print_path(&mut self, path: &Path) { + fn print_path(&mut self, path: &Path, map: &TypesMap) { let edition = self.edition; - print_path(self.db, path, self, edition).unwrap(); + print_path(self.db, path, map, self, edition).unwrap(); } fn print_generic_params(&mut self, params: &GenericParams, parent: GenericModItem) { @@ -586,7 +616,7 @@ impl Printer<'_> { }, TypeOrConstParamData::ConstParamData(konst) => { w!(self, "const {}: ", konst.name.display(self.db.upcast(), self.edition)); - self.print_type_ref(&konst.ty); + self.print_type_ref(konst.ty, ¶ms.types_map); } } } @@ -640,14 +670,16 @@ impl Printer<'_> { }; match target { - WherePredicateTypeTarget::TypeRef(ty) => this.print_type_ref(ty), + WherePredicateTypeTarget::TypeRef(ty) => { + this.print_type_ref(*ty, ¶ms.types_map) + } WherePredicateTypeTarget::TypeOrConstParam(id) => match params[*id].name() { Some(name) => w!(this, "{}", name.display(self.db.upcast(), edition)), None => w!(this, "_anon_{}", id.into_raw()), }, } w!(this, ": "); - this.print_type_bounds(std::slice::from_ref(bound)); + this.print_type_bounds(std::slice::from_ref(bound), ¶ms.types_map); } }); true diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lib.rs b/src/tools/rust-analyzer/crates/hir-def/src/lib.rs index 157c9ef08057..f6ed826f04c7 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lib.rs @@ -1531,11 +1531,3 @@ fn macro_call_as_call_id_with_eager( pub struct UnresolvedMacro { pub path: hir_expand::mod_path::ModPath, } - -intern::impl_internable!( - crate::type_ref::TypeRef, - crate::type_ref::TraitRef, - crate::type_ref::TypeBound, - crate::path::GenericArgs, - generics::GenericParams, -); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/lower.rs index 8e521460c358..fef3b3442333 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lower.rs @@ -5,43 +5,52 @@ use hir_expand::{ span_map::{SpanMap, SpanMapRef}, AstId, HirFileId, InFile, }; -use intern::Interned; use span::{AstIdMap, AstIdNode}; use syntax::ast; use triomphe::Arc; -use crate::{db::DefDatabase, path::Path, type_ref::TypeBound}; +use crate::{ + db::DefDatabase, + path::Path, + type_ref::{TypeBound, TypePtr, TypeRef, TypeRefId, TypesMap, TypesSourceMap}, +}; pub struct LowerCtx<'a> { pub db: &'a dyn DefDatabase, file_id: HirFileId, span_map: OnceCell, ast_id_map: OnceCell>, - impl_trait_bounds: RefCell>>>, + impl_trait_bounds: RefCell>>, // Prevent nested impl traits like `impl Foo`. outer_impl_trait: RefCell, + types_map: RefCell<(&'a mut TypesMap, &'a mut TypesSourceMap)>, } -pub(crate) struct OuterImplTraitGuard<'a> { - ctx: &'a LowerCtx<'a>, +pub(crate) struct OuterImplTraitGuard<'a, 'b> { + ctx: &'a LowerCtx<'b>, old: bool, } -impl<'a> OuterImplTraitGuard<'a> { - fn new(ctx: &'a LowerCtx<'a>, impl_trait: bool) -> Self { +impl<'a, 'b> OuterImplTraitGuard<'a, 'b> { + fn new(ctx: &'a LowerCtx<'b>, impl_trait: bool) -> Self { let old = ctx.outer_impl_trait.replace(impl_trait); Self { ctx, old } } } -impl Drop for OuterImplTraitGuard<'_> { +impl Drop for OuterImplTraitGuard<'_, '_> { fn drop(&mut self) { self.ctx.outer_impl_trait.replace(self.old); } } impl<'a> LowerCtx<'a> { - pub fn new(db: &'a dyn DefDatabase, file_id: HirFileId) -> Self { + pub fn new( + db: &'a dyn DefDatabase, + file_id: HirFileId, + types_map: &'a mut TypesMap, + types_source_map: &'a mut TypesSourceMap, + ) -> Self { LowerCtx { db, file_id, @@ -49,6 +58,7 @@ impl<'a> LowerCtx<'a> { ast_id_map: OnceCell::new(), impl_trait_bounds: RefCell::new(Vec::new()), outer_impl_trait: RefCell::default(), + types_map: RefCell::new((types_map, types_source_map)), } } @@ -56,6 +66,8 @@ impl<'a> LowerCtx<'a> { db: &'a dyn DefDatabase, file_id: HirFileId, span_map: OnceCell, + types_map: &'a mut TypesMap, + types_source_map: &'a mut TypesSourceMap, ) -> Self { LowerCtx { db, @@ -64,6 +76,7 @@ impl<'a> LowerCtx<'a> { ast_id_map: OnceCell::new(), impl_trait_bounds: RefCell::new(Vec::new()), outer_impl_trait: RefCell::default(), + types_map: RefCell::new((types_map, types_source_map)), } } @@ -82,11 +95,11 @@ impl<'a> LowerCtx<'a> { ) } - pub fn update_impl_traits_bounds(&self, bounds: Vec>) { + pub fn update_impl_traits_bounds(&self, bounds: Vec) { self.impl_trait_bounds.borrow_mut().push(bounds); } - pub fn take_impl_traits_bounds(&self) -> Vec>> { + pub fn take_impl_traits_bounds(&self) -> Vec> { self.impl_trait_bounds.take() } @@ -94,7 +107,32 @@ impl<'a> LowerCtx<'a> { *self.outer_impl_trait.borrow() } - pub(crate) fn outer_impl_trait_scope(&'a self, impl_trait: bool) -> OuterImplTraitGuard<'a> { + pub(crate) fn outer_impl_trait_scope<'b>( + &'b self, + impl_trait: bool, + ) -> OuterImplTraitGuard<'b, 'a> { OuterImplTraitGuard::new(self, impl_trait) } + + pub(crate) fn alloc_type_ref(&self, type_ref: TypeRef, node: TypePtr) -> TypeRefId { + let mut types_map = self.types_map.borrow_mut(); + let (types_map, types_source_map) = &mut *types_map; + let id = types_map.types.alloc(type_ref); + types_source_map.types_map_back.insert(id, InFile::new(self.file_id, node)); + id + } + + pub(crate) fn alloc_type_ref_desugared(&self, type_ref: TypeRef) -> TypeRefId { + self.types_map.borrow_mut().0.types.alloc(type_ref) + } + + pub(crate) fn alloc_error_type(&self) -> TypeRefId { + self.types_map.borrow_mut().0.types.alloc(TypeRef::Error) + } + + // FIXME: If we alloc while holding this, well... Bad Things will happen. Need to change this + // to use proper mutability instead of interior mutability. + pub(crate) fn types_map(&self) -> std::cell::Ref<'_, TypesMap> { + std::cell::Ref::map(self.types_map.borrow(), |it| &*it.0) + } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/incremental.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/incremental.rs index d319831867c0..d920c1082662 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/incremental.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests/incremental.rs @@ -253,7 +253,8 @@ m!(Z); let (_, module_data) = crate_def_map.modules.iter().last().unwrap(); assert_eq!(module_data.scope.resolutions().count(), 4); }); - let n_recalculated_item_trees = events.iter().filter(|it| it.contains("item_tree")).count(); + let n_recalculated_item_trees = + events.iter().filter(|it| it.contains("item_tree(")).count(); assert_eq!(n_recalculated_item_trees, 6); let n_reparsed_macros = events.iter().filter(|it| it.contains("parse_macro_expansion(")).count(); @@ -308,7 +309,7 @@ pub type Ty = (); let events = db.log_executed(|| { db.file_item_tree(pos.file_id.into()); }); - let n_calculated_item_trees = events.iter().filter(|it| it.contains("item_tree")).count(); + let n_calculated_item_trees = events.iter().filter(|it| it.contains("item_tree(")).count(); assert_eq!(n_calculated_item_trees, 1); let n_parsed_files = events.iter().filter(|it| it.contains("parse(")).count(); assert_eq!(n_parsed_files, 1); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/path.rs b/src/tools/rust-analyzer/crates/hir-def/src/path.rs index 077863c0c939..4f02a59f8d31 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/path.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/path.rs @@ -9,7 +9,7 @@ use std::{ use crate::{ lang_item::LangItemTarget, lower::LowerCtx, - type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRef}, + type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRefId}, }; use hir_expand::name::Name; use intern::Interned; @@ -51,10 +51,10 @@ pub enum Path { Normal { /// Type based path like `::foo`. /// Note that paths like `::foo` are desugared to `Trait::::foo`. - type_anchor: Option>, + type_anchor: Option, mod_path: Interned, /// Invariant: the same len as `self.mod_path.segments` or `None` if all segments are `None`. - generic_args: Option>]>>, + generic_args: Option]>>, }, /// A link to a lang item. It is used in desugaring of things like `it?`. We can show these /// links via a normal path since they might be private and not accessible in the usage place. @@ -86,20 +86,20 @@ pub struct AssociatedTypeBinding { pub name: Name, /// The generic arguments to the associated type. e.g. For `Trait = &'a T>`, this /// would be `['a, T]`. - pub args: Option>, + pub args: Option, /// The type bound to this associated type (in `Item = T`, this would be the /// `T`). This can be `None` if there are bounds instead. - pub type_ref: Option, + pub type_ref: Option, /// Bounds for the associated type, like in `Iterator`. (This is the unstable `associated_type_bounds` /// feature.) - pub bounds: Box<[Interned]>, + pub bounds: Box<[TypeBound]>, } /// A single generic argument. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum GenericArg { - Type(TypeRef), + Type(TypeRefId), Lifetime(LifetimeRef), Const(ConstRef), } @@ -114,7 +114,7 @@ impl Path { /// Converts a known mod path to `Path`. pub fn from_known_path( path: ModPath, - generic_args: impl Into>]>>, + generic_args: impl Into]>>, ) -> Path { let generic_args = generic_args.into(); assert_eq!(path.len(), generic_args.len()); @@ -137,9 +137,9 @@ impl Path { } } - pub fn type_anchor(&self) -> Option<&TypeRef> { + pub fn type_anchor(&self) -> Option { match self { - Path::Normal { type_anchor, .. } => type_anchor.as_deref(), + Path::Normal { type_anchor, .. } => *type_anchor, Path::LangItem(..) => None, } } @@ -178,7 +178,7 @@ impl Path { return None; } let res = Path::Normal { - type_anchor: type_anchor.clone(), + type_anchor: *type_anchor, mod_path: Interned::new(ModPath::from_segments( mod_path.kind, mod_path.segments()[..mod_path.segments().len() - 1].iter().cloned(), @@ -204,7 +204,7 @@ pub struct PathSegment<'a> { pub struct PathSegments<'a> { segments: &'a [Name], - generic_args: Option<&'a [Option>]>, + generic_args: Option<&'a [Option]>, } impl<'a> PathSegments<'a> { @@ -224,7 +224,7 @@ impl<'a> PathSegments<'a> { pub fn get(&self, idx: usize) -> Option> { let res = PathSegment { name: self.segments.get(idx)?, - args_and_bindings: self.generic_args.and_then(|it| it.get(idx)?.as_deref()), + args_and_bindings: self.generic_args.and_then(|it| it.get(idx)?.as_ref()), }; Some(res) } @@ -244,7 +244,7 @@ impl<'a> PathSegments<'a> { self.segments .iter() .zip(self.generic_args.into_iter().flatten().chain(iter::repeat(&None))) - .map(|(name, args)| PathSegment { name, args_and_bindings: args.as_deref() }) + .map(|(name, args)| PathSegment { name, args_and_bindings: args.as_ref() }) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs index 70918a9358e8..5472da59b5c7 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs @@ -51,8 +51,7 @@ pub(super) fn lower_path(ctx: &LowerCtx<'_>, mut path: ast::Path) -> Option, mut path: ast::Path) -> Option::foo None => { - type_anchor = Some(Interned::new(self_type)); + type_anchor = Some(self_type); kind = PathKind::Plain; } // >::Foo desugars to Trait::Foo @@ -95,7 +94,7 @@ pub(super) fn lower_path(ctx: &LowerCtx<'_>, mut path: ast::Path) -> Option GenericArgs { args: iter::once(self_type) .chain(it.args.iter().cloned()) @@ -110,7 +109,7 @@ pub(super) fn lower_path(ctx: &LowerCtx<'_>, mut path: ast::Path) -> Option { let type_ref = TypeRef::from_ast_opt(lower_ctx, type_arg.ty()); - type_ref.walk(&mut |tr| { + let types_map = lower_ctx.types_map(); + TypeRef::walk(type_ref, &types_map, &mut |tr| { if let TypeRef::ImplTrait(bounds) = tr { lower_ctx.update_impl_traits_bounds(bounds.clone()); } }); + drop(types_map); args.push(GenericArg::Type(type_ref)); } ast::GenericArg::AssocTypeArg(assoc_type_arg) => { @@ -212,20 +213,19 @@ pub(super) fn lower_generic_args( let name = name_ref.as_name(); let args = assoc_type_arg .generic_arg_list() - .and_then(|args| lower_generic_args(lower_ctx, args)) - .map(Interned::new); + .and_then(|args| lower_generic_args(lower_ctx, args)); let type_ref = assoc_type_arg.ty().map(|it| TypeRef::from_ast(lower_ctx, it)); - let type_ref = type_ref.inspect(|tr| { - tr.walk(&mut |tr| { + let type_ref = type_ref.inspect(|&tr| { + let types_map = lower_ctx.types_map(); + TypeRef::walk(tr, &types_map, &mut |tr| { if let TypeRef::ImplTrait(bounds) = tr { lower_ctx.update_impl_traits_bounds(bounds.clone()); } }); + drop(types_map); }); let bounds = if let Some(l) = assoc_type_arg.type_bound_list() { - l.bounds() - .map(|it| Interned::new(TypeBound::from_ast(lower_ctx, it))) - .collect() + l.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)).collect() } else { Box::default() }; @@ -269,7 +269,8 @@ fn lower_generic_args_from_fn_path( let type_ref = TypeRef::from_ast_opt(ctx, param.ty()); param_types.push(type_ref); } - let args = Box::new([GenericArg::Type(TypeRef::Tuple(param_types))]); + let args = + Box::new([GenericArg::Type(ctx.alloc_type_ref_desugared(TypeRef::Tuple(param_types)))]); let bindings = if let Some(ret_type) = ret_type { let type_ref = TypeRef::from_ast_opt(ctx, ret_type.ty()); Box::new([AssociatedTypeBinding { @@ -280,7 +281,7 @@ fn lower_generic_args_from_fn_path( }]) } else { // -> () - let type_ref = TypeRef::Tuple(Vec::new()); + let type_ref = ctx.alloc_type_ref_desugared(TypeRef::Tuple(Vec::new())); Box::new([AssociatedTypeBinding { name: Name::new_symbol_root(sym::Output.clone()), args: None, diff --git a/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs index 49c0ad412499..f8fd5cfb7751 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs @@ -6,7 +6,6 @@ use std::{ }; use hir_expand::mod_path::PathKind; -use intern::Interned; use itertools::Itertools; use span::Edition; @@ -14,12 +13,15 @@ use crate::{ db::DefDatabase, lang_item::LangItemTarget, path::{GenericArg, GenericArgs, Path}, - type_ref::{Mutability, TraitBoundModifier, TypeBound, TypeRef, UseArgRef}, + type_ref::{ + Mutability, TraitBoundModifier, TypeBound, TypeRef, TypeRefId, TypesMap, UseArgRef, + }, }; pub(crate) fn print_path( db: &dyn DefDatabase, path: &Path, + map: &TypesMap, buf: &mut dyn Write, edition: Edition, ) -> fmt::Result { @@ -61,7 +63,7 @@ pub(crate) fn print_path( match path.type_anchor() { Some(anchor) => { write!(buf, "<")?; - print_type_ref(db, anchor, buf, edition)?; + print_type_ref(db, anchor, map, buf, edition)?; write!(buf, ">::")?; } None => match path.kind() { @@ -90,7 +92,7 @@ pub(crate) fn print_path( write!(buf, "{}", segment.name.display(db.upcast(), edition))?; if let Some(generics) = segment.args_and_bindings { write!(buf, "::<")?; - print_generic_args(db, generics, buf, edition)?; + print_generic_args(db, generics, map, buf, edition)?; write!(buf, ">")?; } @@ -102,6 +104,7 @@ pub(crate) fn print_path( pub(crate) fn print_generic_args( db: &dyn DefDatabase, generics: &GenericArgs, + map: &TypesMap, buf: &mut dyn Write, edition: Edition, ) -> fmt::Result { @@ -109,7 +112,7 @@ pub(crate) fn print_generic_args( let args = if generics.has_self_type { let (self_ty, args) = generics.args.split_first().unwrap(); write!(buf, "Self=")?; - print_generic_arg(db, self_ty, buf, edition)?; + print_generic_arg(db, self_ty, map, buf, edition)?; first = false; args } else { @@ -120,7 +123,7 @@ pub(crate) fn print_generic_args( write!(buf, ", ")?; } first = false; - print_generic_arg(db, arg, buf, edition)?; + print_generic_arg(db, arg, map, buf, edition)?; } for binding in generics.bindings.iter() { if !first { @@ -130,11 +133,11 @@ pub(crate) fn print_generic_args( write!(buf, "{}", binding.name.display(db.upcast(), edition))?; if !binding.bounds.is_empty() { write!(buf, ": ")?; - print_type_bounds(db, &binding.bounds, buf, edition)?; + print_type_bounds(db, &binding.bounds, map, buf, edition)?; } - if let Some(ty) = &binding.type_ref { + if let Some(ty) = binding.type_ref { write!(buf, " = ")?; - print_type_ref(db, ty, buf, edition)?; + print_type_ref(db, ty, map, buf, edition)?; } } Ok(()) @@ -143,11 +146,12 @@ pub(crate) fn print_generic_args( pub(crate) fn print_generic_arg( db: &dyn DefDatabase, arg: &GenericArg, + map: &TypesMap, buf: &mut dyn Write, edition: Edition, ) -> fmt::Result { match arg { - GenericArg::Type(ty) => print_type_ref(db, ty, buf, edition), + GenericArg::Type(ty) => print_type_ref(db, *ty, map, buf, edition), GenericArg::Const(c) => write!(buf, "{}", c.display(db.upcast(), edition)), GenericArg::Lifetime(lt) => write!(buf, "{}", lt.name.display(db.upcast(), edition)), } @@ -155,12 +159,13 @@ pub(crate) fn print_generic_arg( pub(crate) fn print_type_ref( db: &dyn DefDatabase, - type_ref: &TypeRef, + type_ref: TypeRefId, + map: &TypesMap, buf: &mut dyn Write, edition: Edition, ) -> fmt::Result { // FIXME: deduplicate with `HirDisplay` impl - match type_ref { + match &map[type_ref] { TypeRef::Never => write!(buf, "!")?, TypeRef::Placeholder => write!(buf, "_")?, TypeRef::Tuple(fields) => { @@ -169,18 +174,18 @@ pub(crate) fn print_type_ref( if i != 0 { write!(buf, ", ")?; } - print_type_ref(db, field, buf, edition)?; + print_type_ref(db, *field, map, buf, edition)?; } write!(buf, ")")?; } - TypeRef::Path(path) => print_path(db, path, buf, edition)?, + TypeRef::Path(path) => print_path(db, path, map, buf, edition)?, TypeRef::RawPtr(pointee, mtbl) => { let mtbl = match mtbl { Mutability::Shared => "*const", Mutability::Mut => "*mut", }; write!(buf, "{mtbl} ")?; - print_type_ref(db, pointee, buf, edition)?; + print_type_ref(db, *pointee, map, buf, edition)?; } TypeRef::Reference(pointee, lt, mtbl) => { let mtbl = match mtbl { @@ -192,19 +197,19 @@ pub(crate) fn print_type_ref( write!(buf, "{} ", lt.name.display(db.upcast(), edition))?; } write!(buf, "{mtbl}")?; - print_type_ref(db, pointee, buf, edition)?; + print_type_ref(db, *pointee, map, buf, edition)?; } TypeRef::Array(elem, len) => { write!(buf, "[")?; - print_type_ref(db, elem, buf, edition)?; + print_type_ref(db, *elem, map, buf, edition)?; write!(buf, "; {}]", len.display(db.upcast(), edition))?; } TypeRef::Slice(elem) => { write!(buf, "[")?; - print_type_ref(db, elem, buf, edition)?; + print_type_ref(db, *elem, map, buf, edition)?; write!(buf, "]")?; } - TypeRef::Fn(args_and_ret, varargs, is_unsafe, abi) => { + TypeRef::Fn { params: args_and_ret, is_varargs: varargs, is_unsafe, abi } => { let ((_, return_type), args) = args_and_ret.split_last().expect("TypeRef::Fn is missing return type"); if *is_unsafe { @@ -220,7 +225,7 @@ pub(crate) fn print_type_ref( if i != 0 { write!(buf, ", ")?; } - print_type_ref(db, typeref, buf, edition)?; + print_type_ref(db, *typeref, map, buf, edition)?; } if *varargs { if !args.is_empty() { @@ -229,7 +234,7 @@ pub(crate) fn print_type_ref( write!(buf, "...")?; } write!(buf, ") -> ")?; - print_type_ref(db, return_type, buf, edition)?; + print_type_ref(db, *return_type, map, buf, edition)?; } TypeRef::Macro(_ast_id) => { write!(buf, "")?; @@ -237,11 +242,11 @@ pub(crate) fn print_type_ref( TypeRef::Error => write!(buf, "{{unknown}}")?, TypeRef::ImplTrait(bounds) => { write!(buf, "impl ")?; - print_type_bounds(db, bounds, buf, edition)?; + print_type_bounds(db, bounds, map, buf, edition)?; } TypeRef::DynTrait(bounds) => { write!(buf, "dyn ")?; - print_type_bounds(db, bounds, buf, edition)?; + print_type_bounds(db, bounds, map, buf, edition)?; } } @@ -250,7 +255,8 @@ pub(crate) fn print_type_ref( pub(crate) fn print_type_bounds( db: &dyn DefDatabase, - bounds: &[Interned], + bounds: &[TypeBound], + map: &TypesMap, buf: &mut dyn Write, edition: Edition, ) -> fmt::Result { @@ -259,13 +265,13 @@ pub(crate) fn print_type_bounds( write!(buf, " + ")?; } - match bound.as_ref() { + match bound { TypeBound::Path(path, modifier) => { match modifier { TraitBoundModifier::None => (), TraitBoundModifier::Maybe => write!(buf, "?")?, } - print_path(db, path, buf, edition)?; + print_path(db, path, map, buf, edition)?; } TypeBound::ForLifetime(lifetimes, path) => { write!( @@ -273,7 +279,7 @@ pub(crate) fn print_type_bounds( "for<{}> ", lifetimes.iter().map(|it| it.display(db.upcast(), edition)).format(", ") )?; - print_path(db, path, buf, edition)?; + print_path(db, path, map, buf, edition)?; } TypeBound::Lifetime(lt) => write!(buf, "{}", lt.name.display(db.upcast(), edition))?, TypeBound::Use(args) => { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs index 266851e3c0d5..0b49ee80511c 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs @@ -3,7 +3,7 @@ use std::{fmt, iter, mem}; use base_db::CrateId; use hir_expand::{name::Name, MacroDefId}; -use intern::{sym, Interned}; +use intern::sym; use itertools::Itertools as _; use rustc_hash::FxHashSet; use smallvec::{smallvec, SmallVec}; @@ -24,7 +24,7 @@ use crate::{ nameres::{DefMap, MacroSubNs}, path::{ModPath, Path, PathKind}, per_ns::PerNs, - type_ref::LifetimeRef, + type_ref::{LifetimeRef, TypesMap}, visibility::{RawVisibility, Visibility}, AdtId, ConstId, ConstParamId, CrateRootModuleId, DefWithBodyId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId, FunctionId, FxIndexMap, GenericDefId, GenericParamId, HasModule, @@ -76,7 +76,7 @@ enum Scope { /// All the items and imported names of a module BlockScope(ModuleItemMap), /// Brings the generic parameters of an item into scope - GenericParams { def: GenericDefId, params: Interned }, + GenericParams { def: GenericDefId, params: Arc }, /// Brings `Self` in `impl` block into scope ImplDefScope(ImplId), /// Brings `Self` in enum, struct and union definitions into scope @@ -620,13 +620,15 @@ impl Resolver { pub fn where_predicates_in_scope( &self, - ) -> impl Iterator { + ) -> impl Iterator { self.scopes() .filter_map(|scope| match scope { Scope::GenericParams { params, def } => Some((params, def)), _ => None, }) - .flat_map(|(params, def)| params.where_predicates().zip(iter::repeat(def))) + .flat_map(|(params, def)| { + params.where_predicates().zip(iter::repeat((def, ¶ms.types_map))) + }) } pub fn generic_def(&self) -> Option { @@ -636,13 +638,20 @@ impl Resolver { }) } - pub fn generic_params(&self) -> Option<&Interned> { + pub fn generic_params(&self) -> Option<&Arc> { self.scopes().find_map(|scope| match scope { Scope::GenericParams { params, .. } => Some(params), _ => None, }) } + pub fn all_generic_params(&self) -> impl Iterator { + self.scopes().filter_map(|scope| match scope { + Scope::GenericParams { params, def } => Some((&**params, def)), + _ => None, + }) + } + pub fn body_owner(&self) -> Option { self.scopes().find_map(|scope| match scope { Scope::ExprScope(it) => Some(it.owner), diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs b/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs index 8a616956de23..4bc78afacc09 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs @@ -615,8 +615,9 @@ pub(crate) fn associated_ty_data_query( let type_alias_data = db.type_alias_data(type_alias); let generic_params = generics(db.upcast(), type_alias.into()); let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast()); - let ctx = crate::TyLoweringContext::new(db, &resolver, type_alias.into()) - .with_type_param_mode(crate::lower::ParamLoweringMode::Variable); + let ctx = + crate::TyLoweringContext::new(db, &resolver, &type_alias_data.types_map, type_alias.into()) + .with_type_param_mode(crate::lower::ParamLoweringMode::Variable); let trait_subst = TyBuilder::subst_for_def(db, trait_, None) .fill_with_bound_vars(crate::DebruijnIndex::INNERMOST, generic_params.len_self()) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs index 7f6b7e392b30..c9ab0acc0849 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs @@ -309,7 +309,7 @@ impl<'a> DeclValidator<'a> { /// Check incorrect names for struct fields. fn validate_struct_fields(&mut self, struct_id: StructId) { let data = self.db.struct_data(struct_id); - let VariantData::Record(fields) = data.variant_data.as_ref() else { + let VariantData::Record { fields, .. } = data.variant_data.as_ref() else { return; }; let edition = self.edition(struct_id); @@ -469,7 +469,7 @@ impl<'a> DeclValidator<'a> { /// Check incorrect names for fields of enum variant. fn validate_enum_variant_fields(&mut self, variant_id: EnumVariantId) { let variant_data = self.db.enum_variant_data(variant_id); - let VariantData::Record(fields) = variant_data.variant_data.as_ref() else { + let VariantData::Record { fields, .. } = variant_data.variant_data.as_ref() else { return; }; let edition = self.edition(variant_id); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs index 4bc07bc9ec8f..c5d8c9566155 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs @@ -341,7 +341,7 @@ impl HirDisplay for Pat { }; let variant_data = variant.variant_data(f.db.upcast()); - if let VariantData::Record(rec_fields) = &*variant_data { + if let VariantData::Record { fields: rec_fields, .. } = &*variant_data { write!(f, " {{ ")?; let mut printed = 0; diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs index 79861345b8ce..e5c3c35e2bcc 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs @@ -19,7 +19,9 @@ use hir_def::{ lang_item::{LangItem, LangItemTarget}, nameres::DefMap, path::{Path, PathKind}, - type_ref::{TraitBoundModifier, TypeBound, TypeRef, UseArgRef}, + type_ref::{ + TraitBoundModifier, TypeBound, TypeRef, TypeRefId, TypesMap, TypesSourceMap, UseArgRef, + }, visibility::Visibility, GenericDefId, HasModule, ImportPathConfig, ItemContainerId, LocalFieldId, Lookup, ModuleDefId, ModuleId, TraitId, @@ -806,7 +808,7 @@ fn render_variant_after_name( memory_map: &MemoryMap, ) -> Result<(), HirDisplayError> { match data { - VariantData::Record(fields) | VariantData::Tuple(fields) => { + VariantData::Record { fields, .. } | VariantData::Tuple { fields, .. } => { let render_field = |f: &mut HirFormatter<'_>, id: LocalFieldId| { let offset = layout.fields.offset(u32::from(id.into_raw()) as usize).bytes_usize(); let ty = field_types[id].clone().substitute(Interner, subst); @@ -817,7 +819,7 @@ fn render_variant_after_name( render_const_scalar(f, &b[offset..offset + size], memory_map, &ty) }; let mut it = fields.iter(); - if matches!(data, VariantData::Record(_)) { + if matches!(data, VariantData::Record { .. }) { write!(f, " {{")?; if let Some((id, data)) = it.next() { write!(f, " {}: ", data.name.display(f.db.upcast(), f.edition()))?; @@ -1897,27 +1899,70 @@ pub fn write_visibility( } } -impl HirDisplay for TypeRef { +pub trait HirDisplayWithTypesMap { + fn hir_fmt( + &self, + f: &mut HirFormatter<'_>, + types_map: &TypesMap, + ) -> Result<(), HirDisplayError>; +} + +impl HirDisplayWithTypesMap for &'_ T { + fn hir_fmt( + &self, + f: &mut HirFormatter<'_>, + types_map: &TypesMap, + ) -> Result<(), HirDisplayError> { + T::hir_fmt(&**self, f, types_map) + } +} + +pub fn hir_display_with_types_map<'a, T: HirDisplayWithTypesMap + 'a>( + value: T, + types_map: &'a TypesMap, +) -> impl HirDisplay + 'a { + TypesMapAdapter(value, types_map) +} + +struct TypesMapAdapter<'a, T>(T, &'a TypesMap); + +impl<'a, T> TypesMapAdapter<'a, T> { + fn wrap(types_map: &'a TypesMap) -> impl Fn(T) -> TypesMapAdapter<'a, T> { + move |value| TypesMapAdapter(value, types_map) + } +} + +impl HirDisplay for TypesMapAdapter<'_, T> { fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> { - match self { + T::hir_fmt(&self.0, f, self.1) + } +} + +impl HirDisplayWithTypesMap for TypeRefId { + fn hir_fmt( + &self, + f: &mut HirFormatter<'_>, + types_map: &TypesMap, + ) -> Result<(), HirDisplayError> { + match &types_map[*self] { TypeRef::Never => write!(f, "!")?, TypeRef::Placeholder => write!(f, "_")?, TypeRef::Tuple(elems) => { write!(f, "(")?; - f.write_joined(elems, ", ")?; + f.write_joined(elems.iter().map(TypesMapAdapter::wrap(types_map)), ", ")?; if elems.len() == 1 { write!(f, ",")?; } write!(f, ")")?; } - TypeRef::Path(path) => path.hir_fmt(f)?, + TypeRef::Path(path) => path.hir_fmt(f, types_map)?, TypeRef::RawPtr(inner, mutability) => { let mutability = match mutability { hir_def::type_ref::Mutability::Shared => "*const ", hir_def::type_ref::Mutability::Mut => "*mut ", }; write!(f, "{mutability}")?; - inner.hir_fmt(f)?; + inner.hir_fmt(f, types_map)?; } TypeRef::Reference(inner, lifetime, mutability) => { let mutability = match mutability { @@ -1929,19 +1974,19 @@ impl HirDisplay for TypeRef { write!(f, "{} ", lifetime.name.display(f.db.upcast(), f.edition()))?; } write!(f, "{mutability}")?; - inner.hir_fmt(f)?; + inner.hir_fmt(f, types_map)?; } TypeRef::Array(inner, len) => { write!(f, "[")?; - inner.hir_fmt(f)?; + inner.hir_fmt(f, types_map)?; write!(f, "; {}]", len.display(f.db.upcast(), f.edition()))?; } TypeRef::Slice(inner) => { write!(f, "[")?; - inner.hir_fmt(f)?; + inner.hir_fmt(f, types_map)?; write!(f, "]")?; } - &TypeRef::Fn(ref parameters, is_varargs, is_unsafe, ref abi) => { + &TypeRef::Fn { params: ref parameters, is_varargs, is_unsafe, ref abi } => { if is_unsafe { write!(f, "unsafe ")?; } @@ -1958,7 +2003,7 @@ impl HirDisplay for TypeRef { write!(f, "{}: ", name.display(f.db.upcast(), f.edition()))?; } - param_type.hir_fmt(f)?; + param_type.hir_fmt(f, types_map)?; if index != function_parameters.len() - 1 { write!(f, ", ")?; @@ -1968,29 +2013,36 @@ impl HirDisplay for TypeRef { write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?; } write!(f, ")")?; - match &return_type { + match &types_map[*return_type] { TypeRef::Tuple(tup) if tup.is_empty() => {} _ => { write!(f, " -> ")?; - return_type.hir_fmt(f)?; + return_type.hir_fmt(f, types_map)?; } } } } TypeRef::ImplTrait(bounds) => { write!(f, "impl ")?; - f.write_joined(bounds, " + ")?; + f.write_joined(bounds.iter().map(TypesMapAdapter::wrap(types_map)), " + ")?; } TypeRef::DynTrait(bounds) => { write!(f, "dyn ")?; - f.write_joined(bounds, " + ")?; + f.write_joined(bounds.iter().map(TypesMapAdapter::wrap(types_map)), " + ")?; } TypeRef::Macro(macro_call) => { - let ctx = hir_def::lower::LowerCtx::new(f.db.upcast(), macro_call.file_id); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = hir_def::lower::LowerCtx::new( + f.db.upcast(), + macro_call.file_id, + &mut types_map, + &mut types_source_map, + ); let macro_call = macro_call.to_node(f.db.upcast()); match macro_call.path() { Some(path) => match Path::from_src(&ctx, path) { - Some(path) => path.hir_fmt(f)?, + Some(path) => path.hir_fmt(f, &types_map)?, None => write!(f, "{{macro}}")?, }, None => write!(f, "{{macro}}")?, @@ -2003,15 +2055,19 @@ impl HirDisplay for TypeRef { } } -impl HirDisplay for TypeBound { - fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> { +impl HirDisplayWithTypesMap for TypeBound { + fn hir_fmt( + &self, + f: &mut HirFormatter<'_>, + types_map: &TypesMap, + ) -> Result<(), HirDisplayError> { match self { TypeBound::Path(path, modifier) => { match modifier { TraitBoundModifier::None => (), TraitBoundModifier::Maybe => write!(f, "?")?, } - path.hir_fmt(f) + path.hir_fmt(f, types_map) } TypeBound::Lifetime(lifetime) => { write!(f, "{}", lifetime.name.display(f.db.upcast(), f.edition())) @@ -2023,7 +2079,7 @@ impl HirDisplay for TypeBound { "for<{}> ", lifetimes.iter().map(|it| it.display(f.db.upcast(), edition)).format(", ") )?; - path.hir_fmt(f) + path.hir_fmt(f, types_map) } TypeBound::Use(args) => { let edition = f.edition(); @@ -2043,12 +2099,16 @@ impl HirDisplay for TypeBound { } } -impl HirDisplay for Path { - fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> { +impl HirDisplayWithTypesMap for Path { + fn hir_fmt( + &self, + f: &mut HirFormatter<'_>, + types_map: &TypesMap, + ) -> Result<(), HirDisplayError> { match (self.type_anchor(), self.kind()) { (Some(anchor), _) => { write!(f, "<")?; - anchor.hir_fmt(f)?; + anchor.hir_fmt(f, types_map)?; write!(f, ">")?; } (_, PathKind::Plain) => {} @@ -2091,7 +2151,7 @@ impl HirDisplay for Path { }); if let Some(ty) = trait_self_ty { write!(f, "<")?; - ty.hir_fmt(f)?; + ty.hir_fmt(f, types_map)?; write!(f, " as ")?; // Now format the path of the trait... } @@ -2107,21 +2167,26 @@ impl HirDisplay for Path { if generic_args.desugared_from_fn { // First argument will be a tuple, which already includes the parentheses. // If the tuple only contains 1 item, write it manually to avoid the trailing `,`. - if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) = - &generic_args.args[0] - { + let tuple = match generic_args.args[0] { + hir_def::path::GenericArg::Type(ty) => match &types_map[ty] { + TypeRef::Tuple(it) => Some(it), + _ => None, + }, + _ => None, + }; + if let Some(v) = tuple { if v.len() == 1 { write!(f, "(")?; - v[0].hir_fmt(f)?; + v[0].hir_fmt(f, types_map)?; write!(f, ")")?; } else { - generic_args.args[0].hir_fmt(f)?; + generic_args.args[0].hir_fmt(f, types_map)?; } } - if let Some(ret) = &generic_args.bindings[0].type_ref { - if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) { + if let Some(ret) = generic_args.bindings[0].type_ref { + if !matches!(&types_map[ret], TypeRef::Tuple(v) if v.is_empty()) { write!(f, " -> ")?; - ret.hir_fmt(f)?; + ret.hir_fmt(f, types_map)?; } } return Ok(()); @@ -2136,7 +2201,7 @@ impl HirDisplay for Path { } else { write!(f, ", ")?; } - arg.hir_fmt(f)?; + arg.hir_fmt(f, types_map)?; } for binding in generic_args.bindings.iter() { if first { @@ -2149,11 +2214,14 @@ impl HirDisplay for Path { match &binding.type_ref { Some(ty) => { write!(f, " = ")?; - ty.hir_fmt(f)? + ty.hir_fmt(f, types_map)? } None => { write!(f, ": ")?; - f.write_joined(binding.bounds.iter(), " + ")?; + f.write_joined( + binding.bounds.iter().map(TypesMapAdapter::wrap(types_map)), + " + ", + )?; } } } @@ -2175,10 +2243,14 @@ impl HirDisplay for Path { } } -impl HirDisplay for hir_def::path::GenericArg { - fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> { +impl HirDisplayWithTypesMap for hir_def::path::GenericArg { + fn hir_fmt( + &self, + f: &mut HirFormatter<'_>, + types_map: &TypesMap, + ) -> Result<(), HirDisplayError> { match self { - hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f), + hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f, types_map), hir_def::path::GenericArg::Const(c) => { write!(f, "{}", c.display(f.db.upcast(), f.edition())) } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/generics.rs b/src/tools/rust-analyzer/crates/hir-ty/src/generics.rs index 89ca707c2e69..c094bc395129 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/generics.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/generics.rs @@ -16,12 +16,13 @@ use hir_def::{ GenericParamDataRef, GenericParams, LifetimeParamData, TypeOrConstParamData, TypeParamProvenance, }, + type_ref::TypesMap, ConstParamId, GenericDefId, GenericParamId, ItemContainerId, LifetimeParamId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId, }; -use intern::Interned; use itertools::chain; use stdx::TupleExt; +use triomphe::Arc; use crate::{db::HirDatabase, lt_to_placeholder_idx, to_placeholder_idx, Interner, Substitution}; @@ -34,7 +35,7 @@ pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics { #[derive(Clone, Debug)] pub(crate) struct Generics { def: GenericDefId, - params: Interned, + params: Arc, parent_generics: Option>, has_trait_self_param: bool, } @@ -85,6 +86,18 @@ impl Generics { self.iter_self().chain(self.iter_parent()) } + pub(crate) fn iter_with_types_map( + &self, + ) -> impl Iterator), &TypesMap)> + '_ { + self.iter_self().zip(std::iter::repeat(&self.params.types_map)).chain( + self.iter_parent().zip( + self.parent_generics() + .into_iter() + .flat_map(|it| std::iter::repeat(&it.params.types_map)), + ), + ) + } + /// Iterate over the params without parent params. pub(crate) fn iter_self( &self, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index 3cb0d89e01c4..3685ed569640 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -41,7 +41,7 @@ use hir_def::{ layout::Integer, path::{ModPath, Path}, resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, - type_ref::{LifetimeRef, TypeRef}, + type_ref::{LifetimeRef, TypeRefId, TypesMap}, AdtId, AssocItemId, DefWithBodyId, FieldId, FunctionId, ImplId, ItemContainerId, Lookup, TraitId, TupleFieldId, TupleId, TypeAliasId, VariantId, }; @@ -858,7 +858,7 @@ impl<'a> InferenceContext<'a> { } fn collect_const(&mut self, data: &ConstData) { - let return_ty = self.make_ty(&data.type_ref); + let return_ty = self.make_ty(data.type_ref, &data.types_map); // Constants might be defining usage sites of TAITs. self.make_tait_coercion_table(iter::once(&return_ty)); @@ -867,7 +867,7 @@ impl<'a> InferenceContext<'a> { } fn collect_static(&mut self, data: &StaticData) { - let return_ty = self.make_ty(&data.type_ref); + let return_ty = self.make_ty(data.type_ref, &data.types_map); // Statics might be defining usage sites of TAITs. self.make_tait_coercion_table(iter::once(&return_ty)); @@ -877,11 +877,11 @@ impl<'a> InferenceContext<'a> { fn collect_fn(&mut self, func: FunctionId) { let data = self.db.function_data(func); - let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()) - .with_type_param_mode(ParamLoweringMode::Placeholder) - .with_impl_trait_mode(ImplTraitLoweringMode::Param); - let mut param_tys = - data.params.iter().map(|type_ref| ctx.lower_ty(type_ref)).collect::>(); + let mut param_tys = self.with_ty_lowering(&data.types_map, |ctx| { + ctx.type_param_mode(ParamLoweringMode::Placeholder) + .impl_trait_mode(ImplTraitLoweringMode::Param); + data.params.iter().map(|&type_ref| ctx.lower_ty(type_ref)).collect::>() + }); // Check if function contains a va_list, if it does then we append it to the parameter types // that are collected from the function data if data.is_varargs() { @@ -916,12 +916,13 @@ impl<'a> InferenceContext<'a> { tait_candidates.insert(ty); } } - let return_ty = &*data.ret_type; + let return_ty = data.ret_type; - let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()) - .with_type_param_mode(ParamLoweringMode::Placeholder) - .with_impl_trait_mode(ImplTraitLoweringMode::Opaque); - let return_ty = ctx.lower_ty(return_ty); + let return_ty = self.with_ty_lowering(&data.types_map, |ctx| { + ctx.type_param_mode(ParamLoweringMode::Placeholder) + .impl_trait_mode(ImplTraitLoweringMode::Opaque) + .lower_ty(return_ty) + }); let return_ty = self.insert_type_vars(return_ty); let return_ty = if let Some(rpits) = self.db.return_type_impl_traits(func) { @@ -1225,20 +1226,43 @@ impl<'a> InferenceContext<'a> { self.result.diagnostics.push(diagnostic); } - fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { - let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()); - let ty = ctx.lower_ty(type_ref); + fn with_ty_lowering( + &self, + types_map: &TypesMap, + f: impl FnOnce(&mut crate::lower::TyLoweringContext<'_>) -> R, + ) -> R { + let mut ctx = crate::lower::TyLoweringContext::new( + self.db, + &self.resolver, + types_map, + self.owner.into(), + ); + f(&mut ctx) + } + + fn with_body_ty_lowering( + &self, + f: impl FnOnce(&mut crate::lower::TyLoweringContext<'_>) -> R, + ) -> R { + self.with_ty_lowering(&self.body.types, f) + } + + fn make_ty(&mut self, type_ref: TypeRefId, types_map: &TypesMap) -> Ty { + let ty = self.with_ty_lowering(types_map, |ctx| ctx.lower_ty(type_ref)); let ty = self.insert_type_vars(ty); self.normalize_associated_types_in(ty) } + fn make_body_ty(&mut self, type_ref: TypeRefId) -> Ty { + self.make_ty(type_ref, &self.body.types) + } + fn err_ty(&self) -> Ty { self.result.standard_types.unknown.clone() } fn make_lifetime(&mut self, lifetime_ref: &LifetimeRef) -> Lifetime { - let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()); - let lt = ctx.lower_lifetime(lifetime_ref); + let lt = self.with_ty_lowering(TypesMap::EMPTY, |ctx| ctx.lower_lifetime(lifetime_ref)); self.insert_type_vars(lt) } @@ -1396,7 +1420,12 @@ impl<'a> InferenceContext<'a> { Some(path) => path, None => return (self.err_ty(), None), }; - let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()); + let ctx = crate::lower::TyLoweringContext::new( + self.db, + &self.resolver, + &self.body.types, + self.owner.into(), + ); let (resolution, unresolved) = if value_ns { match self.resolver.resolve_path_in_value_ns(self.db.upcast(), path, HygieneId::ROOT) { Some(ResolveValueResult::ValueNs(value, _)) => match value { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs index f5face07d860..5a251683b962 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs @@ -283,11 +283,11 @@ impl CapturedItem { ProjectionElem::Deref => {} ProjectionElem::Field(Either::Left(f)) => { match &*f.parent.variant_data(db.upcast()) { - VariantData::Record(fields) => { + VariantData::Record { fields, .. } => { result.push('_'); result.push_str(fields[f.local_id].name.as_str()) } - VariantData::Tuple(fields) => { + VariantData::Tuple { fields, .. } => { let index = fields.iter().position(|it| it.0 == f.local_id); if let Some(index) = index { format_to!(result, "_{index}"); @@ -325,12 +325,12 @@ impl CapturedItem { ProjectionElem::Field(Either::Left(f)) => { let variant_data = f.parent.variant_data(db.upcast()); match &*variant_data { - VariantData::Record(fields) => format_to!( + VariantData::Record { fields, .. } => format_to!( result, ".{}", fields[f.local_id].name.display(db.upcast(), edition) ), - VariantData::Tuple(fields) => format_to!( + VariantData::Tuple { fields, .. } => format_to!( result, ".{}", fields.iter().position(|it| it.0 == f.local_id).unwrap_or_default() @@ -383,8 +383,10 @@ impl CapturedItem { } let variant_data = f.parent.variant_data(db.upcast()); let field = match &*variant_data { - VariantData::Record(fields) => fields[f.local_id].name.as_str().to_owned(), - VariantData::Tuple(fields) => fields + VariantData::Record { fields, .. } => { + fields[f.local_id].name.as_str().to_owned() + } + VariantData::Tuple { fields, .. } => fields .iter() .position(|it| it.0 == f.local_id) .unwrap_or_default() diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs index e55ddad4e969..ee55dbe1c3dd 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs @@ -382,7 +382,7 @@ impl InferenceContext<'_> { // collect explicitly written argument types for arg_type in arg_types.iter() { let arg_ty = match arg_type { - Some(type_ref) => self.make_ty(type_ref), + Some(type_ref) => self.make_body_ty(*type_ref), None => self.table.new_type_var(), }; sig_tys.push(arg_ty); @@ -390,7 +390,7 @@ impl InferenceContext<'_> { // add return type let ret_ty = match ret_type { - Some(type_ref) => self.make_ty(type_ref), + Some(type_ref) => self.make_body_ty(*type_ref), None => self.table.new_type_var(), }; if let ClosureKind::Async = closure_kind { @@ -786,7 +786,7 @@ impl InferenceContext<'_> { self.resolve_associated_type(inner_ty, self.resolve_future_future_output()) } Expr::Cast { expr, type_ref } => { - let cast_ty = self.make_ty(type_ref); + let cast_ty = self.make_body_ty(*type_ref); let expr_ty = self.infer_expr( *expr, &Expectation::Castable(cast_ty.clone()), @@ -1598,7 +1598,7 @@ impl InferenceContext<'_> { Statement::Let { pat, type_ref, initializer, else_branch } => { let decl_ty = type_ref .as_ref() - .map(|tr| this.make_ty(tr)) + .map(|&tr| this.make_body_ty(tr)) .unwrap_or_else(|| this.table.new_type_var()); let ty = if let Some(expr) = initializer { @@ -2141,7 +2141,8 @@ impl InferenceContext<'_> { kind_id, args.next().unwrap(), // `peek()` is `Some(_)`, so guaranteed no panic self, - |this, type_ref| this.make_ty(type_ref), + &self.body.types, + |this, type_ref| this.make_body_ty(type_ref), |this, c, ty| { const_or_path_to_chalk( this.db, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs index 44c496c05421..0df44f5df28b 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs @@ -94,8 +94,7 @@ impl InferenceContext<'_> { return Some(ValuePathResolution::NonGeneric(ty)); }; - let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()); - let substs = ctx.substs_from_path(path, value_def, true); + let substs = self.with_body_ty_lowering(|ctx| ctx.substs_from_path(path, value_def, true)); let substs = substs.as_slice(Interner); if let ValueNs::EnumVariantId(_) = value { @@ -152,8 +151,12 @@ impl InferenceContext<'_> { let last = path.segments().last()?; // Don't use `self.make_ty()` here as we need `orig_ns`. - let ctx = - crate::lower::TyLoweringContext::new(self.db, &self.resolver, self.owner.into()); + let ctx = crate::lower::TyLoweringContext::new( + self.db, + &self.resolver, + &self.body.types, + self.owner.into(), + ); let (ty, orig_ns) = ctx.lower_ty_ext(type_ref); let ty = self.table.insert_type_vars(ty); let ty = self.table.normalize_associated_types_in(ty); @@ -243,17 +246,10 @@ impl InferenceContext<'_> { (TypeNs::TraitId(trait_), true) => { let segment = remaining_segments.last().expect("there should be at least one segment here"); - let ctx = crate::lower::TyLoweringContext::new( - self.db, - &self.resolver, - self.owner.into(), - ); - let trait_ref = ctx.lower_trait_ref_from_resolved_path( - trait_, - resolved_segment, - self.table.new_type_var(), - ); - + let self_ty = self.table.new_type_var(); + let trait_ref = self.with_body_ty_lowering(|ctx| { + ctx.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty) + }); self.resolve_trait_assoc_item(trait_ref, segment, id) } (def, _) => { @@ -263,17 +259,14 @@ impl InferenceContext<'_> { // as Iterator>::Item::default`) let remaining_segments_for_ty = remaining_segments.take(remaining_segments.len() - 1); - let ctx = crate::lower::TyLoweringContext::new( - self.db, - &self.resolver, - self.owner.into(), - ); - let (ty, _) = ctx.lower_partly_resolved_path( - def, - resolved_segment, - remaining_segments_for_ty, - true, - ); + let (ty, _) = self.with_body_ty_lowering(|ctx| { + ctx.lower_partly_resolved_path( + def, + resolved_segment, + remaining_segments_for_ty, + true, + ) + }); if ty.is_unknown() { return None; } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs index f7db9489980b..ed1ee4837494 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs @@ -34,6 +34,7 @@ use hir_def::{ resolver::{HasResolver, LifetimeNs, Resolver, TypeNs}, type_ref::{ ConstRef, LifetimeRef, TraitBoundModifier, TraitRef as HirTraitRef, TypeBound, TypeRef, + TypeRefId, TypesMap, TypesSourceMap, }, AdtId, AssocItemId, CallableDefId, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, GenericParamId, HasModule, ImplId, InTypeConstLoc, ItemContainerId, @@ -41,7 +42,6 @@ use hir_def::{ TypeOwnerId, UnionId, VariantId, }; use hir_expand::{name::Name, ExpandResult}; -use intern::Interned; use la_arena::{Arena, ArenaMap}; use rustc_hash::FxHashSet; use rustc_pattern_analysis::Captures; @@ -122,6 +122,11 @@ pub struct TyLoweringContext<'a> { pub db: &'a dyn HirDatabase, resolver: &'a Resolver, generics: OnceCell>, + types_map: &'a TypesMap, + /// If this is set, that means we're in a context of a freshly expanded macro, and that means + /// we should not use `TypeRefId` in diagnostics because the caller won't have the `TypesMap`, + /// instead we need to put `TypeSource` from the source map. + types_source_map: Option<&'a TypesSourceMap>, in_binders: DebruijnIndex, // FIXME: Should not be an `Option` but `Resolver` currently does not return owners in all cases // where expected @@ -138,13 +143,20 @@ pub struct TyLoweringContext<'a> { } impl<'a> TyLoweringContext<'a> { - pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver, owner: TypeOwnerId) -> Self { - Self::new_maybe_unowned(db, resolver, Some(owner)) + pub fn new( + db: &'a dyn HirDatabase, + resolver: &'a Resolver, + types_map: &'a TypesMap, + owner: TypeOwnerId, + ) -> Self { + Self::new_maybe_unowned(db, resolver, types_map, None, Some(owner)) } pub fn new_maybe_unowned( db: &'a dyn HirDatabase, resolver: &'a Resolver, + types_map: &'a TypesMap, + types_source_map: Option<&'a TypesSourceMap>, owner: Option, ) -> Self { let impl_trait_mode = ImplTraitLoweringState::Disallowed; @@ -154,6 +166,8 @@ impl<'a> TyLoweringContext<'a> { db, resolver, generics: OnceCell::new(), + types_map, + types_source_map, owner, in_binders, impl_trait_mode, @@ -201,6 +215,16 @@ impl<'a> TyLoweringContext<'a> { pub fn with_type_param_mode(self, type_param_mode: ParamLoweringMode) -> Self { Self { type_param_mode, ..self } } + + pub fn impl_trait_mode(&mut self, impl_trait_mode: ImplTraitLoweringMode) -> &mut Self { + self.impl_trait_mode = ImplTraitLoweringState::new(impl_trait_mode); + self + } + + pub fn type_param_mode(&mut self, type_param_mode: ParamLoweringMode) -> &mut Self { + self.type_param_mode = type_param_mode; + self + } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -230,7 +254,7 @@ pub enum ParamLoweringMode { } impl<'a> TyLoweringContext<'a> { - pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty { + pub fn lower_ty(&self, type_ref: TypeRefId) -> Ty { self.lower_ty_ext(type_ref).0 } @@ -254,12 +278,13 @@ impl<'a> TyLoweringContext<'a> { .as_ref() } - pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { + pub fn lower_ty_ext(&self, type_ref_id: TypeRefId) -> (Ty, Option) { let mut res = None; + let type_ref = &self.types_map[type_ref_id]; let ty = match type_ref { TypeRef::Never => TyKind::Never.intern(Interner), TypeRef::Tuple(inner) => { - let inner_tys = inner.iter().map(|tr| self.lower_ty(tr)); + let inner_tys = inner.iter().map(|&tr| self.lower_ty(tr)); TyKind::Tuple(inner_tys.len(), Substitution::from_iter(Interner, inner_tys)) .intern(Interner) } @@ -268,21 +293,21 @@ impl<'a> TyLoweringContext<'a> { res = res_; ty } - TypeRef::RawPtr(inner, mutability) => { + &TypeRef::RawPtr(inner, mutability) => { let inner_ty = self.lower_ty(inner); - TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(Interner) + TyKind::Raw(lower_to_chalk_mutability(mutability), inner_ty).intern(Interner) } TypeRef::Array(inner, len) => { - let inner_ty = self.lower_ty(inner); + let inner_ty = self.lower_ty(*inner); let const_len = self.lower_const(len, TyBuilder::usize()); TyKind::Array(inner_ty, const_len).intern(Interner) } - TypeRef::Slice(inner) => { + &TypeRef::Slice(inner) => { let inner_ty = self.lower_ty(inner); TyKind::Slice(inner_ty).intern(Interner) } TypeRef::Reference(inner, lifetime, mutability) => { - let inner_ty = self.lower_ty(inner); + let inner_ty = self.lower_ty(*inner); // FIXME: It should infer the eldided lifetimes instead of stubbing with static let lifetime = lifetime.as_ref().map_or_else(error_lifetime, |lr| self.lower_lifetime(lr)); @@ -290,9 +315,12 @@ impl<'a> TyLoweringContext<'a> { .intern(Interner) } TypeRef::Placeholder => TyKind::Error.intern(Interner), - &TypeRef::Fn(ref params, variadic, is_unsafe, ref abi) => { + &TypeRef::Fn { ref params, is_varargs: variadic, is_unsafe, ref abi } => { let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { - Substitution::from_iter(Interner, params.iter().map(|(_, tr)| ctx.lower_ty(tr))) + Substitution::from_iter( + Interner, + params.iter().map(|&(_, tr)| ctx.lower_ty(tr)), + ) }); TyKind::Function(FnPointer { num_binders: 0, // FIXME lower `for<'a> fn()` correctly @@ -351,8 +379,8 @@ impl<'a> TyLoweringContext<'a> { ImplTraitLoweringState::Param(counter) => { let idx = counter.get(); // Count the number of `impl Trait` things that appear within our bounds. - // Since t hose have been emitted as implicit type args already. - counter.set(idx + count_impl_traits(type_ref) as u16); + // Since those have been emitted as implicit type args already. + counter.set(idx + self.count_impl_traits(type_ref_id) as u16); let kind = self .generics() .expect("param impl trait lowering must be in a generic def") @@ -376,7 +404,7 @@ impl<'a> TyLoweringContext<'a> { let idx = counter.get(); // Count the number of `impl Trait` things that appear within our bounds. // Since t hose have been emitted as implicit type args already. - counter.set(idx + count_impl_traits(type_ref) as u16); + counter.set(idx + self.count_impl_traits(type_ref_id) as u16); let kind = self .generics() .expect("variable impl trait lowering must be in a generic def") @@ -432,12 +460,40 @@ impl<'a> TyLoweringContext<'a> { match expander.enter_expand::(self.db.upcast(), macro_call, resolver) { Ok(ExpandResult { value: Some((mark, expanded)), .. }) => { - let ctx = expander.ctx(self.db.upcast()); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + + let ctx = expander.ctx( + self.db.upcast(), + &mut types_map, + &mut types_source_map, + ); // FIXME: Report syntax errors in expansion here let type_ref = TypeRef::from_ast(&ctx, expanded.tree()); drop(expander); - let ty = self.lower_ty(&type_ref); + + // FIXME: That may be better served by mutating `self` then restoring, but this requires + // making it `&mut self`. + let inner_ctx = TyLoweringContext { + db: self.db, + resolver: self.resolver, + generics: self.generics.clone(), + types_map: &types_map, + types_source_map: Some(&types_source_map), + in_binders: self.in_binders, + owner: self.owner, + type_param_mode: self.type_param_mode, + impl_trait_mode: self.impl_trait_mode.take(), + expander: RefCell::new(self.expander.take()), + unsized_types: RefCell::new(self.unsized_types.take()), + }; + + let ty = inner_ctx.lower_ty(type_ref); + + self.impl_trait_mode.swap(&inner_ctx.impl_trait_mode); + *self.expander.borrow_mut() = inner_ctx.expander.into_inner(); + *self.unsized_types.borrow_mut() = inner_ctx.unsized_types.into_inner(); self.expander.borrow_mut().as_mut().unwrap().exit(mark); Some(ty) @@ -463,7 +519,8 @@ impl<'a> TyLoweringContext<'a> { /// This is only for `generic_predicates_for_param`, where we can't just /// lower the self types of the predicates since that could lead to cycles. /// So we just check here if the `type_ref` resolves to a generic param, and which. - fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option { + fn lower_ty_only_param(&self, type_ref: TypeRefId) -> Option { + let type_ref = &self.types_map[type_ref]; let path = match type_ref { TypeRef::Path(path) => path, _ => return None, @@ -663,7 +720,7 @@ impl<'a> TyLoweringContext<'a> { if matches!(resolution, TypeNs::TraitId(_)) && remaining_index.is_none() { // trait object type without dyn let bound = TypeBound::Path(path.clone(), TraitBoundModifier::None); - let ty = self.lower_dyn_trait(&[Interned::new(bound)]); + let ty = self.lower_dyn_trait(&[bound]); return (ty, None); } @@ -864,7 +921,7 @@ impl<'a> TyLoweringContext<'a> { assert!(matches!(id, GenericParamId::TypeParamId(_))); had_explicit_args = true; if let GenericArg::Type(ty) = &args[0] { - substs.push(self.lower_ty(ty).cast(Interner)); + substs.push(self.lower_ty(*ty).cast(Interner)); } } } else { @@ -901,6 +958,7 @@ impl<'a> TyLoweringContext<'a> { id, arg, &mut (), + self.types_map, |_, type_ref| self.lower_ty(type_ref), |_, const_ref, ty| self.lower_const(const_ref, ty), |_, lifetime_ref| self.lower_lifetime(lifetime_ref), @@ -998,7 +1056,7 @@ impl<'a> TyLoweringContext<'a> { WherePredicate::ForLifetime { target, bound, .. } | WherePredicate::TypeBound { target, bound } => { let self_ty = match target { - WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref), + WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(*type_ref), &WherePredicateTypeTarget::TypeOrConstParam(local_id) => { let param_id = hir_def::TypeOrConstParamId { parent: def, local_id }; match self.type_param_mode { @@ -1029,12 +1087,12 @@ impl<'a> TyLoweringContext<'a> { pub(crate) fn lower_type_bound( &'a self, - bound: &'a Interned, + bound: &'a TypeBound, self_ty: Ty, ignore_bindings: bool, ) -> impl Iterator + 'a { let mut trait_ref = None; - let clause = match bound.as_ref() { + let clause = match bound { TypeBound::Path(path, TraitBoundModifier::None) => { trait_ref = self.lower_trait_ref_from_path(path, self_ty); trait_ref.clone().map(WhereClause::Implemented).map(crate::wrap_empty_binders) @@ -1079,10 +1137,10 @@ impl<'a> TyLoweringContext<'a> { fn assoc_type_bindings_from_type_bound( &'a self, - bound: &'a Interned, + bound: &'a TypeBound, trait_ref: TraitRef, ) -> impl Iterator + 'a { - let last_segment = match bound.as_ref() { + let last_segment = match bound { TypeBound::Path(path, TraitBoundModifier::None) | TypeBound::ForLifetime(_, path) => { path.segments().last() } @@ -1111,7 +1169,7 @@ impl<'a> TyLoweringContext<'a> { // this point (`super_trait_ref.substitution`). let substitution = self.substs_from_path_segment( // FIXME: This is hack. We shouldn't really build `PathSegment` directly. - PathSegment { name: &binding.name, args_and_bindings: binding.args.as_deref() }, + PathSegment { name: &binding.name, args_and_bindings: binding.args.as_ref() }, Some(associated_ty.into()), false, // this is not relevant Some(super_trait_ref.self_type_parameter(Interner)), @@ -1131,8 +1189,8 @@ impl<'a> TyLoweringContext<'a> { let mut predicates: SmallVec<[_; 1]> = SmallVec::with_capacity( binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(), ); - if let Some(type_ref) = &binding.type_ref { - match (type_ref, &self.impl_trait_mode) { + if let Some(type_ref) = binding.type_ref { + match (&self.types_map[type_ref], &self.impl_trait_mode) { (TypeRef::ImplTrait(_), ImplTraitLoweringState::Disallowed) => (), ( _, @@ -1179,6 +1237,8 @@ impl<'a> TyLoweringContext<'a> { let mut ext = TyLoweringContext::new_maybe_unowned( self.db, self.resolver, + self.types_map, + self.types_source_map, self.owner, ) .with_type_param_mode(self.type_param_mode); @@ -1216,7 +1276,7 @@ impl<'a> TyLoweringContext<'a> { }) } - fn lower_dyn_trait(&self, bounds: &[Interned]) -> Ty { + fn lower_dyn_trait(&self, bounds: &[TypeBound]) -> Ty { let self_ty = TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(Interner); // INVARIANT: The principal trait bound, if present, must come first. Others may be in any // order but should be in the same order for the same set but possibly different order of @@ -1314,7 +1374,7 @@ impl<'a> TyLoweringContext<'a> { } } - fn lower_impl_trait(&self, bounds: &[Interned], krate: CrateId) -> ImplTrait { + fn lower_impl_trait(&self, bounds: &[TypeBound], krate: CrateId) -> ImplTrait { cov_mark::hit!(lower_rpit); let self_ty = TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(Interner); let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { @@ -1366,6 +1426,17 @@ impl<'a> TyLoweringContext<'a> { None => error_lifetime(), } } + + // FIXME: This does not handle macros! + fn count_impl_traits(&self, type_ref: TypeRefId) -> usize { + let mut count = 0; + TypeRef::walk(type_ref, self.types_map, &mut |type_ref| { + if matches!(type_ref, TypeRef::ImplTrait(_)) { + count += 1; + } + }); + count + } } /// Build the signature of a callable item (function, struct or enum variant). @@ -1386,17 +1457,6 @@ pub fn associated_type_shorthand_candidates( named_associated_type_shorthand_candidates(db, def, res, None, |name, _, id| cb(name, id)) } -// FIXME: This does not handle macros! -fn count_impl_traits(type_ref: &TypeRef) -> usize { - let mut count = 0; - type_ref.walk(&mut |type_ref| { - if matches!(type_ref, TypeRef::ImplTrait(_)) { - count += 1; - } - }); - count -} - fn named_associated_type_shorthand_candidates( db: &dyn HirDatabase, // If the type parameter is defined in an impl and we're in a method, there @@ -1500,10 +1560,10 @@ pub(crate) fn field_types_query( }; let generics = generics(db.upcast(), def); let mut res = ArenaMap::default(); - let ctx = TyLoweringContext::new(db, &resolver, def.into()) + let ctx = TyLoweringContext::new(db, &resolver, var_data.types_map(), def.into()) .with_type_param_mode(ParamLoweringMode::Variable); for (field_id, field_data) in var_data.fields().iter() { - res.insert(field_id, make_binders(db, &generics, ctx.lower_ty(&field_data.type_ref))); + res.insert(field_id, make_binders(db, &generics, ctx.lower_ty(field_data.type_ref))); } Arc::new(res) } @@ -1523,38 +1583,38 @@ pub(crate) fn generic_predicates_for_param_query( assoc_name: Option, ) -> GenericPredicates { let resolver = def.resolver(db.upcast()); - let ctx = if let GenericDefId::FunctionId(_) = def { - TyLoweringContext::new(db, &resolver, def.into()) + let mut ctx = if let GenericDefId::FunctionId(_) = def { + TyLoweringContext::new(db, &resolver, TypesMap::EMPTY, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Variable) .with_type_param_mode(ParamLoweringMode::Variable) } else { - TyLoweringContext::new(db, &resolver, def.into()) + TyLoweringContext::new(db, &resolver, TypesMap::EMPTY, def.into()) .with_type_param_mode(ParamLoweringMode::Variable) }; let generics = generics(db.upcast(), def); // we have to filter out all other predicates *first*, before attempting to lower them - let predicate = |(pred, &def): &(&_, _)| match pred { + let predicate = |pred: &_, def: &_, ctx: &TyLoweringContext<'_>| match pred { WherePredicate::ForLifetime { target, bound, .. } | WherePredicate::TypeBound { target, bound, .. } => { let invalid_target = match target { WherePredicateTypeTarget::TypeRef(type_ref) => { - ctx.lower_ty_only_param(type_ref) != Some(param_id) + ctx.lower_ty_only_param(*type_ref) != Some(param_id) } &WherePredicateTypeTarget::TypeOrConstParam(local_id) => { - let target_id = TypeOrConstParamId { parent: def, local_id }; + let target_id = TypeOrConstParamId { parent: *def, local_id }; target_id != param_id } }; if invalid_target { // If this is filtered out without lowering, `?Sized` is not gathered into `ctx.unsized_types` - if let TypeBound::Path(_, TraitBoundModifier::Maybe) = &**bound { - ctx.lower_where_predicate(pred, &def, true).for_each(drop); + if let TypeBound::Path(_, TraitBoundModifier::Maybe) = bound { + ctx.lower_where_predicate(pred, def, true).for_each(drop); } return false; } - match &**bound { + match bound { TypeBound::ForLifetime(_, path) | TypeBound::Path(path, _) => { // Only lower the bound if the trait could possibly define the associated // type we're looking for. @@ -1577,13 +1637,15 @@ pub(crate) fn generic_predicates_for_param_query( } WherePredicate::Lifetime { .. } => false, }; - let mut predicates: Vec<_> = resolver - .where_predicates_in_scope() - .filter(predicate) - .flat_map(|(pred, def)| { - ctx.lower_where_predicate(pred, def, true).map(|p| make_binders(db, &generics, p)) - }) - .collect(); + let mut predicates = Vec::new(); + for (params, def) in resolver.all_generic_params() { + ctx.types_map = ¶ms.types_map; + predicates.extend( + params.where_predicates().filter(|pred| predicate(pred, def, &ctx)).flat_map(|pred| { + ctx.lower_where_predicate(pred, def, true).map(|p| make_binders(db, &generics, p)) + }), + ); + } let subst = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); if !subst.is_empty(Interner) { @@ -1630,23 +1692,27 @@ pub(crate) fn trait_environment_query( def: GenericDefId, ) -> Arc { let resolver = def.resolver(db.upcast()); - let ctx = if let GenericDefId::FunctionId(_) = def { - TyLoweringContext::new(db, &resolver, def.into()) + let mut ctx = if let GenericDefId::FunctionId(_) = def { + TyLoweringContext::new(db, &resolver, TypesMap::EMPTY, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Param) .with_type_param_mode(ParamLoweringMode::Placeholder) } else { - TyLoweringContext::new(db, &resolver, def.into()) + TyLoweringContext::new(db, &resolver, TypesMap::EMPTY, def.into()) .with_type_param_mode(ParamLoweringMode::Placeholder) }; let mut traits_in_scope = Vec::new(); let mut clauses = Vec::new(); - for (pred, def) in resolver.where_predicates_in_scope() { - for pred in ctx.lower_where_predicate(pred, def, false) { - if let WhereClause::Implemented(tr) = &pred.skip_binders() { - traits_in_scope.push((tr.self_type_parameter(Interner).clone(), tr.hir_trait_id())); + for (params, def) in resolver.all_generic_params() { + ctx.types_map = ¶ms.types_map; + for pred in params.where_predicates() { + for pred in ctx.lower_where_predicate(pred, def, false) { + if let WhereClause::Implemented(tr) = pred.skip_binders() { + traits_in_scope + .push((tr.self_type_parameter(Interner).clone(), tr.hir_trait_id())); + } + let program_clause: chalk_ir::ProgramClause = pred.cast(Interner); + clauses.push(program_clause.into_from_env_clause(Interner)); } - let program_clause: chalk_ir::ProgramClause = pred.cast(Interner); - clauses.push(program_clause.into_from_env_clause(Interner)); } } @@ -1725,18 +1791,20 @@ where } _ => (ImplTraitLoweringMode::Disallowed, ParamLoweringMode::Variable), }; - let ctx = TyLoweringContext::new(db, &resolver, def.into()) + let mut ctx = TyLoweringContext::new(db, &resolver, TypesMap::EMPTY, def.into()) .with_impl_trait_mode(impl_trait_lowering) .with_type_param_mode(param_lowering); let generics = generics(db.upcast(), def); - let mut predicates = resolver - .where_predicates_in_scope() - .filter(|(pred, def)| filter(pred, def)) - .flat_map(|(pred, def)| { - ctx.lower_where_predicate(pred, def, false).map(|p| make_binders(db, &generics, p)) - }) - .collect::>(); + let mut predicates = Vec::new(); + for (params, def) in resolver.all_generic_params() { + ctx.types_map = ¶ms.types_map; + predicates.extend(params.where_predicates().filter(|pred| filter(pred, def)).flat_map( + |pred| { + ctx.lower_where_predicate(pred, def, false).map(|p| make_binders(db, &generics, p)) + }, + )); + } if generics.len() > 0 { let subst = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); @@ -1812,18 +1880,19 @@ pub(crate) fn generic_defaults_query(db: &dyn HirDatabase, def: GenericDefId) -> let resolver = def.resolver(db.upcast()); let parent_start_idx = generic_params.len_self(); - let ctx = TyLoweringContext::new(db, &resolver, def.into()) + let mut ctx = TyLoweringContext::new(db, &resolver, TypesMap::EMPTY, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Disallowed) .with_type_param_mode(ParamLoweringMode::Variable); - GenericDefaults(Some(Arc::from_iter(generic_params.iter().enumerate().map( - |(idx, (id, p))| { + GenericDefaults(Some(Arc::from_iter(generic_params.iter_with_types_map().enumerate().map( + |(idx, ((id, p), types_map))| { + ctx.types_map = types_map; match p { GenericParamDataRef::TypeParamData(p) => { let ty = p.default.as_ref().map_or(TyKind::Error.intern(Interner), |ty| { // Each default can only refer to previous parameters. // Type variable default referring to parameter coming // after it is forbidden (FIXME: report diagnostic) - fallback_bound_vars(ctx.lower_ty(ty), idx, parent_start_idx) + fallback_bound_vars(ctx.lower_ty(*ty), idx, parent_start_idx) }); crate::make_binders(db, &generic_params, ty.cast(Interner)) } @@ -1835,7 +1904,7 @@ pub(crate) fn generic_defaults_query(db: &dyn HirDatabase, def: GenericDefId) -> let mut val = p.default.as_ref().map_or_else( || unknown_const_as_generic(db.const_param_ty(id)), |c| { - let c = ctx.lower_const(c, ctx.lower_ty(&p.ty)); + let c = ctx.lower_const(c, ctx.lower_ty(p.ty)); c.cast(Interner) }, ); @@ -1875,14 +1944,14 @@ pub(crate) fn generic_defaults_recover( fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig { let data = db.function_data(def); let resolver = def.resolver(db.upcast()); - let ctx_params = TyLoweringContext::new(db, &resolver, def.into()) + let ctx_params = TyLoweringContext::new(db, &resolver, &data.types_map, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Variable) .with_type_param_mode(ParamLoweringMode::Variable); - let params = data.params.iter().map(|tr| ctx_params.lower_ty(tr)); - let ctx_ret = TyLoweringContext::new(db, &resolver, def.into()) + let params = data.params.iter().map(|&tr| ctx_params.lower_ty(tr)); + let ctx_ret = TyLoweringContext::new(db, &resolver, &data.types_map, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_type_param_mode(ParamLoweringMode::Variable); - let ret = ctx_ret.lower_ty(&data.ret_type); + let ret = ctx_ret.lower_ty(data.ret_type); let generics = generics(db.upcast(), def.into()); let sig = CallableSig::from_params_and_return( params, @@ -1911,28 +1980,33 @@ fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders { let data = db.const_data(def); let generics = generics(db.upcast(), def.into()); let resolver = def.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, def.into()) + let ctx = TyLoweringContext::new(db, &resolver, &data.types_map, def.into()) .with_type_param_mode(ParamLoweringMode::Variable); - make_binders(db, &generics, ctx.lower_ty(&data.type_ref)) + make_binders(db, &generics, ctx.lower_ty(data.type_ref)) } /// Build the declared type of a static. fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders { let data = db.static_data(def); let resolver = def.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, def.into()); + let ctx = TyLoweringContext::new(db, &resolver, &data.types_map, def.into()); - Binders::empty(Interner, ctx.lower_ty(&data.type_ref)) + Binders::empty(Interner, ctx.lower_ty(data.type_ref)) } fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig { let struct_data = db.struct_data(def); let fields = struct_data.variant_data.fields(); let resolver = def.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, AdtId::from(def).into()) - .with_type_param_mode(ParamLoweringMode::Variable); - let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)); + let ctx = TyLoweringContext::new( + db, + &resolver, + struct_data.variant_data.types_map(), + AdtId::from(def).into(), + ) + .with_type_param_mode(ParamLoweringMode::Variable); + let params = fields.iter().map(|(_, field)| ctx.lower_ty(field.type_ref)); let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders(); Binders::new( binders, @@ -1962,9 +2036,14 @@ fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) let var_data = db.enum_variant_data(def); let fields = var_data.variant_data.fields(); let resolver = def.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, DefWithBodyId::VariantId(def).into()) - .with_type_param_mode(ParamLoweringMode::Variable); - let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)); + let ctx = TyLoweringContext::new( + db, + &resolver, + var_data.variant_data.types_map(), + DefWithBodyId::VariantId(def).into(), + ) + .with_type_param_mode(ParamLoweringMode::Variable); + let params = fields.iter().map(|(_, field)| ctx.lower_ty(field.type_ref)); let (ret, binders) = type_for_adt(db, def.lookup(db.upcast()).parent.into()).into_value_and_skipped_binders(); Binders::new( @@ -2005,15 +2084,17 @@ fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders { fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders { let generics = generics(db.upcast(), t.into()); let resolver = t.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, t.into()) + let type_alias_data = db.type_alias_data(t); + let ctx = TyLoweringContext::new(db, &resolver, &type_alias_data.types_map, t.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_type_param_mode(ParamLoweringMode::Variable); - let type_alias_data = db.type_alias_data(t); let inner = if type_alias_data.is_extern { TyKind::Foreign(crate::to_foreign_def_id(t)).intern(Interner) } else { - let type_ref = &type_alias_data.type_ref; - ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error)) + type_alias_data + .type_ref + .map(|type_ref| ctx.lower_ty(type_ref)) + .unwrap_or_else(|| TyKind::Error.intern(Interner)) }; make_binders(db, &generics, inner) } @@ -2086,9 +2167,9 @@ pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binde let impl_data = db.impl_data(impl_id); let resolver = impl_id.resolver(db.upcast()); let generics = generics(db.upcast(), impl_id.into()); - let ctx = TyLoweringContext::new(db, &resolver, impl_id.into()) + let ctx = TyLoweringContext::new(db, &resolver, &impl_data.types_map, impl_id.into()) .with_type_param_mode(ParamLoweringMode::Variable); - make_binders(db, &generics, ctx.lower_ty(&impl_data.self_ty)) + make_binders(db, &generics, ctx.lower_ty(impl_data.self_ty)) } // returns None if def is a type arg @@ -2096,13 +2177,13 @@ pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> T let parent_data = db.generic_params(def.parent()); let data = &parent_data[def.local_id()]; let resolver = def.parent().resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, def.parent().into()); + let ctx = TyLoweringContext::new(db, &resolver, &parent_data.types_map, def.parent().into()); match data { TypeOrConstParamData::TypeParamData(_) => { never!(); Ty::new(Interner, TyKind::Error) } - TypeOrConstParamData::ConstParamData(d) => ctx.lower_ty(&d.ty), + TypeOrConstParamData::ConstParamData(d) => ctx.lower_ty(d.ty), } } @@ -2118,7 +2199,7 @@ pub(crate) fn impl_self_ty_recover( pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option> { let impl_data = db.impl_data(impl_id); let resolver = impl_id.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, impl_id.into()) + let ctx = TyLoweringContext::new(db, &resolver, &impl_data.types_map, impl_id.into()) .with_type_param_mode(ParamLoweringMode::Variable); let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders(); let target_trait = impl_data.target_trait.as_ref()?; @@ -2132,10 +2213,10 @@ pub(crate) fn return_type_impl_traits( // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe let data = db.function_data(def); let resolver = def.resolver(db.upcast()); - let ctx_ret = TyLoweringContext::new(db, &resolver, def.into()) + let ctx_ret = TyLoweringContext::new(db, &resolver, &data.types_map, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_type_param_mode(ParamLoweringMode::Variable); - let _ret = ctx_ret.lower_ty(&data.ret_type); + let _ret = ctx_ret.lower_ty(data.ret_type); let generics = generics(db.upcast(), def.into()); let return_type_impl_traits = ImplTraits { impl_traits: match ctx_ret.impl_trait_mode { @@ -2156,10 +2237,10 @@ pub(crate) fn type_alias_impl_traits( ) -> Option>> { let data = db.type_alias_data(def); let resolver = def.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver, def.into()) + let ctx = TyLoweringContext::new(db, &resolver, &data.types_map, def.into()) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_type_param_mode(ParamLoweringMode::Variable); - if let Some(type_ref) = &data.type_ref { + if let Some(type_ref) = data.type_ref { let _ty = ctx.lower_ty(type_ref); } let type_alias_impl_traits = ImplTraits { @@ -2191,7 +2272,8 @@ pub(crate) fn generic_arg_to_chalk<'a, T>( kind_id: GenericParamId, arg: &'a GenericArg, this: &mut T, - for_type: impl FnOnce(&mut T, &TypeRef) -> Ty + 'a, + types_map: &TypesMap, + for_type: impl FnOnce(&mut T, TypeRefId) -> Ty + 'a, for_const: impl FnOnce(&mut T, &ConstRef, Ty) -> Const + 'a, for_lifetime: impl FnOnce(&mut T, &LifetimeRef) -> Lifetime + 'a, ) -> crate::GenericArg { @@ -2204,7 +2286,7 @@ pub(crate) fn generic_arg_to_chalk<'a, T>( GenericParamId::LifetimeParamId(_) => ParamKind::Lifetime, }; match (arg, kind) { - (GenericArg::Type(type_ref), ParamKind::Type) => for_type(this, type_ref).cast(Interner), + (GenericArg::Type(type_ref), ParamKind::Type) => for_type(this, *type_ref).cast(Interner), (GenericArg::Const(c), ParamKind::Const(c_ty)) => for_const(this, c, c_ty).cast(Interner), (GenericArg::Lifetime(lifetime_ref), ParamKind::Lifetime) => { for_lifetime(this, lifetime_ref).cast(Interner) @@ -2215,7 +2297,7 @@ pub(crate) fn generic_arg_to_chalk<'a, T>( // We want to recover simple idents, which parser detects them // as types. Maybe here is not the best place to do it, but // it works. - if let TypeRef::Path(p) = t { + if let TypeRef::Path(p) = &types_map[*t] { if let Some(p) = p.mod_path() { if p.kind == PathKind::Plain { if let [n] = p.segments() { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs index b7b565dece8d..e73b9dc27d12 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs @@ -2849,7 +2849,8 @@ impl Evaluator<'_> { } let layout = self.layout_adt(id.0, subst.clone())?; match data.variant_data.as_ref() { - VariantData::Record(fields) | VariantData::Tuple(fields) => { + VariantData::Record { fields, .. } + | VariantData::Tuple { fields, .. } => { let field_types = self.db.field_types(s.into()); for (field, _) in fields.iter() { let offset = layout diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs index 99a4e112f8b2..333942276069 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs @@ -14,6 +14,7 @@ use hir_def::{ lang_item::{LangItem, LangItemTarget}, path::Path, resolver::{HasResolver, ResolveValueResult, Resolver, ValueNs}, + type_ref::TypesMap, AdtId, DefWithBodyId, EnumVariantId, GeneralConstId, HasModule, ItemContainerId, LocalFieldId, Lookup, TraitId, TupleId, TypeOrConstParamId, }; @@ -28,7 +29,7 @@ use triomphe::Arc; use crate::{ consteval::ConstEvalError, db::{HirDatabase, InternedClosure}, - display::HirDisplay, + display::{hir_display_with_types_map, HirDisplay}, error_lifetime, generics::generics, infer::{cast::CastTy, unify::InferenceTable, CaptureKind, CapturedItem, TypeMismatch}, @@ -247,8 +248,15 @@ impl From for MirLowerError { } impl MirLowerError { - fn unresolved_path(db: &dyn HirDatabase, p: &Path, edition: Edition) -> Self { - Self::UnresolvedName(p.display(db, edition).to_string()) + fn unresolved_path( + db: &dyn HirDatabase, + p: &Path, + edition: Edition, + types_map: &TypesMap, + ) -> Self { + Self::UnresolvedName( + hir_display_with_types_map(p, types_map).display(db, edition).to_string(), + ) } } @@ -451,7 +459,12 @@ impl<'ctx> MirLowerCtx<'ctx> { .resolver .resolve_path_in_value_ns_fully(self.db.upcast(), p, hygiene) .ok_or_else(|| { - MirLowerError::unresolved_path(self.db, p, self.edition()) + MirLowerError::unresolved_path( + self.db, + p, + self.edition(), + &self.body.types, + ) })?; self.resolver.reset_to_guard(resolver_guard); result @@ -824,7 +837,9 @@ impl<'ctx> MirLowerCtx<'ctx> { let variant_id = self.infer.variant_resolution_for_expr(expr_id).ok_or_else(|| match path { Some(p) => MirLowerError::UnresolvedName( - p.display(self.db, self.edition()).to_string(), + hir_display_with_types_map(&**p, &self.body.types) + .display(self.db, self.edition()) + .to_string(), ), None => MirLowerError::RecordLiteralWithoutPath, })?; @@ -1358,8 +1373,9 @@ impl<'ctx> MirLowerCtx<'ctx> { ), }; let edition = self.edition(); - let unresolved_name = - || MirLowerError::unresolved_path(self.db, c.as_ref(), edition); + let unresolved_name = || { + MirLowerError::unresolved_path(self.db, c.as_ref(), edition, &self.body.types) + }; let pr = self .resolver .resolve_path_in_value_ns(self.db.upcast(), c.as_ref(), HygieneId::ROOT) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs index d985a6451b7d..2ffea34c85a1 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -349,8 +349,9 @@ impl MirLowerCtx<'_> { mode, )?, None => { - let unresolved_name = - || MirLowerError::unresolved_path(self.db, p, self.edition()); + let unresolved_name = || { + MirLowerError::unresolved_path(self.db, p, self.edition(), &self.body.types) + }; let hygiene = self.body.pat_path_hygiene(pattern); let pr = self .resolver diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs index 98e8feceb063..0a436ff2b41a 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs @@ -163,10 +163,12 @@ fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId, cb: impl FnMut(Tra WherePredicate::ForLifetime { target, bound, .. } | WherePredicate::TypeBound { target, bound } => { let is_trait = match target { - WherePredicateTypeTarget::TypeRef(type_ref) => match &**type_ref { - TypeRef::Path(p) => p.is_self_type(), - _ => false, - }, + WherePredicateTypeTarget::TypeRef(type_ref) => { + match &generic_params.types_map[*type_ref] { + TypeRef::Path(p) => p.is_self_type(), + _ => false, + } + } WherePredicateTypeTarget::TypeOrConstParam(local_id) => { Some(*local_id) == trait_self } diff --git a/src/tools/rust-analyzer/crates/hir/src/display.rs b/src/tools/rust-analyzer/crates/hir/src/display.rs index c2b2fbef7517..80370c7421e6 100644 --- a/src/tools/rust-analyzer/crates/hir/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir/src/display.rs @@ -12,12 +12,11 @@ use hir_def::{ }; use hir_ty::{ display::{ - write_bounds_like_dyn_trait_with_prefix, write_visibility, HirDisplay, HirDisplayError, - HirFormatter, SizedByDefault, + hir_display_with_types_map, write_bounds_like_dyn_trait_with_prefix, write_visibility, + HirDisplay, HirDisplayError, HirDisplayWithTypesMap, HirFormatter, SizedByDefault, }, AliasEq, AliasTy, Interner, ProjectionTyExt, TraitRefExt, TyKind, WhereClause, }; -use intern::Interned; use itertools::Itertools; use crate::{ @@ -113,7 +112,7 @@ impl HirDisplay for Function { f.write_str(&pat_str)?; f.write_str(": ")?; - type_ref.hir_fmt(f)?; + type_ref.hir_fmt(f, &data.types_map)?; } if data.is_varargs() { @@ -129,28 +128,30 @@ impl HirDisplay for Function { // Use ugly pattern match to strip the Future trait. // Better way? let ret_type = if !data.is_async() { - &data.ret_type + Some(data.ret_type) } else { - match &*data.ret_type { - TypeRef::ImplTrait(bounds) => match bounds[0].as_ref() { - TypeBound::Path(path, _) => { - path.segments().iter().last().unwrap().args_and_bindings.unwrap().bindings + match &data.types_map[data.ret_type] { + TypeRef::ImplTrait(bounds) => match &bounds[0] { + TypeBound::Path(path, _) => Some( + *path.segments().iter().last().unwrap().args_and_bindings.unwrap().bindings [0] .type_ref .as_ref() - .unwrap() - } - _ => &TypeRef::Error, + .unwrap(), + ), + _ => None, }, - _ => &TypeRef::Error, + _ => None, } }; - match ret_type { - TypeRef::Tuple(tup) if tup.is_empty() => {} - ty => { - f.write_str(" -> ")?; - ty.hir_fmt(f)?; + if let Some(ret_type) = ret_type { + match &data.types_map[ret_type] { + TypeRef::Tuple(tup) if tup.is_empty() => {} + _ => { + f.write_str(" -> ")?; + ret_type.hir_fmt(f, &data.types_map)?; + } } } @@ -192,10 +193,10 @@ fn write_impl_header(impl_: &Impl, f: &mut HirFormatter<'_>) -> Result<(), HirDi impl HirDisplay for SelfParam { fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> { let data = f.db.function_data(self.func); - let param = data.params.first().unwrap(); - match &**param { + let param = *data.params.first().unwrap(); + match &data.types_map[param] { TypeRef::Path(p) if p.is_self_type() => f.write_str("self"), - TypeRef::Reference(inner, lifetime, mut_) if matches!(&**inner, TypeRef::Path(p) if p.is_self_type()) => + TypeRef::Reference(inner, lifetime, mut_) if matches!(&data.types_map[*inner], TypeRef::Path(p) if p.is_self_type()) => { f.write_char('&')?; if let Some(lifetime) = lifetime { @@ -206,9 +207,9 @@ impl HirDisplay for SelfParam { } f.write_str("self") } - ty => { + _ => { f.write_str("self: ")?; - ty.hir_fmt(f) + param.hir_fmt(f, &data.types_map) } } } @@ -393,7 +394,7 @@ impl HirDisplay for Variant { let data = self.variant_data(f.db); match &*data { VariantData::Unit => {} - VariantData::Tuple(fields) => { + VariantData::Tuple { fields, types_map } => { f.write_char('(')?; let mut first = true; for (_, field) in fields.iter() { @@ -403,11 +404,11 @@ impl HirDisplay for Variant { f.write_str(", ")?; } // Enum variant fields must be pub. - field.type_ref.hir_fmt(f)?; + field.type_ref.hir_fmt(f, types_map)?; } f.write_char(')')?; } - VariantData::Record(_) => { + VariantData::Record { .. } => { if let Some(limit) = f.entity_limit { write_fields(&self.fields(f.db), false, limit, true, f)?; } @@ -579,13 +580,13 @@ fn write_generic_params( write!(f, "{}", name.display(f.db.upcast(), f.edition()))?; if let Some(default) = &ty.default { f.write_str(" = ")?; - default.hir_fmt(f)?; + default.hir_fmt(f, ¶ms.types_map)?; } } TypeOrConstParamData::ConstParamData(c) => { delim(f)?; write!(f, "const {}: ", name.display(f.db.upcast(), f.edition()))?; - c.ty.hir_fmt(f)?; + c.ty.hir_fmt(f, ¶ms.types_map)?; if let Some(default) = &c.default { f.write_str(" = ")?; @@ -615,7 +616,7 @@ fn write_where_clause( Ok(true) } -fn has_disaplayable_predicates(params: &Interned) -> bool { +fn has_disaplayable_predicates(params: &GenericParams) -> bool { params.where_predicates().any(|pred| { !matches!( pred, @@ -626,21 +627,20 @@ fn has_disaplayable_predicates(params: &Interned) -> bool { } fn write_where_predicates( - params: &Interned, + params: &GenericParams, f: &mut HirFormatter<'_>, ) -> Result<(), HirDisplayError> { use WherePredicate::*; // unnamed type targets are displayed inline with the argument itself, e.g. `f: impl Y`. - let is_unnamed_type_target = - |params: &Interned, target: &WherePredicateTypeTarget| { - matches!(target, - WherePredicateTypeTarget::TypeOrConstParam(id) if params[*id].name().is_none() - ) - }; + let is_unnamed_type_target = |params: &GenericParams, target: &WherePredicateTypeTarget| { + matches!(target, + WherePredicateTypeTarget::TypeOrConstParam(id) if params[*id].name().is_none() + ) + }; let write_target = |target: &WherePredicateTypeTarget, f: &mut HirFormatter<'_>| match target { - WherePredicateTypeTarget::TypeRef(ty) => ty.hir_fmt(f), + WherePredicateTypeTarget::TypeRef(ty) => ty.hir_fmt(f, ¶ms.types_map), WherePredicateTypeTarget::TypeOrConstParam(id) => match params[*id].name() { Some(name) => write!(f, "{}", name.display(f.db.upcast(), f.edition())), None => f.write_str("{unnamed}"), @@ -668,7 +668,7 @@ fn write_where_predicates( TypeBound { target, bound } => { write_target(target, f)?; f.write_str(": ")?; - bound.hir_fmt(f)?; + bound.hir_fmt(f, ¶ms.types_map)?; } Lifetime { target, bound } => { let target = target.name.display(f.db.upcast(), f.edition()); @@ -681,14 +681,16 @@ fn write_where_predicates( write!(f, "for<{lifetimes}> ")?; write_target(target, f)?; f.write_str(": ")?; - bound.hir_fmt(f)?; + bound.hir_fmt(f, ¶ms.types_map)?; } } while let Some(nxt) = iter.next_if(|nxt| check_same_target(pred, nxt)) { f.write_str(" + ")?; match nxt { - TypeBound { bound, .. } | ForLifetime { bound, .. } => bound.hir_fmt(f)?, + TypeBound { bound, .. } | ForLifetime { bound, .. } => { + bound.hir_fmt(f, ¶ms.types_map)? + } Lifetime { bound, .. } => { write!(f, "{}", bound.name.display(f.db.upcast(), f.edition()))? } @@ -716,7 +718,7 @@ impl HirDisplay for Const { Some(name) => write!(f, "{}: ", name.display(f.db.upcast(), f.edition()))?, None => f.write_str("_: ")?, } - data.type_ref.hir_fmt(f)?; + data.type_ref.hir_fmt(f, &data.types_map)?; Ok(()) } } @@ -730,7 +732,7 @@ impl HirDisplay for Static { f.write_str("mut ")?; } write!(f, "{}: ", data.name.display(f.db.upcast(), f.edition()))?; - data.type_ref.hir_fmt(f)?; + data.type_ref.hir_fmt(f, &data.types_map)?; Ok(()) } } @@ -813,11 +815,14 @@ impl HirDisplay for TypeAlias { write_generic_params(def_id, f)?; if !data.bounds.is_empty() { f.write_str(": ")?; - f.write_joined(data.bounds.iter(), " + ")?; + f.write_joined( + data.bounds.iter().map(|bound| hir_display_with_types_map(bound, &data.types_map)), + " + ", + )?; } - if let Some(ty) = &data.type_ref { + if let Some(ty) = data.type_ref { f.write_str(" = ")?; - ty.hir_fmt(f)?; + ty.hir_fmt(f, &data.types_map)?; } write_where_clause(def_id, f)?; Ok(()) diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index 4a18795e7d62..d264bb3901f0 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -2420,7 +2420,7 @@ impl SelfParam { func_data .params .first() - .map(|param| match &**param { + .map(|¶m| match func_data.types_map[param] { TypeRef::Reference(.., mutability) => match mutability { hir_def::type_ref::Mutability::Shared => Access::Shared, hir_def::type_ref::Mutability::Mut => Access::Exclusive, @@ -2747,10 +2747,6 @@ impl TypeAlias { Module { id: self.id.module(db.upcast()) } } - pub fn type_ref(self, db: &dyn HirDatabase) -> Option { - db.type_alias_data(self.id).type_ref.as_deref().cloned() - } - pub fn ty(self, db: &dyn HirDatabase) -> Type { Type::from_def(db, self.id) } diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index 860754d5e704..7e9ce5208d3c 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -16,7 +16,7 @@ use hir_def::{ nameres::{MacroSubNs, ModuleOrigin}, path::ModPath, resolver::{self, HasResolver, Resolver, TypeNs}, - type_ref::Mutability, + type_ref::{Mutability, TypesMap, TypesSourceMap}, AsMacroCall, DefWithBodyId, FunctionId, MacroId, StructId, TraitId, VariantId, }; use hir_expand::{ @@ -1259,19 +1259,28 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_type(&self, ty: &ast::Type) -> Option { let analyze = self.analyze(ty.syntax())?; - let ctx = LowerCtx::new(self.db.upcast(), analyze.file_id); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = + LowerCtx::new(self.db.upcast(), analyze.file_id, &mut types_map, &mut types_source_map); + let type_ref = crate::TypeRef::from_ast(&ctx, ty.clone()); let ty = hir_ty::TyLoweringContext::new_maybe_unowned( self.db, &analyze.resolver, + &types_map, + None, analyze.resolver.type_owner(), ) - .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone())); + .lower_ty(type_ref); Some(Type::new_with_resolver(self.db, &analyze.resolver, ty)) } pub fn resolve_trait(&self, path: &ast::Path) -> Option { let analyze = self.analyze(path.syntax())?; - let ctx = LowerCtx::new(self.db.upcast(), analyze.file_id); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = + LowerCtx::new(self.db.upcast(), analyze.file_id, &mut types_map, &mut types_source_map); let hir_path = Path::from_src(&ctx, path.clone())?; match analyze.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), &hir_path)? { TypeNs::TraitId(id) => Some(Trait { id }), @@ -1953,13 +1962,17 @@ impl SemanticsScope<'_> { /// Resolve a path as-if it was written at the given scope. This is /// necessary a heuristic, as it doesn't take hygiene into account. pub fn speculative_resolve(&self, ast_path: &ast::Path) -> Option { - let ctx = LowerCtx::new(self.db.upcast(), self.file_id); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = + LowerCtx::new(self.db.upcast(), self.file_id, &mut types_map, &mut types_source_map); let path = Path::from_src(&ctx, ast_path.clone())?; resolve_hir_path( self.db, &self.resolver, &path, name_hygiene(self.db, InFile::new(self.file_id, ast_path.syntax())), + &types_map, ) } diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index f5b57d57dfc7..8d6e228e14c0 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -24,7 +24,7 @@ use hir_def::{ nameres::MacroSubNs, path::{ModPath, Path, PathKind}, resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs}, - type_ref::Mutability, + type_ref::{Mutability, TypesMap, TypesSourceMap}, AsMacroCall, AssocItemId, ConstId, DefWithBodyId, FieldId, FunctionId, ItemContainerId, LocalFieldId, Lookup, ModuleDefId, StructId, TraitId, VariantId, }; @@ -614,7 +614,10 @@ impl SourceAnalyzer { db: &dyn HirDatabase, macro_call: InFile<&ast::MacroCall>, ) -> Option { - let ctx = LowerCtx::new(db.upcast(), macro_call.file_id); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = + LowerCtx::new(db.upcast(), macro_call.file_id, &mut types_map, &mut types_source_map); let path = macro_call.value.path().and_then(|ast| Path::from_src(&ctx, ast))?; self.resolver .resolve_path_as_macro(db.upcast(), path.mod_path()?, Some(MacroSubNs::Bang)) @@ -632,7 +635,7 @@ impl SourceAnalyzer { Pat::Path(path) => path, _ => return None, }; - let res = resolve_hir_path(db, &self.resolver, path, HygieneId::ROOT)?; + let res = resolve_hir_path(db, &self.resolver, path, HygieneId::ROOT, TypesMap::EMPTY)?; match res { PathResolution::Def(def) => Some(def), _ => None, @@ -726,14 +729,16 @@ impl SourceAnalyzer { return resolved; } - let ctx = LowerCtx::new(db.upcast(), self.file_id); + let (mut types_map, mut types_source_map) = + (TypesMap::default(), TypesSourceMap::default()); + let ctx = LowerCtx::new(db.upcast(), self.file_id, &mut types_map, &mut types_source_map); let hir_path = Path::from_src(&ctx, path.clone())?; // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are // trying to resolve foo::bar. if let Some(use_tree) = parent().and_then(ast::UseTree::cast) { if use_tree.coloncolon_token().is_some() { - return resolve_hir_path_qualifier(db, &self.resolver, &hir_path); + return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &types_map); } } @@ -750,7 +755,7 @@ impl SourceAnalyzer { // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are // trying to resolve foo::bar. if path.parent_path().is_some() { - return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path) { + return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &types_map) { None if meta_path.is_some() => { path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| { ToolModule::by_name(db, self.resolver.krate().into(), &name_ref.text()) @@ -821,7 +826,7 @@ impl SourceAnalyzer { }; } if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) { - resolve_hir_path_qualifier(db, &self.resolver, &hir_path) + resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &types_map) } else { resolve_hir_path_( db, @@ -829,6 +834,7 @@ impl SourceAnalyzer { &hir_path, prefer_value_ns, name_hygiene(db, InFile::new(self.file_id, path.syntax())), + &types_map, ) } } @@ -1156,8 +1162,9 @@ pub(crate) fn resolve_hir_path( resolver: &Resolver, path: &Path, hygiene: HygieneId, + types_map: &TypesMap, ) -> Option { - resolve_hir_path_(db, resolver, path, false, hygiene) + resolve_hir_path_(db, resolver, path, false, hygiene, types_map) } #[inline] @@ -1178,13 +1185,19 @@ fn resolve_hir_path_( path: &Path, prefer_value_ns: bool, hygiene: HygieneId, + types_map: &TypesMap, ) -> Option { let types = || { let (ty, unresolved) = match path.type_anchor() { Some(type_ref) => { - let (_, res) = - TyLoweringContext::new_maybe_unowned(db, resolver, resolver.type_owner()) - .lower_ty_ext(type_ref); + let (_, res) = TyLoweringContext::new_maybe_unowned( + db, + resolver, + types_map, + None, + resolver.type_owner(), + ) + .lower_ty_ext(type_ref); res.map(|ty_ns| (ty_ns, path.segments().first())) } None => { @@ -1305,13 +1318,19 @@ fn resolve_hir_path_qualifier( db: &dyn HirDatabase, resolver: &Resolver, path: &Path, + types_map: &TypesMap, ) -> Option { (|| { let (ty, unresolved) = match path.type_anchor() { Some(type_ref) => { - let (_, res) = - TyLoweringContext::new_maybe_unowned(db, resolver, resolver.type_owner()) - .lower_ty_ext(type_ref); + let (_, res) = TyLoweringContext::new_maybe_unowned( + db, + resolver, + types_map, + None, + resolver.type_owner(), + ) + .lower_ty_ext(type_ref); res.map(|ty_ns| (ty_ns, path.segments().first())) } None => { diff --git a/src/tools/rust-analyzer/crates/hir/src/symbols.rs b/src/tools/rust-analyzer/crates/hir/src/symbols.rs index e2ad0081e3a7..f8416f86bf9f 100644 --- a/src/tools/rust-analyzer/crates/hir/src/symbols.rs +++ b/src/tools/rust-analyzer/crates/hir/src/symbols.rs @@ -8,7 +8,10 @@ use hir_def::{ TraitId, }; use hir_expand::HirFileId; -use hir_ty::{db::HirDatabase, display::HirDisplay}; +use hir_ty::{ + db::HirDatabase, + display::{hir_display_with_types_map, HirDisplay}, +}; use span::Edition; use syntax::{ast::HasName, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, ToSmolStr}; @@ -214,7 +217,11 @@ impl<'a> SymbolCollector<'a> { fn collect_from_impl(&mut self, impl_id: ImplId) { let impl_data = self.db.impl_data(impl_id); - let impl_name = Some(impl_data.self_ty.display(self.db, self.edition).to_smolstr()); + let impl_name = Some( + hir_display_with_types_map(impl_data.self_ty, &impl_data.types_map) + .display(self.db, self.edition) + .to_smolstr(), + ); self.with_container_name(impl_name, |s| { for &assoc_item_id in impl_data.items.iter() { s.push_assoc_item(assoc_item_id) From ab81593ed8783edd01215fbd2ba4955a98ff02fc Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 13 Oct 2024 08:33:51 +0300 Subject: [PATCH 231/366] Fix memory usage calculation's queries list --- src/tools/rust-analyzer/crates/hir/src/db.rs | 50 +++++++++++-------- .../crates/ide-db/src/apply_change.rs | 20 ++++++++ 2 files changed, 49 insertions(+), 21 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/db.rs b/src/tools/rust-analyzer/crates/hir/src/db.rs index cb5f5b06aefb..22760c41aaec 100644 --- a/src/tools/rust-analyzer/crates/hir/src/db.rs +++ b/src/tools/rust-analyzer/crates/hir/src/db.rs @@ -4,35 +4,43 @@ //! //! But we need this for at least LRU caching at the query level. pub use hir_def::db::{ - AttrsQuery, BlockDefMapQuery, BlockItemTreeQuery, BodyQuery, BodyWithSourceMapQuery, - ConstDataQuery, ConstVisibilityQuery, CrateDefMapQuery, CrateLangItemsQuery, - CrateNotableTraitsQuery, CrateSupportsNoStdQuery, DefDatabase, DefDatabaseStorage, - EnumDataQuery, EnumVariantDataWithDiagnosticsQuery, ExprScopesQuery, ExternCrateDeclDataQuery, - FieldVisibilitiesQuery, FieldsAttrsQuery, FieldsAttrsSourceMapQuery, FileItemTreeQuery, - FunctionDataQuery, FunctionVisibilityQuery, GenericParamsQuery, ImplDataWithDiagnosticsQuery, - ImportMapQuery, InternAnonymousConstQuery, InternBlockQuery, InternConstQuery, InternDatabase, - InternDatabaseStorage, InternEnumQuery, InternExternBlockQuery, InternExternCrateQuery, - InternFunctionQuery, InternImplQuery, InternInTypeConstQuery, InternMacro2Query, - InternMacroRulesQuery, InternProcMacroQuery, InternStaticQuery, InternStructQuery, - InternTraitAliasQuery, InternTraitQuery, InternTypeAliasQuery, InternUnionQuery, - InternUseQuery, LangItemQuery, Macro2DataQuery, MacroRulesDataQuery, ProcMacroDataQuery, - StaticDataQuery, StructDataWithDiagnosticsQuery, TraitAliasDataQuery, - TraitDataWithDiagnosticsQuery, TypeAliasDataQuery, UnionDataWithDiagnosticsQuery, + AttrsQuery, BlockDefMapQuery, BlockItemTreeQuery, BlockItemTreeWithSourceMapQuery, BodyQuery, + BodyWithSourceMapQuery, ConstDataQuery, ConstVisibilityQuery, CrateDefMapQuery, + CrateLangItemsQuery, CrateNotableTraitsQuery, CrateSupportsNoStdQuery, DefDatabase, + DefDatabaseStorage, EnumDataQuery, EnumVariantDataWithDiagnosticsQuery, + ExpandProcAttrMacrosQuery, ExprScopesQuery, ExternCrateDeclDataQuery, FieldVisibilitiesQuery, + FieldsAttrsQuery, FieldsAttrsSourceMapQuery, FileItemTreeQuery, FileItemTreeWithSourceMapQuery, + FunctionDataQuery, FunctionVisibilityQuery, GenericParamsQuery, + GenericParamsWithSourceMapQuery, ImplDataWithDiagnosticsQuery, ImportMapQuery, + IncludeMacroInvocQuery, InternAnonymousConstQuery, InternBlockQuery, InternConstQuery, + InternDatabase, InternDatabaseStorage, InternEnumQuery, InternExternBlockQuery, + InternExternCrateQuery, InternFunctionQuery, InternImplQuery, InternInTypeConstQuery, + InternMacro2Query, InternMacroRulesQuery, InternProcMacroQuery, InternStaticQuery, + InternStructQuery, InternTraitAliasQuery, InternTraitQuery, InternTypeAliasQuery, + InternUnionQuery, InternUseQuery, LangItemQuery, Macro2DataQuery, MacroDefQuery, + MacroRulesDataQuery, NotableTraitsInDepsQuery, ProcMacroDataQuery, StaticDataQuery, + StructDataWithDiagnosticsQuery, TraitAliasDataQuery, TraitDataWithDiagnosticsQuery, + TypeAliasDataQuery, UnionDataWithDiagnosticsQuery, }; pub use hir_expand::db::{ AstIdMapQuery, DeclMacroExpanderQuery, ExpandDatabase, ExpandDatabaseStorage, ExpandProcMacroQuery, InternMacroCallQuery, InternSyntaxContextQuery, MacroArgQuery, - ParseMacroExpansionErrorQuery, ParseMacroExpansionQuery, ProcMacrosQuery, RealSpanMapQuery, + ParseMacroExpansionErrorQuery, ParseMacroExpansionQuery, ProcMacroSpanQuery, ProcMacrosQuery, + RealSpanMapQuery, }; pub use hir_ty::db::{ AdtDatumQuery, AdtVarianceQuery, AssociatedTyDataQuery, AssociatedTyValueQuery, BorrowckQuery, CallableItemSignatureQuery, ConstEvalDiscriminantQuery, ConstEvalQuery, ConstEvalStaticQuery, - ConstParamTyQuery, FieldTypesQuery, FnDefDatumQuery, FnDefVarianceQuery, GenericDefaultsQuery, - GenericPredicatesForParamQuery, GenericPredicatesQuery, HirDatabase, HirDatabaseStorage, - ImplDatumQuery, ImplSelfTyQuery, ImplTraitQuery, IncoherentInherentImplCratesQuery, + ConstParamTyQuery, DynCompatibilityOfTraitQuery, FieldTypesQuery, FnDefDatumQuery, + FnDefVarianceQuery, GenericDefaultsQuery, GenericPredicatesForParamQuery, + GenericPredicatesQuery, GenericPredicatesWithoutParentQuery, HirDatabase, HirDatabaseStorage, + ImplDatumQuery, ImplSelfTyQuery, ImplTraitQuery, IncoherentInherentImplCratesQuery, InferQuery, InherentImplsInBlockQuery, InherentImplsInCrateQuery, InternCallableDefQuery, InternClosureQuery, InternCoroutineQuery, InternImplTraitIdQuery, InternLifetimeParamIdQuery, - InternTypeOrConstParamIdQuery, LayoutOfAdtQuery, MirBodyQuery, ProgramClausesForChalkEnvQuery, - ReturnTypeImplTraitsQuery, TargetDataLayoutQuery, TraitDatumQuery, TraitEnvironmentQuery, - TraitImplsInBlockQuery, TraitImplsInCrateQuery, TraitImplsInDepsQuery, TyQuery, ValueTyQuery, + InternTypeOrConstParamIdQuery, LayoutOfAdtQuery, LayoutOfTyQuery, LookupImplMethodQuery, + MirBodyForClosureQuery, MirBodyQuery, MonomorphizedMirBodyForClosureQuery, + MonomorphizedMirBodyQuery, ProgramClausesForChalkEnvQuery, ReturnTypeImplTraitsQuery, + TargetDataLayoutQuery, TraitDatumQuery, TraitEnvironmentQuery, TraitImplsInBlockQuery, + TraitImplsInCrateQuery, TraitImplsInDepsQuery, TraitSolveQuery, TyQuery, + TypeAliasImplTraitsQuery, ValueTyQuery, }; diff --git a/src/tools/rust-analyzer/crates/ide-db/src/apply_change.rs b/src/tools/rust-analyzer/crates/ide-db/src/apply_change.rs index 7474d7bc54db..35e3a8d9bf7f 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/apply_change.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/apply_change.rs @@ -100,16 +100,19 @@ impl RootDatabase { hir::db::ConstEvalQuery hir::db::ConstEvalStaticQuery hir::db::ConstParamTyQuery + hir::db::DynCompatibilityOfTraitQuery hir::db::FieldTypesQuery hir::db::FnDefDatumQuery hir::db::FnDefVarianceQuery hir::db::GenericDefaultsQuery hir::db::GenericPredicatesForParamQuery hir::db::GenericPredicatesQuery + hir::db::GenericPredicatesWithoutParentQuery hir::db::ImplDatumQuery hir::db::ImplSelfTyQuery hir::db::ImplTraitQuery hir::db::IncoherentInherentImplCratesQuery + hir::db::InferQuery hir::db::InherentImplsInBlockQuery hir::db::InherentImplsInCrateQuery hir::db::InternCallableDefQuery @@ -119,7 +122,12 @@ impl RootDatabase { hir::db::InternLifetimeParamIdQuery hir::db::InternTypeOrConstParamIdQuery hir::db::LayoutOfAdtQuery + hir::db::LayoutOfTyQuery + hir::db::LookupImplMethodQuery + hir::db::MirBodyForClosureQuery hir::db::MirBodyQuery + hir::db::MonomorphizedMirBodyForClosureQuery + hir::db::MonomorphizedMirBodyQuery hir::db::ProgramClausesForChalkEnvQuery hir::db::ReturnTypeImplTraitsQuery hir::db::TargetDataLayoutQuery @@ -128,13 +136,16 @@ impl RootDatabase { hir::db::TraitImplsInBlockQuery hir::db::TraitImplsInCrateQuery hir::db::TraitImplsInDepsQuery + hir::db::TraitSolveQuery hir::db::TyQuery + hir::db::TypeAliasImplTraitsQuery hir::db::ValueTyQuery // DefDatabase hir::db::AttrsQuery hir::db::BlockDefMapQuery hir::db::BlockItemTreeQuery + hir::db::BlockItemTreeWithSourceMapQuery hir::db::BodyQuery hir::db::BodyWithSourceMapQuery hir::db::ConstDataQuery @@ -145,17 +156,21 @@ impl RootDatabase { hir::db::CrateSupportsNoStdQuery hir::db::EnumDataQuery hir::db::EnumVariantDataWithDiagnosticsQuery + hir::db::ExpandProcAttrMacrosQuery hir::db::ExprScopesQuery hir::db::ExternCrateDeclDataQuery hir::db::FieldVisibilitiesQuery hir::db::FieldsAttrsQuery hir::db::FieldsAttrsSourceMapQuery hir::db::FileItemTreeQuery + hir::db::FileItemTreeWithSourceMapQuery hir::db::FunctionDataQuery hir::db::FunctionVisibilityQuery hir::db::GenericParamsQuery + hir::db::GenericParamsWithSourceMapQuery hir::db::ImplDataWithDiagnosticsQuery hir::db::ImportMapQuery + hir::db::IncludeMacroInvocQuery hir::db::InternAnonymousConstQuery hir::db::InternBlockQuery hir::db::InternConstQuery @@ -177,7 +192,9 @@ impl RootDatabase { hir::db::InternUseQuery hir::db::LangItemQuery hir::db::Macro2DataQuery + hir::db::MacroDefQuery hir::db::MacroRulesDataQuery + hir::db::NotableTraitsInDepsQuery hir::db::ProcMacroDataQuery hir::db::StaticDataQuery hir::db::StructDataWithDiagnosticsQuery @@ -212,6 +229,7 @@ impl RootDatabase { hir::db::MacroArgQuery hir::db::ParseMacroExpansionErrorQuery hir::db::ParseMacroExpansionQuery + hir::db::ProcMacroSpanQuery hir::db::ProcMacrosQuery hir::db::RealSpanMapQuery @@ -220,7 +238,9 @@ impl RootDatabase { // SourceDatabase base_db::ParseQuery + base_db::ParseErrorsQuery base_db::CrateGraphQuery + base_db::CrateWorkspaceDataQuery // SourceDatabaseExt base_db::FileTextQuery From fc5bce925c827f9836591c9bea4ca06587430cfe Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Fri, 18 Oct 2024 16:38:20 +0300 Subject: [PATCH 232/366] Reuse empty `GenericParams` This saves back 15mb that went for typeref source maps. --- .../crates/hir-def/src/generics.rs | 23 +++++++++++++++---- .../crates/hir-def/src/item_tree/lower.rs | 2 +- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs index f30a2edda908..c4f871c96823 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs @@ -3,7 +3,7 @@ //! generic parameters. See also the `Generics` type and the `generics_of` query //! in rustc. -use std::ops; +use std::{ops, sync::LazyLock}; use either::Either; use hir_expand::{ @@ -412,7 +412,7 @@ impl GenericParams { ); } let generics = generic_params.finish(types_map, &mut types_source_maps); - (Arc::new(generics), Some(Arc::new(types_source_maps))) + (generics, Some(Arc::new(types_source_maps))) } } GenericDefId::AdtId(AdtId::StructId(id)) => id_to_generics(db, id, enabled_params), @@ -686,19 +686,32 @@ impl GenericParamsCollector { self, mut generics_types_map: TypesMap, generics_types_source_map: &mut TypesSourceMap, - ) -> GenericParams { + ) -> Arc { let Self { mut lifetimes, mut type_or_consts, mut where_predicates } = self; + + if lifetimes.is_empty() && type_or_consts.is_empty() && where_predicates.is_empty() { + static EMPTY: LazyLock> = LazyLock::new(|| { + Arc::new(GenericParams { + lifetimes: Arena::new(), + type_or_consts: Arena::new(), + where_predicates: Box::default(), + types_map: TypesMap::default(), + }) + }); + return Arc::clone(&EMPTY); + } + lifetimes.shrink_to_fit(); type_or_consts.shrink_to_fit(); where_predicates.shrink_to_fit(); generics_types_map.shrink_to_fit(); generics_types_source_map.shrink_to_fit(); - GenericParams { + Arc::new(GenericParams { type_or_consts, lifetimes, where_predicates: where_predicates.into_boxed_slice(), types_map: generics_types_map, - } + }) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index c42c849c3b9b..350603568788 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -895,7 +895,7 @@ impl<'a> Ctx<'a> { generics.fill(&body_ctx, node, add_param_attrs); let generics = generics.finish(types_map, &mut types_source_map); - (Arc::new(generics), types_source_map) + (generics, types_source_map) } fn lower_type_bounds( From a16a3d345fdc3cced391eb21bd0d15e360972d27 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sat, 19 Oct 2024 20:47:17 +0300 Subject: [PATCH 233/366] Shrink `ItemTreeSourceMaps` This saves 16mb on `analysis-stats .`. --- .../crates/hir-def/src/generics.rs | 6 +- .../crates/hir-def/src/item_tree.rs | 168 +++++++++++++----- .../crates/hir-def/src/item_tree/lower.rs | 54 +++--- 3 files changed, 155 insertions(+), 73 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs index c4f871c96823..20a6e5cc2d11 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs @@ -385,7 +385,7 @@ impl GenericParams { (enabled_params, None) } else { let source_maps = loc.id.item_tree_with_source_map(db).1; - let item_source_maps = &source_maps[loc.id.value]; + let item_source_maps = source_maps.function(loc.id.value); let mut generic_params = GenericParamsCollector { type_or_consts: enabled_params.type_or_consts.clone(), lifetimes: enabled_params.lifetimes.clone(), @@ -393,7 +393,7 @@ impl GenericParams { }; let (mut types_map, mut types_source_maps) = - (enabled_params.types_map.clone(), item_source_maps.generics.clone()); + (enabled_params.types_map.clone(), item_source_maps.generics().clone()); // Don't create an `Expander` if not needed since this // could cause a reparse after the `ItemTree` has been created due to the spanmap. let mut expander = None; @@ -408,7 +408,7 @@ impl GenericParams { }, param, &item.types_map, - &item_source_maps.item, + item_source_maps.item(), ); } let generics = generic_params.finish(types_map, &mut types_source_maps); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs index 74500fd76e6d..b39a3fece62b 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs @@ -113,7 +113,7 @@ impl ItemTree { let ctx = lower::Ctx::new(db, file_id); let syntax = db.parse_or_expand(file_id); let mut top_attrs = None; - let (mut item_tree, mut source_maps) = match_ast! { + let (mut item_tree, source_maps) = match_ast! { match syntax { ast::SourceFile(file) => { top_attrs = Some(RawAttrs::new(db.upcast(), &file, ctx.span_map())); @@ -155,7 +155,6 @@ impl ItemTree { .clone() } else { item_tree.shrink_to_fit(); - source_maps.shrink_to_fit(); (Arc::new(item_tree), Arc::new(source_maps)) } } @@ -175,7 +174,7 @@ impl ItemTree { let block = loc.ast_id.to_node(db.upcast()); let ctx = lower::Ctx::new(db, loc.ast_id.file_id); - let (mut item_tree, mut source_maps) = ctx.lower_block(&block); + let (mut item_tree, source_maps) = ctx.lower_block(&block); if item_tree.data.is_none() && item_tree.top_level.is_empty() && item_tree.attrs.is_empty() { EMPTY @@ -192,7 +191,6 @@ impl ItemTree { .clone() } else { item_tree.shrink_to_fit(); - source_maps.shrink_to_fit(); (Arc::new(item_tree), Arc::new(source_maps)) } } @@ -331,29 +329,59 @@ struct ItemTreeData { } #[derive(Default, Debug, Eq, PartialEq)] -pub struct GenericItemSourceMap { +pub struct ItemTreeSourceMaps { + all_concatenated: Box<[TypesSourceMap]>, + structs_offset: u32, + unions_offset: u32, + enum_generics_offset: u32, + variants_offset: u32, + consts_offset: u32, + statics_offset: u32, + trait_generics_offset: u32, + trait_alias_generics_offset: u32, + impls_offset: u32, + type_aliases_offset: u32, +} + +#[derive(Clone, Copy)] +pub struct GenericItemSourceMap<'a>(&'a [TypesSourceMap; 2]); + +impl<'a> GenericItemSourceMap<'a> { + #[inline] + pub fn item(self) -> &'a TypesSourceMap { + &self.0[0] + } + + #[inline] + pub fn generics(self) -> &'a TypesSourceMap { + &self.0[1] + } +} + +#[derive(Default, Debug, Eq, PartialEq)] +pub struct GenericItemSourceMapBuilder { pub item: TypesSourceMap, pub generics: TypesSourceMap, } #[derive(Default, Debug, Eq, PartialEq)] -pub struct ItemTreeSourceMaps { - functions: Vec, - structs: Vec, - unions: Vec, +struct ItemTreeSourceMapsBuilder { + functions: Vec, + structs: Vec, + unions: Vec, enum_generics: Vec, variants: Vec, consts: Vec, statics: Vec, trait_generics: Vec, trait_alias_generics: Vec, - impls: Vec, - type_aliases: Vec, + impls: Vec, + type_aliases: Vec, } -impl ItemTreeSourceMaps { - fn shrink_to_fit(&mut self) { - let ItemTreeSourceMaps { +impl ItemTreeSourceMapsBuilder { + fn build(self) -> ItemTreeSourceMaps { + let ItemTreeSourceMapsBuilder { functions, structs, unions, @@ -366,44 +394,92 @@ impl ItemTreeSourceMaps { impls, type_aliases, } = self; - functions.shrink_to_fit(); - structs.shrink_to_fit(); - unions.shrink_to_fit(); - enum_generics.shrink_to_fit(); - variants.shrink_to_fit(); - consts.shrink_to_fit(); - statics.shrink_to_fit(); - trait_generics.shrink_to_fit(); - trait_alias_generics.shrink_to_fit(); - impls.shrink_to_fit(); - type_aliases.shrink_to_fit(); + let structs_offset = functions.len() as u32 * 2; + let unions_offset = structs_offset + (structs.len() as u32 * 2); + let enum_generics_offset = unions_offset + (unions.len() as u32 * 2); + let variants_offset = enum_generics_offset + (enum_generics.len() as u32); + let consts_offset = variants_offset + (variants.len() as u32); + let statics_offset = consts_offset + (consts.len() as u32); + let trait_generics_offset = statics_offset + (statics.len() as u32); + let trait_alias_generics_offset = trait_generics_offset + (trait_generics.len() as u32); + let impls_offset = trait_alias_generics_offset + (trait_alias_generics.len() as u32); + let type_aliases_offset = impls_offset + (impls.len() as u32 * 2); + let all_concatenated = generics_concat(functions) + .chain(generics_concat(structs)) + .chain(generics_concat(unions)) + .chain(enum_generics) + .chain(variants) + .chain(consts) + .chain(statics) + .chain(trait_generics) + .chain(trait_alias_generics) + .chain(generics_concat(impls)) + .chain(generics_concat(type_aliases)) + .collect(); + return ItemTreeSourceMaps { + all_concatenated, + structs_offset, + unions_offset, + enum_generics_offset, + variants_offset, + consts_offset, + statics_offset, + trait_generics_offset, + trait_alias_generics_offset, + impls_offset, + type_aliases_offset, + }; + + fn generics_concat( + source_maps: Vec, + ) -> impl Iterator { + source_maps.into_iter().flat_map(|it| [it.item, it.generics]) + } } } -macro_rules! index_source_maps { - ( $( $field:ident[$tree_id:ident] = $result:ident, )* ) => { - $( - impl Index> for ItemTreeSourceMaps { - type Output = $result; - fn index(&self, index: FileItemTreeId<$tree_id>) -> &Self::Output { - &self.$field[index.0.into_raw().into_u32() as usize] +impl ItemTreeSourceMaps { + #[inline] + fn generic_item(&self, offset: u32, index: u32) -> GenericItemSourceMap<'_> { + GenericItemSourceMap( + self.all_concatenated[(offset + (index * 2)) as usize..][..2].try_into().unwrap(), + ) + } + + #[inline] + fn non_generic_item(&self, offset: u32, index: u32) -> &TypesSourceMap { + &self.all_concatenated[(offset + index) as usize] + } + + #[inline] + pub fn function(&self, index: FileItemTreeId) -> GenericItemSourceMap<'_> { + self.generic_item(0, index.0.into_raw().into_u32()) + } +} + +macro_rules! index_item_source_maps { + ( $( $name:ident; $field:ident[$tree_id:ident]; $fn:ident; $ret:ty, )* ) => { + impl ItemTreeSourceMaps { + $( + #[inline] + pub fn $name(&self, index: FileItemTreeId<$tree_id>) -> $ret { + self.$fn(self.$field, index.0.into_raw().into_u32()) } - } - )* + )* + } }; } -index_source_maps! { - functions[Function] = GenericItemSourceMap, - structs[Struct] = GenericItemSourceMap, - unions[Union] = GenericItemSourceMap, - enum_generics[Enum] = TypesSourceMap, - variants[Variant] = TypesSourceMap, - consts[Const] = TypesSourceMap, - statics[Static] = TypesSourceMap, - trait_generics[Trait] = TypesSourceMap, - trait_alias_generics[TraitAlias] = TypesSourceMap, - impls[Impl] = GenericItemSourceMap, - type_aliases[TypeAlias] = GenericItemSourceMap, +index_item_source_maps! { + strukt; structs_offset[Struct]; generic_item; GenericItemSourceMap<'_>, + union; unions_offset[Union]; generic_item; GenericItemSourceMap<'_>, + enum_generic; enum_generics_offset[Enum]; non_generic_item; &TypesSourceMap, + variant; variants_offset[Variant]; non_generic_item; &TypesSourceMap, + konst; consts_offset[Const]; non_generic_item; &TypesSourceMap, + statik; statics_offset[Static]; non_generic_item; &TypesSourceMap, + trait_generic; trait_generics_offset[Trait]; non_generic_item; &TypesSourceMap, + trait_alias_generic; trait_alias_generics_offset[TraitAlias]; non_generic_item; &TypesSourceMap, + impl_; impls_offset[Impl]; generic_item; GenericItemSourceMap<'_>, + type_alias; type_aliases_offset[TypeAlias]; generic_item; GenericItemSourceMap<'_>, } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index 350603568788..d3dc8d9cb04d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -23,11 +23,12 @@ use crate::{ generics::{GenericParams, GenericParamsCollector, TypeParamData, TypeParamProvenance}, item_tree::{ AssocItem, AttrOwner, Const, Either, Enum, ExternBlock, ExternCrate, Field, FieldParent, - FieldsShape, FileItemTreeId, FnFlags, Function, GenericArgs, GenericItemSourceMap, + FieldsShape, FileItemTreeId, FnFlags, Function, GenericArgs, GenericItemSourceMapBuilder, GenericModItem, Idx, Impl, ImportAlias, Interned, ItemTree, ItemTreeData, - ItemTreeSourceMaps, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, ModPath, - Mutability, Name, Param, Path, Range, RawAttrs, RawIdx, RawVisibilityId, Static, Struct, - StructKind, Trait, TraitAlias, TypeAlias, Union, Use, UseTree, UseTreeKind, Variant, + ItemTreeSourceMaps, ItemTreeSourceMapsBuilder, Macro2, MacroCall, MacroRules, Mod, ModItem, + ModKind, ModPath, Mutability, Name, Param, Path, Range, RawAttrs, RawIdx, RawVisibilityId, + Static, Struct, StructKind, Trait, TraitAlias, TypeAlias, Union, Use, UseTree, UseTreeKind, + Variant, }, lower::LowerCtx, path::AssociatedTypeBinding, @@ -51,7 +52,7 @@ pub(super) struct Ctx<'a> { FxHashMap, RawAttrs>, span_map: OnceCell, file: HirFileId, - source_maps: ItemTreeSourceMaps, + source_maps: ItemTreeSourceMapsBuilder, } impl<'a> Ctx<'a> { @@ -63,7 +64,7 @@ impl<'a> Ctx<'a> { source_ast_id_map: db.ast_id_map(file), file, span_map: OnceCell::new(), - source_maps: ItemTreeSourceMaps::default(), + source_maps: ItemTreeSourceMapsBuilder::default(), } } @@ -97,7 +98,7 @@ impl<'a> Ctx<'a> { self.tree.top_level = item_owner.items().flat_map(|item| self.lower_mod_item(&item)).collect(); assert!(self.generic_param_attr_buffer.is_empty()); - (self.tree, self.source_maps) + (self.tree, self.source_maps.build()) } pub(super) fn lower_macro_stmts( @@ -134,7 +135,7 @@ impl<'a> Ctx<'a> { } assert!(self.generic_param_attr_buffer.is_empty()); - (self.tree, self.source_maps) + (self.tree, self.source_maps.build()) } pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> (ItemTree, ItemTreeSourceMaps) { @@ -163,7 +164,7 @@ impl<'a> Ctx<'a> { } assert!(self.generic_param_attr_buffer.is_empty()); - (self.tree, self.source_maps) + (self.tree, self.source_maps.build()) } fn data(&mut self) -> &mut ItemTreeData { @@ -249,9 +250,10 @@ impl<'a> Ctx<'a> { types_map: Arc::new(types_map), }; let id = id(self.data().structs.alloc(res)); - self.source_maps - .structs - .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); + self.source_maps.structs.push(GenericItemSourceMapBuilder { + item: types_source_map, + generics: generics_source_map, + }); for (idx, attr) in attrs { self.add_attrs( AttrOwner::Field( @@ -352,9 +354,10 @@ impl<'a> Ctx<'a> { types_map: Arc::new(types_map), }; let id = id(self.data().unions.alloc(res)); - self.source_maps - .unions - .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); + self.source_maps.unions.push(GenericItemSourceMapBuilder { + item: types_source_map, + generics: generics_source_map, + }); for (idx, attr) in attrs { self.add_attrs( AttrOwner::Field( @@ -558,9 +561,10 @@ impl<'a> Ctx<'a> { }; let id = id(self.data().functions.alloc(res)); - self.source_maps - .functions - .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); + self.source_maps.functions.push(GenericItemSourceMapBuilder { + item: types_source_map, + generics: generics_source_map, + }); for (idx, attr) in attrs { self.add_attrs(AttrOwner::Param(id, Idx::from_raw(RawIdx::from_u32(idx as u32))), attr); } @@ -594,9 +598,10 @@ impl<'a> Ctx<'a> { types_map: Arc::new(types_map), }; let id = id(self.data().type_aliases.alloc(res)); - self.source_maps - .type_aliases - .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); + self.source_maps.type_aliases.push(GenericItemSourceMapBuilder { + item: types_source_map, + generics: generics_source_map, + }); self.write_generic_params_attributes(id.into()); Some(id) } @@ -751,9 +756,10 @@ impl<'a> Ctx<'a> { types_map: Arc::new(types_map), }; let id = id(self.data().impls.alloc(res)); - self.source_maps - .impls - .push(GenericItemSourceMap { item: types_source_map, generics: generics_source_map }); + self.source_maps.impls.push(GenericItemSourceMapBuilder { + item: types_source_map, + generics: generics_source_map, + }); self.write_generic_params_attributes(id.into()); id } From 61d14ba93727936939448f49ee50781001c5a656 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sat, 19 Oct 2024 23:07:02 +0300 Subject: [PATCH 234/366] Do not allocate attributes entry if there are no attributes This saves 8mb. --- .../crates/hir-def/src/item_tree/lower.rs | 14 ++++++++------ .../rust-analyzer/crates/hir-expand/src/attrs.rs | 5 +++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index d3dc8d9cb04d..3367d5540f54 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -198,12 +198,14 @@ impl<'a> Ctx<'a> { } fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) { - match self.tree.attrs.entry(item) { - Entry::Occupied(mut entry) => { - *entry.get_mut() = entry.get().merge(attrs); - } - Entry::Vacant(entry) => { - entry.insert(attrs); + if !attrs.is_empty() { + match self.tree.attrs.entry(item) { + Entry::Occupied(mut entry) => { + *entry.get_mut() = entry.get().merge(attrs); + } + Entry::Vacant(entry) => { + entry.insert(attrs); + } } } } diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/attrs.rs b/src/tools/rust-analyzer/crates/hir-expand/src/attrs.rs index 79cfeb4cf184..12df3cf21882 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/attrs.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/attrs.rs @@ -26,6 +26,7 @@ use crate::{ /// Syntactical attributes, without filtering of `cfg_attr`s. #[derive(Default, Debug, Clone, PartialEq, Eq)] pub struct RawAttrs { + // FIXME: This can become `Box<[Attr]>` if https://internals.rust-lang.org/t/layout-of-dst-box/21728?u=chrefr is accepted. entries: Option>, } @@ -169,6 +170,10 @@ impl RawAttrs { }; RawAttrs { entries } } + + pub fn is_empty(&self) -> bool { + self.entries.is_none() + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] From 183796ed0ee3058e7f323e70109fdaf51db4ae33 Mon Sep 17 00:00:00 2001 From: HackerVole <78761827+hackervole@users.noreply.github.com> Date: Thu, 24 Oct 2024 23:20:40 -0400 Subject: [PATCH 235/366] editors/code: Add md for walkthrough setup example Add a separate markdown file containing the settings.json snippet from the "Useful Setup Tips". This fixes the rendering and also makes the text selectable. Also use double-backticks for `code` rendering. --- src/tools/rust-analyzer/editors/code/.vscodeignore | 1 + src/tools/rust-analyzer/editors/code/package.json | 7 +++---- .../editors/code/walkthrough-setup-tips.md | 10 ++++++++++ 3 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 src/tools/rust-analyzer/editors/code/walkthrough-setup-tips.md diff --git a/src/tools/rust-analyzer/editors/code/.vscodeignore b/src/tools/rust-analyzer/editors/code/.vscodeignore index 09dc27056b37..1712a1477e6f 100644 --- a/src/tools/rust-analyzer/editors/code/.vscodeignore +++ b/src/tools/rust-analyzer/editors/code/.vscodeignore @@ -12,3 +12,4 @@ !ra_syntax_tree.tmGrammar.json !server !README.md +!walkthrough-setup-tips.md diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index e55eceff7811..6eebdf9f016a 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -3224,10 +3224,9 @@ { "id": "setup", "title": "Useful Setup Tips", - "description": "There are a couple of things you might want to configure upfront to your tastes. We'll name a few here but be sure to check out the docs linked below!\n\n**Marking library sources as readonly**\n\nAdding the following to your settings.json will mark all Rust library sources as readonly:\n```json\n\"files.readonlyInclude\": {\n \"**/.cargo/registry/src/**/*.rs\": true,\n \"**/lib/rustlib/src/rust/library/**/*.rs\": true,\n},\n```\n\n**Check on Save**\n\nBy default, rust-analyzer will run `cargo check` on your codebase when you save a file, rendering diagnostics emitted by `cargo check` within your code. This can potentially collide with other `cargo` commands running concurrently, blocking them from running for a certain amount of time. In these cases it is recommended to disable the `rust-analyzer.checkOnSave` configuration and running the `rust-analyzer: Run flycheck` command on-demand instead.", + "description": "There are a couple of things you might want to configure upfront to your tastes. We'll name a few here but be sure to check out the docs linked below!\n\n**Marking library sources as readonly**\n\nAdding the snippet on the right to your settings.json will mark all Rust library sources as readonly.\n\n**Check on Save**\n\nBy default, rust-analyzer will run ``cargo check`` on your codebase when you save a file, rendering diagnostics emitted by ``cargo check`` within your code. This can potentially collide with other ``cargo`` commands running concurrently, blocking them from running for a certain amount of time. In these cases it is recommended to disable the ``rust-analyzer.checkOnSave`` configuration and running the ``rust-analyzer: Run flycheck`` command on-demand instead.", "media": { - "image": "./icon.png", - "altText": "rust-analyzer logo" + "markdown": "./walkthrough-setup-tips.md" } }, { @@ -3245,7 +3244,7 @@ { "id": "faq", "title": "FAQ", - "description": "What are these code hints that are being inserted into my code?\n\nThese hints are called inlay hints which rust-analyzer support and are enabled by default in VSCode. If you wish to disable them you can do so via the `editor.inlayHints.enabled` setting.", + "description": "What are these code hints that are being inserted into my code?\n\nThese hints are called inlay hints which rust-analyzer support and are enabled by default in VSCode. If you wish to disable them you can do so via the ``editor.inlayHints.enabled`` setting.", "media": { "image": "icon.png", "altText": "rust-analyzer logo" diff --git a/src/tools/rust-analyzer/editors/code/walkthrough-setup-tips.md b/src/tools/rust-analyzer/editors/code/walkthrough-setup-tips.md new file mode 100644 index 000000000000..fda4ac80023f --- /dev/null +++ b/src/tools/rust-analyzer/editors/code/walkthrough-setup-tips.md @@ -0,0 +1,10 @@ +# Settings Example + +Add the following to settings.json to mark Rust library sources as read-only: + +```json +"files.readonlyInclude": { + "**/.cargo/registry/src/**/*.rs": true, + "**/lib/rustlib/src/rust/library/**/*.rs": true, +}, +``` From 8f075145200aef04b36f2e2239f09b796c6ac8b8 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 13:57:46 +1100 Subject: [PATCH 236/366] coverage: SSA doesn't need to know about `instrprof_increment` --- compiler/rustc_codegen_gcc/src/builder.rs | 10 -------- compiler/rustc_codegen_llvm/src/builder.rs | 23 ++++++++++--------- .../rustc_codegen_ssa/src/traits/builder.rs | 8 ------- 3 files changed, 12 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index 457380685093..7c52cba096b4 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -1725,16 +1725,6 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn fptosi_sat(&mut self, val: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.fptoint_sat(true, val, dest_ty) } - - fn instrprof_increment( - &mut self, - _fn_name: RValue<'gcc>, - _hash: RValue<'gcc>, - _num_counters: RValue<'gcc>, - _index: RValue<'gcc>, - ) { - unimplemented!(); - } } impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index f4463e037c94..8702532c36ee 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1165,17 +1165,6 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size); } - #[instrument(level = "debug", skip(self))] - fn instrprof_increment( - &mut self, - fn_name: &'ll Value, - hash: &'ll Value, - num_counters: &'ll Value, - index: &'ll Value, - ) { - self.call_intrinsic("llvm.instrprof.increment", &[fn_name, hash, num_counters, index]); - } - fn call( &mut self, llty: &'ll Type, @@ -1645,6 +1634,18 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { kcfi_bundle } + /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation. + #[instrument(level = "debug", skip(self))] + pub(crate) fn instrprof_increment( + &mut self, + fn_name: &'ll Value, + hash: &'ll Value, + num_counters: &'ll Value, + index: &'ll Value, + ) { + self.call_intrinsic("llvm.instrprof.increment", &[fn_name, hash, num_counters, index]); + } + /// Emits a call to `llvm.instrprof.mcdc.parameters`. /// /// This doesn't produce any code directly, but is used as input by diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index c0c1085e949e..50a517141469 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -437,14 +437,6 @@ pub trait BuilderMethods<'a, 'tcx>: /// Called for `StorageDead` fn lifetime_end(&mut self, ptr: Self::Value, size: Size); - fn instrprof_increment( - &mut self, - fn_name: Self::Value, - hash: Self::Value, - num_counters: Self::Value, - index: Self::Value, - ); - fn call( &mut self, llty: Self::Type, From fd7648d92045cf8e5b1d8a9f7751924c70be53d3 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 20 Oct 2024 00:50:18 +0300 Subject: [PATCH 237/366] Shrink `Path` to 16 bytes Thanks to the observation (supported by counting) that the vast majority paths have neither generics no type anchors, and thanks to a new datastructure `ThinVecWithHeader` that is essentially `(T, Box<[U]>)` but with the size of a single pointer, we are able to reach this feat. This (together with `ThinVecWithHeader`) makes the possibility to shrink `TypeRef`, because most types are paths. --- .../crates/hir-def/src/body/lower.rs | 12 +- .../crates/hir-def/src/generics.rs | 21 +- .../rust-analyzer/crates/hir-def/src/hir.rs | 2 +- .../crates/hir-def/src/hir/type_ref.rs | 2 +- .../rust-analyzer/crates/hir-def/src/path.rs | 150 +++--- .../crates/hir-def/src/path/lower.rs | 22 +- .../crates/hir-def/src/resolver.rs | 6 +- .../crates/hir-ty/src/infer/expr.rs | 4 +- .../crates/hir-ty/src/infer/path.rs | 2 +- .../crates/hir-ty/src/mir/lower.rs | 7 +- .../rust-analyzer/crates/stdx/src/lib.rs | 1 + .../rust-analyzer/crates/stdx/src/thin_vec.rs | 472 ++++++++++++++++++ src/tools/rust-analyzer/xtask/src/tidy.rs | 2 +- 13 files changed, 596 insertions(+), 107 deletions(-) create mode 100644 src/tools/rust-analyzer/crates/stdx/src/thin_vec.rs diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index 3ecb9576b7f4..a1b0b52145a3 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -720,12 +720,8 @@ impl ExprCollector<'_> { fn collect_expr_path(&mut self, e: ast::PathExpr) -> Option<(Path, HygieneId)> { e.path().and_then(|path| { let path = self.parse_path(path)?; - let Path::Normal { type_anchor, mod_path, generic_args } = &path else { - panic!("path parsing produced a non-normal path"); - }; // Need to enable `mod_path.len() < 1` for `self`. - let may_be_variable = - type_anchor.is_none() && mod_path.len() <= 1 && generic_args.is_none(); + let may_be_variable = matches!(&path, Path::BarePath(mod_path) if mod_path.len() <= 1); let hygiene = if may_be_variable { self.hygiene_id_for(e.syntax().text_range().start()) } else { @@ -797,7 +793,7 @@ impl ExprCollector<'_> { ast::Expr::PathExpr(e) => { let (path, hygiene) = self .collect_expr_path(e.clone()) - .map(|(path, hygiene)| (Pat::Path(Box::new(path)), hygiene)) + .map(|(path, hygiene)| (Pat::Path(path), hygiene)) .unwrap_or((Pat::Missing, HygieneId::ROOT)); let pat_id = self.alloc_pat_from_expr(path, syntax_ptr); if !hygiene.is_root() { @@ -1059,7 +1055,7 @@ impl ExprCollector<'_> { syntax_ptr, ); let none_arm = MatchArm { - pat: self.alloc_pat_desugared(Pat::Path(Box::new(option_none))), + pat: self.alloc_pat_desugared(Pat::Path(option_none)), guard: None, expr: self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr), }; @@ -1561,7 +1557,7 @@ impl ExprCollector<'_> { Pat::Ref { pat, mutability } } ast::Pat::PathPat(p) => { - let path = p.path().and_then(|path| self.parse_path(path)).map(Box::new); + let path = p.path().and_then(|path| self.parse_path(path)); path.map(Pat::Path).unwrap_or(Pat::Missing) } ast::Pat::OrPat(p) => 'b: { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs index 20a6e5cc2d11..b27a97ab479d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs @@ -21,7 +21,7 @@ use crate::{ item_tree::{AttrOwner, FileItemTreeId, GenericModItem, GenericsItemTreeNode, ItemTree}, lower::LowerCtx, nameres::{DefMap, MacroSubNs}, - path::{AssociatedTypeBinding, GenericArg, GenericArgs, Path}, + path::{AssociatedTypeBinding, GenericArg, GenericArgs, NormalPath, Path}, type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRef, TypeRefId, TypesMap, TypesSourceMap}, AdtId, ConstParamId, GenericDefId, HasModule, ItemTreeLoc, LifetimeParamId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId, @@ -788,19 +788,16 @@ fn copy_path( to_source_map: &mut TypesSourceMap, ) -> Path { match path { - Path::Normal { type_anchor, mod_path, generic_args } => { - let type_anchor = type_anchor + Path::BarePath(mod_path) => Path::BarePath(mod_path.clone()), + Path::Normal(path) => { + let type_anchor = path + .type_anchor() .map(|type_ref| copy_type_ref(type_ref, from, from_source_map, to, to_source_map)); - let mod_path = mod_path.clone(); - let generic_args = generic_args.as_ref().map(|generic_args| { - generic_args - .iter() - .map(|generic_args| { - copy_generic_args(generic_args, from, from_source_map, to, to_source_map) - }) - .collect() + let mod_path = path.mod_path().clone(); + let generic_args = path.generic_args().iter().map(|generic_args| { + copy_generic_args(generic_args, from, from_source_map, to, to_source_map) }); - Path::Normal { type_anchor, mod_path, generic_args } + Path::Normal(NormalPath::new(type_anchor, mod_path, generic_args)) } Path::LangItem(lang_item, name) => Path::LangItem(*lang_item, name.clone()), } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs index df1e10323062..859634694302 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir.rs @@ -583,7 +583,7 @@ pub enum Pat { suffix: Box<[PatId]>, }, /// This might refer to a variable if a single segment path (specifically, on destructuring assignment). - Path(Box), + Path(Path), Lit(ExprId), Bind { id: BindingId, diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs index b9f47ffdd01b..38d95084e739 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs @@ -201,7 +201,7 @@ pub enum TypeBound { } #[cfg(target_pointer_width = "64")] -const _: [(); 48] = [(); ::std::mem::size_of::()]; +const _: [(); 32] = [(); ::std::mem::size_of::()]; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum UseArgRef { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/path.rs b/src/tools/rust-analyzer/crates/hir-def/src/path.rs index 4f02a59f8d31..dc6947c5b56b 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/path.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/path.rs @@ -14,6 +14,7 @@ use crate::{ use hir_expand::name::Name; use intern::Interned; use span::Edition; +use stdx::thin_vec::thin_vec_with_header_struct; use syntax::ast; pub use hir_expand::mod_path::{path, ModPath, PathKind}; @@ -47,20 +48,33 @@ impl Display for ImportAliasDisplay<'_> { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Path { - /// A normal path - Normal { - /// Type based path like `::foo`. - /// Note that paths like `::foo` are desugared to `Trait::::foo`. - type_anchor: Option, - mod_path: Interned, - /// Invariant: the same len as `self.mod_path.segments` or `None` if all segments are `None`. - generic_args: Option]>>, - }, + /// `BarePath` is used when the path has neither generics nor type anchor, since the vast majority of paths + /// are in this category, and splitting `Path` this way allows it to be more thin. When the path has either generics + /// or type anchor, it is `Path::Normal` with the generics filled with `None` even if there are none (practically + /// this is not a problem since many more paths have generics than a type anchor). + BarePath(Interned), + /// `Path::Normal` may have empty generics and type anchor (but generic args will be filled with `None`). + Normal(NormalPath), /// A link to a lang item. It is used in desugaring of things like `it?`. We can show these /// links via a normal path since they might be private and not accessible in the usage place. LangItem(LangItemTarget, Option), } +// This type is being used a lot, make sure it doesn't grow unintentionally. +#[cfg(target_arch = "x86_64")] +const _: () = { + assert!(size_of::() == 16); + assert!(size_of::>() == 16); +}; + +thin_vec_with_header_struct! { + pub new(pub(crate)) struct NormalPath, NormalPathHeader { + pub generic_args: [Option], + pub type_anchor: Option, + pub mod_path: Interned; ref, + } +} + /// Generic arguments to a path segment (e.g. the `i32` in `Option`). This /// also includes bindings of associated types, like in `Iterator`. #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -112,50 +126,49 @@ impl Path { } /// Converts a known mod path to `Path`. - pub fn from_known_path( - path: ModPath, - generic_args: impl Into]>>, - ) -> Path { - let generic_args = generic_args.into(); - assert_eq!(path.len(), generic_args.len()); - Path::Normal { - type_anchor: None, - mod_path: Interned::new(path), - generic_args: Some(generic_args), - } + pub fn from_known_path(path: ModPath, generic_args: Vec>) -> Path { + Path::Normal(NormalPath::new(None, Interned::new(path), generic_args)) } /// Converts a known mod path to `Path`. pub fn from_known_path_with_no_generic(path: ModPath) -> Path { - Path::Normal { type_anchor: None, mod_path: Interned::new(path), generic_args: None } + Path::BarePath(Interned::new(path)) } + #[inline] pub fn kind(&self) -> &PathKind { match self { - Path::Normal { mod_path, .. } => &mod_path.kind, + Path::BarePath(mod_path) => &mod_path.kind, + Path::Normal(path) => &path.mod_path().kind, Path::LangItem(..) => &PathKind::Abs, } } + #[inline] pub fn type_anchor(&self) -> Option { match self { - Path::Normal { type_anchor, .. } => *type_anchor, - Path::LangItem(..) => None, + Path::Normal(path) => path.type_anchor(), + Path::LangItem(..) | Path::BarePath(_) => None, + } + } + + #[inline] + pub fn generic_args(&self) -> Option<&[Option]> { + match self { + Path::Normal(path) => Some(path.generic_args()), + Path::LangItem(..) | Path::BarePath(_) => None, } } pub fn segments(&self) -> PathSegments<'_> { match self { - Path::Normal { mod_path, generic_args, .. } => { - let s = PathSegments { - segments: mod_path.segments(), - generic_args: generic_args.as_deref(), - }; - if let Some(generic_args) = s.generic_args { - assert_eq!(s.segments.len(), generic_args.len()); - } - s + Path::BarePath(mod_path) => { + PathSegments { segments: mod_path.segments(), generic_args: None } } + Path::Normal(path) => PathSegments { + segments: path.mod_path().segments(), + generic_args: Some(path.generic_args()), + }, Path::LangItem(_, seg) => PathSegments { segments: seg.as_ref().map_or(&[], |seg| std::slice::from_ref(seg)), generic_args: None, @@ -165,34 +178,55 @@ impl Path { pub fn mod_path(&self) -> Option<&ModPath> { match self { - Path::Normal { mod_path, .. } => Some(mod_path), + Path::BarePath(mod_path) => Some(mod_path), + Path::Normal(path) => Some(path.mod_path()), Path::LangItem(..) => None, } } pub fn qualifier(&self) -> Option { - let Path::Normal { mod_path, generic_args, type_anchor } = self else { - return None; - }; - if mod_path.is_ident() { - return None; + match self { + Path::BarePath(mod_path) => { + if mod_path.is_ident() { + return None; + } + Some(Path::BarePath(Interned::new(ModPath::from_segments( + mod_path.kind, + mod_path.segments()[..mod_path.segments().len() - 1].iter().cloned(), + )))) + } + Path::Normal(path) => { + let mod_path = path.mod_path(); + if mod_path.is_ident() { + return None; + } + let type_anchor = path.type_anchor(); + let generic_args = path.generic_args(); + let qualifier_mod_path = Interned::new(ModPath::from_segments( + mod_path.kind, + mod_path.segments()[..mod_path.segments().len() - 1].iter().cloned(), + )); + let qualifier_generic_args = &generic_args[..generic_args.len() - 1]; + Some(Path::Normal(NormalPath::new( + type_anchor, + qualifier_mod_path, + qualifier_generic_args.iter().cloned(), + ))) + } + Path::LangItem(..) => None, } - let res = Path::Normal { - type_anchor: *type_anchor, - mod_path: Interned::new(ModPath::from_segments( - mod_path.kind, - mod_path.segments()[..mod_path.segments().len() - 1].iter().cloned(), - )), - generic_args: generic_args.as_ref().map(|it| it[..it.len() - 1].to_vec().into()), - }; - Some(res) } pub fn is_self_type(&self) -> bool { - let Path::Normal { mod_path, generic_args, type_anchor } = self else { - return false; - }; - type_anchor.is_none() && generic_args.as_deref().is_none() && mod_path.is_Self() + match self { + Path::BarePath(mod_path) => mod_path.is_Self(), + Path::Normal(path) => { + path.type_anchor().is_none() + && path.mod_path().is_Self() + && path.generic_args().iter().all(|args| args.is_none()) + } + Path::LangItem(..) => false, + } } } @@ -268,16 +302,6 @@ impl GenericArgs { impl From for Path { fn from(name: Name) -> Path { - Path::Normal { - type_anchor: None, - mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))), - generic_args: None, - } - } -} - -impl From for Box { - fn from(name: Name) -> Box { - Box::new(Path::from(name)) + Path::BarePath(Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name)))) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs index 5472da59b5c7..df036ef3b605 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs @@ -2,7 +2,7 @@ use std::iter; -use crate::{lower::LowerCtx, type_ref::ConstRef}; +use crate::{lower::LowerCtx, path::NormalPath, type_ref::ConstRef}; use hir_expand::{ mod_path::resolve_crate_root, @@ -74,11 +74,9 @@ pub(super) fn lower_path(ctx: &LowerCtx<'_>, mut path: ast::Path) -> Option>::Foo desugars to Trait::Foo Some(trait_ref) => { - let Path::Normal { mod_path, generic_args: path_generic_args, .. } = - Path::from_src(ctx, trait_ref.path()?)? - else { - return None; - }; + let path = Path::from_src(ctx, trait_ref.path()?)?; + let mod_path = path.mod_path()?; + let path_generic_args = path.generic_args(); let num_segments = mod_path.segments().len(); kind = mod_path.kind; @@ -136,7 +134,7 @@ pub(super) fn lower_path(ctx: &LowerCtx<'_>, mut path: ast::Path) -> Option, mut path: ast::Path) -> Option Option { if let Some(q) = path.qualifier() { diff --git a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs index 0b49ee80511c..42c7ea7c09c8 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs @@ -167,7 +167,8 @@ impl Resolver { path: &Path, ) -> Option<(TypeNs, Option, Option)> { let path = match path { - Path::Normal { mod_path, .. } => mod_path, + Path::BarePath(mod_path) => mod_path, + Path::Normal(it) => it.mod_path(), Path::LangItem(l, seg) => { let type_ns = match *l { LangItemTarget::Union(it) => TypeNs::AdtId(it.into()), @@ -265,7 +266,8 @@ impl Resolver { mut hygiene_id: HygieneId, ) -> Option { let path = match path { - Path::Normal { mod_path, .. } => mod_path, + Path::BarePath(mod_path) => mod_path, + Path::Normal(it) => it.mod_path(), Path::LangItem(l, None) => { return Some(ResolveValueResult::ValueNs( match *l { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs index ee55dbe1c3dd..32b4ea2f28ba 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs @@ -198,7 +198,7 @@ impl InferenceContext<'_> { match &self.body[expr] { // Lang item paths cannot currently be local variables or statics. Expr::Path(Path::LangItem(_, _)) => false, - Expr::Path(Path::Normal { type_anchor: Some(_), .. }) => false, + Expr::Path(Path::Normal(path)) => path.type_anchor().is_none(), Expr::Path(path) => self .resolver .resolve_path_in_value_ns_fully( @@ -1214,7 +1214,7 @@ impl InferenceContext<'_> { let ty = match self.infer_path(path, id) { Some(ty) => ty, None => { - if matches!(path, Path::Normal { mod_path, .. } if mod_path.is_ident() || mod_path.is_self()) + if path.mod_path().is_some_and(|mod_path| mod_path.is_ident() || mod_path.is_self()) { self.push_diagnostic(InferenceDiagnostic::UnresolvedIdent { id }); } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs index 0df44f5df28b..442daa9f9ee3 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs @@ -222,7 +222,7 @@ impl InferenceContext<'_> { let _d; let (resolved_segment, remaining_segments) = match path { - Path::Normal { .. } => { + Path::Normal { .. } | Path::BarePath(_) => { assert!(remaining_index < path.segments().len()); ( path.segments().get(remaining_index - 1).unwrap(), diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs index 333942276069..c4e064005106 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs @@ -1373,12 +1373,11 @@ impl<'ctx> MirLowerCtx<'ctx> { ), }; let edition = self.edition(); - let unresolved_name = || { - MirLowerError::unresolved_path(self.db, c.as_ref(), edition, &self.body.types) - }; + let unresolved_name = + || MirLowerError::unresolved_path(self.db, c, edition, &self.body.types); let pr = self .resolver - .resolve_path_in_value_ns(self.db.upcast(), c.as_ref(), HygieneId::ROOT) + .resolve_path_in_value_ns(self.db.upcast(), c, HygieneId::ROOT) .ok_or_else(unresolved_name)?; match pr { ResolveValueResult::ValueNs(v, _) => { diff --git a/src/tools/rust-analyzer/crates/stdx/src/lib.rs b/src/tools/rust-analyzer/crates/stdx/src/lib.rs index 76dbd42ff6b2..3e36394182de 100644 --- a/src/tools/rust-analyzer/crates/stdx/src/lib.rs +++ b/src/tools/rust-analyzer/crates/stdx/src/lib.rs @@ -10,6 +10,7 @@ pub mod non_empty_vec; pub mod panic_context; pub mod process; pub mod rand; +pub mod thin_vec; pub mod thread; pub use always_assert::{always, never}; diff --git a/src/tools/rust-analyzer/crates/stdx/src/thin_vec.rs b/src/tools/rust-analyzer/crates/stdx/src/thin_vec.rs new file mode 100644 index 000000000000..700220e1d3e5 --- /dev/null +++ b/src/tools/rust-analyzer/crates/stdx/src/thin_vec.rs @@ -0,0 +1,472 @@ +use std::alloc::{dealloc, handle_alloc_error, Layout}; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; +use std::ptr::{addr_of_mut, slice_from_raw_parts_mut, NonNull}; + +/// A type that is functionally equivalent to `(Header, Box<[Item]>)`, +/// but all data is stored in one heap allocation and the pointer is thin, +/// so the whole thing's size is like a pointer. +pub struct ThinVecWithHeader { + /// INVARIANT: Points to a valid heap allocation that contains `ThinVecInner
`, + /// followed by (suitably aligned) `len` `Item`s. + ptr: NonNull>, + _marker: PhantomData<(Header, Box<[Item]>)>, +} + +// SAFETY: We essentially own both the header and the items. +unsafe impl Send for ThinVecWithHeader {} +unsafe impl Sync for ThinVecWithHeader {} + +#[derive(Clone)] +struct ThinVecInner
{ + header: Header, + len: usize, +} + +impl ThinVecWithHeader { + /// # Safety + /// + /// The iterator must produce `len` elements. + #[inline] + unsafe fn from_trusted_len_iter( + header: Header, + len: usize, + items: impl Iterator, + ) -> Self { + let (ptr, layout, items_offset) = Self::allocate(len); + + struct DeallocGuard(*mut u8, Layout); + impl Drop for DeallocGuard { + fn drop(&mut self) { + // SAFETY: We allocated this above. + unsafe { + dealloc(self.0, self.1); + } + } + } + let _dealloc_guard = DeallocGuard(ptr.as_ptr().cast::(), layout); + + // INVARIANT: Between `0..1` there are only initialized items. + struct ItemsGuard(*mut Item, *mut Item); + impl Drop for ItemsGuard { + fn drop(&mut self) { + // SAFETY: Our invariant. + unsafe { + slice_from_raw_parts_mut(self.0, self.1.offset_from(self.0) as usize) + .drop_in_place(); + } + } + } + + // SAFETY: We allocated enough space. + let mut items_ptr = unsafe { ptr.as_ptr().byte_add(items_offset).cast::() }; + // INVARIANT: There are zero elements in this range. + let mut items_guard = ItemsGuard(items_ptr, items_ptr); + items.for_each(|item| { + // SAFETY: Our precondition guarantee we won't get more than `len` items, and we allocated + // enough space for `len` items. + unsafe { + items_ptr.write(item); + items_ptr = items_ptr.add(1); + } + // INVARIANT: We just initialized this item. + items_guard.1 = items_ptr; + }); + + // SAFETY: We allocated enough space. + unsafe { + ptr.write(ThinVecInner { header, len }); + } + + std::mem::forget(items_guard); + + std::mem::forget(_dealloc_guard); + + // INVARIANT: We allocated and initialized all fields correctly. + Self { ptr, _marker: PhantomData } + } + + #[inline] + fn allocate(len: usize) -> (NonNull>, Layout, usize) { + let (layout, items_offset) = Self::layout(len); + // SAFETY: We always have `len`, so our allocation cannot be zero-sized. + let ptr = unsafe { std::alloc::alloc(layout).cast::>() }; + let Some(ptr) = NonNull::>::new(ptr) else { + handle_alloc_error(layout); + }; + (ptr, layout, items_offset) + } + + #[inline] + #[allow(clippy::should_implement_trait)] + pub fn from_iter(header: Header, items: I) -> Self + where + I: IntoIterator, + I::IntoIter: TrustedLen, + { + let items = items.into_iter(); + // SAFETY: `TrustedLen` guarantees the iterator length is exact. + unsafe { Self::from_trusted_len_iter(header, items.len(), items) } + } + + #[inline] + fn items_offset(&self) -> usize { + // SAFETY: We `pad_to_align()` in `layout()`, so at most where accessing past the end of the allocation, + // which is allowed. + unsafe { + Layout::new::>().extend(Layout::new::()).unwrap_unchecked().1 + } + } + + #[inline] + fn header_and_len(&self) -> &ThinVecInner
{ + // SAFETY: By `ptr`'s invariant, it is correctly allocated and initialized. + unsafe { &*self.ptr.as_ptr() } + } + + #[inline] + fn items_ptr(&self) -> *mut [Item] { + let len = self.header_and_len().len; + // SAFETY: `items_offset()` returns the correct offset of the items, where they are allocated. + let ptr = unsafe { self.ptr.as_ptr().byte_add(self.items_offset()).cast::() }; + slice_from_raw_parts_mut(ptr, len) + } + + #[inline] + pub fn header(&self) -> &Header { + &self.header_and_len().header + } + + #[inline] + pub fn header_mut(&mut self) -> &mut Header { + // SAFETY: By `ptr`'s invariant, it is correctly allocated and initialized. + unsafe { &mut *addr_of_mut!((*self.ptr.as_ptr()).header) } + } + + #[inline] + pub fn items(&self) -> &[Item] { + // SAFETY: `items_ptr()` gives a valid pointer. + unsafe { &*self.items_ptr() } + } + + #[inline] + pub fn items_mut(&mut self) -> &mut [Item] { + // SAFETY: `items_ptr()` gives a valid pointer. + unsafe { &mut *self.items_ptr() } + } + + #[inline] + pub fn len(&self) -> usize { + self.header_and_len().len + } + + #[inline] + fn layout(len: usize) -> (Layout, usize) { + let (layout, items_offset) = Layout::new::>() + .extend(Layout::array::(len).expect("too big `ThinVec` requested")) + .expect("too big `ThinVec` requested"); + let layout = layout.pad_to_align(); + (layout, items_offset) + } +} + +/// # Safety +/// +/// The length reported must be exactly the number of items yielded. +pub unsafe trait TrustedLen: ExactSizeIterator {} + +unsafe impl TrustedLen for std::vec::IntoIter {} +unsafe impl TrustedLen for std::slice::Iter<'_, T> {} +unsafe impl<'a, T: Clone + 'a, I: TrustedLen> TrustedLen for std::iter::Cloned {} +unsafe impl T> TrustedLen for std::iter::Map {} +unsafe impl TrustedLen for std::vec::Drain<'_, T> {} +unsafe impl TrustedLen for std::array::IntoIter {} + +impl Clone for ThinVecWithHeader { + #[inline] + fn clone(&self) -> Self { + Self::from_iter(self.header().clone(), self.items().iter().cloned()) + } +} + +impl Drop for ThinVecWithHeader { + #[inline] + fn drop(&mut self) { + // This must come before we drop `header`, because after that we cannot make a reference to it in `len()`. + let len = self.len(); + + // SAFETY: The contents are allocated and initialized. + unsafe { + addr_of_mut!((*self.ptr.as_ptr()).header).drop_in_place(); + self.items_ptr().drop_in_place(); + } + + let (layout, _) = Self::layout(len); + // SAFETY: This was allocated in `new()` with the same layout calculation. + unsafe { + dealloc(self.ptr.as_ptr().cast::(), layout); + } + } +} + +impl fmt::Debug for ThinVecWithHeader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ThinVecWithHeader") + .field("header", self.header()) + .field("items", &self.items()) + .finish() + } +} + +impl PartialEq for ThinVecWithHeader { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.header() == other.header() && self.items() == other.items() + } +} + +impl Eq for ThinVecWithHeader {} + +impl Hash for ThinVecWithHeader { + #[inline] + fn hash(&self, state: &mut H) { + self.header().hash(state); + self.items().hash(state); + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct ThinVec(ThinVecWithHeader<(), T>); + +impl ThinVec { + #[inline] + #[allow(clippy::should_implement_trait)] + pub fn from_iter(values: I) -> Self + where + I: IntoIterator, + I::IntoIter: TrustedLen, + { + Self(ThinVecWithHeader::from_iter((), values)) + } + + #[inline] + pub fn len(&self) -> usize { + self.0.len() + } + + #[inline] + pub fn iter(&self) -> std::slice::Iter<'_, T> { + (**self).iter() + } + + #[inline] + pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> { + (**self).iter_mut() + } +} + +impl Deref for ThinVec { + type Target = [T]; + + #[inline] + fn deref(&self) -> &Self::Target { + self.0.items() + } +} + +impl DerefMut for ThinVec { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + self.0.items_mut() + } +} + +impl<'a, T> IntoIterator for &'a ThinVec { + type IntoIter = std::slice::Iter<'a, T>; + type Item = &'a T; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, T> IntoIterator for &'a mut ThinVec { + type IntoIter = std::slice::IterMut<'a, T>; + type Item = &'a mut T; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +impl fmt::Debug for ThinVec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(&**self).finish() + } +} + +/// A [`ThinVec`] that requires no allocation for the empty case. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct EmptyOptimizedThinVec(Option>); + +impl EmptyOptimizedThinVec { + #[inline] + #[allow(clippy::should_implement_trait)] + pub fn from_iter(values: I) -> Self + where + I: IntoIterator, + I::IntoIter: TrustedLen, + { + let values = values.into_iter(); + if values.len() == 0 { + Self::empty() + } else { + Self(Some(ThinVec::from_iter(values))) + } + } + + #[inline] + pub fn empty() -> Self { + Self(None) + } + + #[inline] + pub fn len(&self) -> usize { + self.0.as_ref().map_or(0, ThinVec::len) + } + + #[inline] + pub fn iter(&self) -> std::slice::Iter<'_, T> { + (**self).iter() + } + + #[inline] + pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> { + (**self).iter_mut() + } +} + +impl Default for EmptyOptimizedThinVec { + #[inline] + fn default() -> Self { + Self::empty() + } +} + +impl Deref for EmptyOptimizedThinVec { + type Target = [T]; + + #[inline] + fn deref(&self) -> &Self::Target { + self.0.as_deref().unwrap_or_default() + } +} + +impl DerefMut for EmptyOptimizedThinVec { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + self.0.as_deref_mut().unwrap_or_default() + } +} + +impl<'a, T> IntoIterator for &'a EmptyOptimizedThinVec { + type IntoIter = std::slice::Iter<'a, T>; + type Item = &'a T; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, T> IntoIterator for &'a mut EmptyOptimizedThinVec { + type IntoIter = std::slice::IterMut<'a, T>; + type Item = &'a mut T; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +impl fmt::Debug for EmptyOptimizedThinVec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(&**self).finish() + } +} + +/// Syntax: +/// +/// ```ignore +/// thin_vec_with_header_struct! { +/// pub new(pub(crate)) struct MyCoolStruct, MyCoolStructHeader { +/// pub(crate) variable_length: [Ty], +/// pub field1: CopyTy, +/// pub field2: NonCopyTy; ref, +/// } +/// } +/// ``` +#[doc(hidden)] +#[macro_export] +macro_rules! thin_vec_with_header_struct_ { + (@maybe_ref (ref) $($t:tt)*) => { &$($t)* }; + (@maybe_ref () $($t:tt)*) => { $($t)* }; + ( + $vis:vis new($new_vis:vis) struct $struct:ident, $header:ident { + $items_vis:vis $items:ident : [$items_ty:ty], + $( $header_var_vis:vis $header_var:ident : $header_var_ty:ty $(; $ref:ident)?, )+ + } + ) => { + #[derive(Debug, Clone, Eq, PartialEq, Hash)] + struct $header { + $( $header_var : $header_var_ty, )+ + } + + #[derive(Clone, Eq, PartialEq, Hash)] + $vis struct $struct($crate::thin_vec::ThinVecWithHeader<$header, $items_ty>); + + impl $struct { + #[inline] + #[allow(unused)] + $new_vis fn new( + $( $header_var: $header_var_ty, )+ + $items: I, + ) -> Self + where + I: ::std::iter::IntoIterator, + I::IntoIter: $crate::thin_vec::TrustedLen, + { + Self($crate::thin_vec::ThinVecWithHeader::from_iter( + $header { $( $header_var, )+ }, + $items, + )) + } + + #[inline] + $items_vis fn $items(&self) -> &[$items_ty] { + self.0.items() + } + + $( + #[inline] + $header_var_vis fn $header_var(&self) -> $crate::thin_vec_with_header_struct_!(@maybe_ref ($($ref)?) $header_var_ty) { + $crate::thin_vec_with_header_struct_!(@maybe_ref ($($ref)?) self.0.header().$header_var) + } + )+ + } + + impl ::std::fmt::Debug for $struct { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + f.debug_struct(stringify!($struct)) + $( .field(stringify!($header_var), &self.$header_var()) )* + .field(stringify!($items), &self.$items()) + .finish() + } + } + }; +} +pub use crate::thin_vec_with_header_struct_ as thin_vec_with_header_struct; diff --git a/src/tools/rust-analyzer/xtask/src/tidy.rs b/src/tools/rust-analyzer/xtask/src/tidy.rs index 0268e2473c08..c3d531344a19 100644 --- a/src/tools/rust-analyzer/xtask/src/tidy.rs +++ b/src/tools/rust-analyzer/xtask/src/tidy.rs @@ -223,7 +223,7 @@ struct TidyDocs { impl TidyDocs { fn visit(&mut self, path: &Path, text: &str) { // Tests and diagnostic fixes don't need module level comments. - if is_exclude_dir(path, &["tests", "test_data", "fixes", "grammar", "ra-salsa"]) { + if is_exclude_dir(path, &["tests", "test_data", "fixes", "grammar", "ra-salsa", "stdx"]) { return; } From 3f638482a361d0fe56157776d98d2572fda0f945 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 20 Oct 2024 01:56:51 +0300 Subject: [PATCH 238/366] Shrink `TypeRef` from 16 from 32 bytes Only references and arrays need to be boxed, and they comprise only 9.4% of the types (according to counting on r-a's code). This saves 17mb. --- .../crates/hir-def/src/generics.rs | 101 +++++++++--------- .../crates/hir-def/src/hir/type_ref.rs | 88 +++++++++------ .../crates/hir-def/src/item_tree/lower.rs | 35 +++--- .../rust-analyzer/crates/hir-def/src/lower.rs | 7 +- .../crates/hir-def/src/path/lower.rs | 8 +- .../crates/hir-def/src/pretty.rs | 24 ++--- .../crates/hir-ty/src/display.rs | 26 ++--- .../rust-analyzer/crates/hir-ty/src/lower.rs | 28 ++--- .../rust-analyzer/crates/hir/src/display.rs | 6 +- src/tools/rust-analyzer/crates/hir/src/lib.rs | 4 +- 10 files changed, 178 insertions(+), 149 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs index b27a97ab479d..6b79850e9c40 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/generics.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/generics.rs @@ -11,7 +11,10 @@ use hir_expand::{ ExpandResult, }; use la_arena::{Arena, RawIdx}; -use stdx::impl_from; +use stdx::{ + impl_from, + thin_vec::{EmptyOptimizedThinVec, ThinVec}, +}; use syntax::ast::{self, HasGenericParams, HasName, HasTypeBounds}; use triomphe::Arc; @@ -22,7 +25,10 @@ use crate::{ lower::LowerCtx, nameres::{DefMap, MacroSubNs}, path::{AssociatedTypeBinding, GenericArg, GenericArgs, NormalPath, Path}, - type_ref::{ConstRef, LifetimeRef, TypeBound, TypeRef, TypeRefId, TypesMap, TypesSourceMap}, + type_ref::{ + ArrayType, ConstRef, FnType, LifetimeRef, RefType, TypeBound, TypeRef, TypeRefId, TypesMap, + TypesSourceMap, + }, AdtId, ConstParamId, GenericDefId, HasModule, ItemTreeLoc, LifetimeParamId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId, }; @@ -590,7 +596,7 @@ impl GenericParamsCollector { self.where_predicates.push(predicate); } - fn fill_impl_trait_bounds(&mut self, impl_bounds: Vec>) { + fn fill_impl_trait_bounds(&mut self, impl_bounds: Vec>) { for bounds in impl_bounds { let param = TypeParamData { name: None, @@ -598,10 +604,10 @@ impl GenericParamsCollector { provenance: TypeParamProvenance::ArgumentImplTrait, }; let param_id = self.type_or_consts.alloc(param.into()); - for bound in bounds { + for bound in &bounds { self.where_predicates.push(WherePredicate::TypeBound { target: WherePredicateTypeTarget::TypeOrConstParam(param_id), - bound, + bound: bound.clone(), }); } } @@ -725,46 +731,45 @@ fn copy_type_ref( to_source_map: &mut TypesSourceMap, ) -> TypeRefId { let result = match &from[type_ref] { - &TypeRef::Fn { ref params, is_varargs, is_unsafe, ref abi } => { - let params = params - .iter() - .map(|(name, param_type)| { - ( - name.clone(), - copy_type_ref(*param_type, from, from_source_map, to, to_source_map), - ) - }) - .collect(); - TypeRef::Fn { params, is_varargs, is_unsafe, abi: abi.clone() } + TypeRef::Fn(fn_) => { + let params = fn_.params().iter().map(|(name, param_type)| { + (name.clone(), copy_type_ref(*param_type, from, from_source_map, to, to_source_map)) + }); + TypeRef::Fn(FnType::new(fn_.is_varargs(), fn_.is_unsafe(), fn_.abi().clone(), params)) } - TypeRef::Tuple(types) => TypeRef::Tuple( - types - .iter() - .map(|&t| copy_type_ref(t, from, from_source_map, to, to_source_map)) - .collect(), - ), + TypeRef::Tuple(types) => TypeRef::Tuple(EmptyOptimizedThinVec::from_iter( + types.iter().map(|&t| copy_type_ref(t, from, from_source_map, to, to_source_map)), + )), &TypeRef::RawPtr(type_ref, mutbl) => TypeRef::RawPtr( copy_type_ref(type_ref, from, from_source_map, to, to_source_map), mutbl, ), - TypeRef::Reference(type_ref, lifetime, mutbl) => TypeRef::Reference( - copy_type_ref(*type_ref, from, from_source_map, to, to_source_map), - lifetime.clone(), - *mutbl, - ), - TypeRef::Array(type_ref, len) => TypeRef::Array( - copy_type_ref(*type_ref, from, from_source_map, to, to_source_map), - len.clone(), - ), + TypeRef::Reference(ref_) => TypeRef::Reference(Box::new(RefType { + ty: copy_type_ref(ref_.ty, from, from_source_map, to, to_source_map), + lifetime: ref_.lifetime.clone(), + mutability: ref_.mutability, + })), + TypeRef::Array(array) => TypeRef::Array(Box::new(ArrayType { + ty: copy_type_ref(array.ty, from, from_source_map, to, to_source_map), + len: array.len.clone(), + })), &TypeRef::Slice(type_ref) => { TypeRef::Slice(copy_type_ref(type_ref, from, from_source_map, to, to_source_map)) } - TypeRef::ImplTrait(bounds) => TypeRef::ImplTrait( - copy_type_bounds(bounds, from, from_source_map, to, to_source_map).into(), - ), - TypeRef::DynTrait(bounds) => TypeRef::DynTrait( - copy_type_bounds(bounds, from, from_source_map, to, to_source_map).into(), - ), + TypeRef::ImplTrait(bounds) => TypeRef::ImplTrait(ThinVec::from_iter(copy_type_bounds( + bounds, + from, + from_source_map, + to, + to_source_map, + ))), + TypeRef::DynTrait(bounds) => TypeRef::DynTrait(ThinVec::from_iter(copy_type_bounds( + bounds, + from, + from_source_map, + to, + to_source_map, + ))), TypeRef::Path(path) => { TypeRef::Path(copy_path(path, from, from_source_map, to, to_source_map)) } @@ -833,7 +838,8 @@ fn copy_generic_args( copy_type_ref(type_ref, from, from_source_map, to, to_source_map) }); let bounds = - copy_type_bounds(&binding.bounds, from, from_source_map, to, to_source_map); + copy_type_bounds(&binding.bounds, from, from_source_map, to, to_source_map) + .collect(); AssociatedTypeBinding { name, args, type_ref, bounds } }) .collect(); @@ -846,17 +852,14 @@ fn copy_generic_args( }) } -fn copy_type_bounds( - bounds: &[TypeBound], - from: &TypesMap, - from_source_map: &TypesSourceMap, - to: &mut TypesMap, - to_source_map: &mut TypesSourceMap, -) -> Box<[TypeBound]> { - bounds - .iter() - .map(|bound| copy_type_bound(bound, from, from_source_map, to, to_source_map)) - .collect() +fn copy_type_bounds<'a>( + bounds: &'a [TypeBound], + from: &'a TypesMap, + from_source_map: &'a TypesSourceMap, + to: &'a mut TypesMap, + to_source_map: &'a mut TypesSourceMap, +) -> impl stdx::thin_vec::TrustedLen + 'a { + bounds.iter().map(|bound| copy_type_bound(bound, from, from_source_map, to, to_source_map)) } fn copy_type_bound( diff --git a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs index 38d95084e739..2582340c0f81 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/hir/type_ref.rs @@ -12,6 +12,7 @@ use hir_expand::{ use intern::{sym, Symbol}; use la_arena::{Arena, ArenaMap, Idx}; use span::Edition; +use stdx::thin_vec::{thin_vec_with_header_struct, EmptyOptimizedThinVec, ThinVec}; use syntax::{ ast::{self, HasGenericArgs, HasName, IsString}, AstPtr, @@ -108,31 +109,51 @@ impl TraitRef { } } +thin_vec_with_header_struct! { + pub new(pub(crate)) struct FnType, FnTypeHeader { + pub params: [(Option, TypeRefId)], + pub is_varargs: bool, + pub is_unsafe: bool, + pub abi: Option; ref, + } +} + +#[derive(Clone, PartialEq, Eq, Hash, Debug)] +pub struct ArrayType { + pub ty: TypeRefId, + // FIXME: This should be Ast + pub len: ConstRef, +} + +#[derive(Clone, PartialEq, Eq, Hash, Debug)] +pub struct RefType { + pub ty: TypeRefId, + pub lifetime: Option, + pub mutability: Mutability, +} + /// Compare ty::Ty #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum TypeRef { Never, Placeholder, - Tuple(Vec), + Tuple(EmptyOptimizedThinVec), Path(Path), RawPtr(TypeRefId, Mutability), - Reference(TypeRefId, Option, Mutability), - // FIXME: This should be Array(TypeRefId, Ast), - Array(TypeRefId, ConstRef), + Reference(Box), + Array(Box), Slice(TypeRefId), /// A fn pointer. Last element of the vector is the return type. - Fn { - params: Box<[(Option, TypeRefId)]>, - is_varargs: bool, - is_unsafe: bool, - abi: Option, - }, - ImplTrait(Vec), - DynTrait(Vec), + Fn(FnType), + ImplTrait(ThinVec), + DynTrait(ThinVec), Macro(AstId), Error, } +#[cfg(target_arch = "x86_64")] +const _: () = assert!(size_of::() == 16); + pub type TypeRefId = Idx; #[derive(Default, Clone, PartialEq, Eq, Debug, Hash)] @@ -222,9 +243,9 @@ impl TypeRef { pub fn from_ast(ctx: &LowerCtx<'_>, node: ast::Type) -> TypeRefId { let ty = match &node { ast::Type::ParenType(inner) => return TypeRef::from_ast_opt(ctx, inner.ty()), - ast::Type::TupleType(inner) => { - TypeRef::Tuple(inner.fields().map(|it| TypeRef::from_ast(ctx, it)).collect()) - } + ast::Type::TupleType(inner) => TypeRef::Tuple(EmptyOptimizedThinVec::from_iter( + Vec::from_iter(inner.fields().map(|it| TypeRef::from_ast(ctx, it))), + )), ast::Type::NeverType(..) => TypeRef::Never, ast::Type::PathType(inner) => { // FIXME: Use `Path::from_src` @@ -241,14 +262,17 @@ impl TypeRef { } ast::Type::ArrayType(inner) => { let len = ConstRef::from_const_arg(ctx, inner.const_arg()); - TypeRef::Array(TypeRef::from_ast_opt(ctx, inner.ty()), len) + TypeRef::Array(Box::new(ArrayType { + ty: TypeRef::from_ast_opt(ctx, inner.ty()), + len, + })) } ast::Type::SliceType(inner) => TypeRef::Slice(TypeRef::from_ast_opt(ctx, inner.ty())), ast::Type::RefType(inner) => { let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty()); let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(<)); let mutability = Mutability::from_mutable(inner.mut_token().is_some()); - TypeRef::Reference(inner_ty, lifetime, mutability) + TypeRef::Reference(Box::new(RefType { ty: inner_ty, lifetime, mutability })) } ast::Type::InferType(_inner) => TypeRef::Placeholder, ast::Type::FnPtrType(inner) => { @@ -256,7 +280,7 @@ impl TypeRef { .ret_type() .and_then(|rt| rt.ty()) .map(|it| TypeRef::from_ast(ctx, it)) - .unwrap_or_else(|| ctx.alloc_type_ref_desugared(TypeRef::Tuple(Vec::new()))); + .unwrap_or_else(|| ctx.alloc_type_ref_desugared(TypeRef::unit())); let mut is_varargs = false; let mut params = if let Some(pl) = inner.param_list() { if let Some(param) = pl.params().last() { @@ -288,12 +312,7 @@ impl TypeRef { let abi = inner.abi().map(lower_abi); params.push((None, ret_ty)); - TypeRef::Fn { - params: params.into(), - is_varargs, - is_unsafe: inner.unsafe_token().is_some(), - abi, - } + TypeRef::Fn(FnType::new(is_varargs, inner.unsafe_token().is_some(), abi, params)) } // for types are close enough for our purposes to the inner type for now... ast::Type::ForType(inner) => return TypeRef::from_ast_opt(ctx, inner.ty()), @@ -325,7 +344,7 @@ impl TypeRef { } pub(crate) fn unit() -> TypeRef { - TypeRef::Tuple(Vec::new()) + TypeRef::Tuple(EmptyOptimizedThinVec::empty()) } pub fn walk(this: TypeRefId, map: &TypesMap, f: &mut impl FnMut(&TypeRef)) { @@ -335,14 +354,13 @@ impl TypeRef { let type_ref = &map[type_ref]; f(type_ref); match type_ref { - TypeRef::Fn { params, is_varargs: _, is_unsafe: _, abi: _ } => { - params.iter().for_each(|&(_, param_type)| go(param_type, f, map)) + TypeRef::Fn(fn_) => { + fn_.params().iter().for_each(|&(_, param_type)| go(param_type, f, map)) } TypeRef::Tuple(types) => types.iter().for_each(|&t| go(t, f, map)), - TypeRef::RawPtr(type_ref, _) - | TypeRef::Reference(type_ref, ..) - | TypeRef::Array(type_ref, _) - | TypeRef::Slice(type_ref) => go(*type_ref, f, map), + TypeRef::RawPtr(type_ref, _) | TypeRef::Slice(type_ref) => go(*type_ref, f, map), + TypeRef::Reference(it) => go(it.ty, f, map), + TypeRef::Array(it) => go(it.ty, f, map), TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => { for bound in bounds { match bound { @@ -394,11 +412,13 @@ impl TypeRef { pub(crate) fn type_bounds_from_ast( lower_ctx: &LowerCtx<'_>, type_bounds_opt: Option, -) -> Vec { +) -> ThinVec { if let Some(type_bounds) = type_bounds_opt { - type_bounds.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)).collect() + ThinVec::from_iter(Vec::from_iter( + type_bounds.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)), + )) } else { - vec![] + ThinVec::from_iter([]) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index 3367d5540f54..bd17fce37b73 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -12,6 +12,7 @@ use intern::{sym, Symbol}; use la_arena::Arena; use rustc_hash::FxHashMap; use span::{AstIdMap, SyntaxContextId}; +use stdx::thin_vec::ThinVec; use syntax::{ ast::{self, HasModuleItem, HasName, HasTypeBounds, IsString}, AstNode, @@ -33,8 +34,8 @@ use crate::{ lower::LowerCtx, path::AssociatedTypeBinding, type_ref::{ - LifetimeRef, TraitBoundModifier, TraitRef, TypeBound, TypeRef, TypeRefId, TypesMap, - TypesSourceMap, + LifetimeRef, RefType, TraitBoundModifier, TraitRef, TypeBound, TypeRef, TypeRefId, + TypesMap, TypesSourceMap, }, visibility::RawVisibility, LocalLifetimeParamId, LocalTypeOrConstParamId, @@ -463,20 +464,20 @@ impl<'a> Ctx<'a> { )); match self_param.kind() { ast::SelfParamKind::Owned => self_type, - ast::SelfParamKind::Ref => { - body_ctx.alloc_type_ref_desugared(TypeRef::Reference( - self_type, - self_param.lifetime().as_ref().map(LifetimeRef::new), - Mutability::Shared, - )) - } - ast::SelfParamKind::MutRef => { - body_ctx.alloc_type_ref_desugared(TypeRef::Reference( - self_type, - self_param.lifetime().as_ref().map(LifetimeRef::new), - Mutability::Mut, - )) - } + ast::SelfParamKind::Ref => body_ctx.alloc_type_ref_desugared( + TypeRef::Reference(Box::new(RefType { + ty: self_type, + lifetime: self_param.lifetime().as_ref().map(LifetimeRef::new), + mutability: Mutability::Shared, + })), + ), + ast::SelfParamKind::MutRef => body_ctx.alloc_type_ref_desugared( + TypeRef::Reference(Box::new(RefType { + ty: self_type, + lifetime: self_param.lifetime().as_ref().map(LifetimeRef::new), + mutability: Mutability::Mut, + })), + ), } } }; @@ -511,7 +512,7 @@ impl<'a> Ctx<'a> { let ret_type = if func.async_token().is_some() { let future_impl = desugar_future_path(ret_type); let ty_bound = TypeBound::Path(future_impl, TraitBoundModifier::None); - body_ctx.alloc_type_ref_desugared(TypeRef::ImplTrait(vec![ty_bound])) + body_ctx.alloc_type_ref_desugared(TypeRef::ImplTrait(ThinVec::from_iter([ty_bound]))) } else { ret_type }; diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/lower.rs index fef3b3442333..df5847929c55 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lower.rs @@ -6,6 +6,7 @@ use hir_expand::{ AstId, HirFileId, InFile, }; use span::{AstIdMap, AstIdNode}; +use stdx::thin_vec::ThinVec; use syntax::ast; use triomphe::Arc; @@ -20,7 +21,7 @@ pub struct LowerCtx<'a> { file_id: HirFileId, span_map: OnceCell, ast_id_map: OnceCell>, - impl_trait_bounds: RefCell>>, + impl_trait_bounds: RefCell>>, // Prevent nested impl traits like `impl Foo`. outer_impl_trait: RefCell, types_map: RefCell<(&'a mut TypesMap, &'a mut TypesSourceMap)>, @@ -95,11 +96,11 @@ impl<'a> LowerCtx<'a> { ) } - pub fn update_impl_traits_bounds(&self, bounds: Vec) { + pub fn update_impl_traits_bounds(&self, bounds: ThinVec) { self.impl_trait_bounds.borrow_mut().push(bounds); } - pub fn take_impl_traits_bounds(&self) -> Vec> { + pub fn take_impl_traits_bounds(&self) -> Vec> { self.impl_trait_bounds.take() } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs index df036ef3b605..c328b9c6ce2f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/path/lower.rs @@ -9,6 +9,7 @@ use hir_expand::{ name::{AsName, Name}, }; use intern::{sym, Interned}; +use stdx::thin_vec::EmptyOptimizedThinVec; use syntax::ast::{self, AstNode, HasGenericArgs, HasTypeBounds}; use crate::{ @@ -267,8 +268,9 @@ fn lower_generic_args_from_fn_path( let type_ref = TypeRef::from_ast_opt(ctx, param.ty()); param_types.push(type_ref); } - let args = - Box::new([GenericArg::Type(ctx.alloc_type_ref_desugared(TypeRef::Tuple(param_types)))]); + let args = Box::new([GenericArg::Type( + ctx.alloc_type_ref_desugared(TypeRef::Tuple(EmptyOptimizedThinVec::from_iter(param_types))), + )]); let bindings = if let Some(ret_type) = ret_type { let type_ref = TypeRef::from_ast_opt(ctx, ret_type.ty()); Box::new([AssociatedTypeBinding { @@ -279,7 +281,7 @@ fn lower_generic_args_from_fn_path( }]) } else { // -> () - let type_ref = ctx.alloc_type_ref_desugared(TypeRef::Tuple(Vec::new())); + let type_ref = ctx.alloc_type_ref_desugared(TypeRef::unit()); Box::new([AssociatedTypeBinding { name: Name::new_symbol_root(sym::Output.clone()), args: None, diff --git a/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs index f8fd5cfb7751..9ceb82d5fd6b 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/pretty.rs @@ -187,35 +187,35 @@ pub(crate) fn print_type_ref( write!(buf, "{mtbl} ")?; print_type_ref(db, *pointee, map, buf, edition)?; } - TypeRef::Reference(pointee, lt, mtbl) => { - let mtbl = match mtbl { + TypeRef::Reference(ref_) => { + let mtbl = match ref_.mutability { Mutability::Shared => "", Mutability::Mut => "mut ", }; write!(buf, "&")?; - if let Some(lt) = lt { + if let Some(lt) = &ref_.lifetime { write!(buf, "{} ", lt.name.display(db.upcast(), edition))?; } write!(buf, "{mtbl}")?; - print_type_ref(db, *pointee, map, buf, edition)?; + print_type_ref(db, ref_.ty, map, buf, edition)?; } - TypeRef::Array(elem, len) => { + TypeRef::Array(array) => { write!(buf, "[")?; - print_type_ref(db, *elem, map, buf, edition)?; - write!(buf, "; {}]", len.display(db.upcast(), edition))?; + print_type_ref(db, array.ty, map, buf, edition)?; + write!(buf, "; {}]", array.len.display(db.upcast(), edition))?; } TypeRef::Slice(elem) => { write!(buf, "[")?; print_type_ref(db, *elem, map, buf, edition)?; write!(buf, "]")?; } - TypeRef::Fn { params: args_and_ret, is_varargs: varargs, is_unsafe, abi } => { + TypeRef::Fn(fn_) => { let ((_, return_type), args) = - args_and_ret.split_last().expect("TypeRef::Fn is missing return type"); - if *is_unsafe { + fn_.params().split_last().expect("TypeRef::Fn is missing return type"); + if fn_.is_unsafe() { write!(buf, "unsafe ")?; } - if let Some(abi) = abi { + if let Some(abi) = fn_.abi() { buf.write_str("extern ")?; buf.write_str(abi.as_str())?; buf.write_char(' ')?; @@ -227,7 +227,7 @@ pub(crate) fn print_type_ref( } print_type_ref(db, *typeref, map, buf, edition)?; } - if *varargs { + if fn_.is_varargs() { if !args.is_empty() { write!(buf, ", ")?; } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs index e5c3c35e2bcc..277dabe9aa34 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs @@ -1964,39 +1964,39 @@ impl HirDisplayWithTypesMap for TypeRefId { write!(f, "{mutability}")?; inner.hir_fmt(f, types_map)?; } - TypeRef::Reference(inner, lifetime, mutability) => { - let mutability = match mutability { + TypeRef::Reference(ref_) => { + let mutability = match ref_.mutability { hir_def::type_ref::Mutability::Shared => "", hir_def::type_ref::Mutability::Mut => "mut ", }; write!(f, "&")?; - if let Some(lifetime) = lifetime { + if let Some(lifetime) = &ref_.lifetime { write!(f, "{} ", lifetime.name.display(f.db.upcast(), f.edition()))?; } write!(f, "{mutability}")?; - inner.hir_fmt(f, types_map)?; + ref_.ty.hir_fmt(f, types_map)?; } - TypeRef::Array(inner, len) => { + TypeRef::Array(array) => { write!(f, "[")?; - inner.hir_fmt(f, types_map)?; - write!(f, "; {}]", len.display(f.db.upcast(), f.edition()))?; + array.ty.hir_fmt(f, types_map)?; + write!(f, "; {}]", array.len.display(f.db.upcast(), f.edition()))?; } TypeRef::Slice(inner) => { write!(f, "[")?; inner.hir_fmt(f, types_map)?; write!(f, "]")?; } - &TypeRef::Fn { params: ref parameters, is_varargs, is_unsafe, ref abi } => { - if is_unsafe { + TypeRef::Fn(fn_) => { + if fn_.is_unsafe() { write!(f, "unsafe ")?; } - if let Some(abi) = abi { + if let Some(abi) = fn_.abi() { f.write_str("extern \"")?; f.write_str(abi.as_str())?; f.write_str("\" ")?; } write!(f, "fn(")?; - if let Some(((_, return_type), function_parameters)) = parameters.split_last() { + if let Some(((_, return_type), function_parameters)) = fn_.params().split_last() { for index in 0..function_parameters.len() { let (param_name, param_type) = &function_parameters[index]; if let Some(name) = param_name { @@ -2009,8 +2009,8 @@ impl HirDisplayWithTypesMap for TypeRefId { write!(f, ", ")?; } } - if is_varargs { - write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?; + if fn_.is_varargs() { + write!(f, "{}...", if fn_.params().len() == 1 { "" } else { ", " })?; } write!(f, ")")?; match &types_map[*return_type] { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs index ed1ee4837494..e3a92e52f61e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs @@ -297,37 +297,39 @@ impl<'a> TyLoweringContext<'a> { let inner_ty = self.lower_ty(inner); TyKind::Raw(lower_to_chalk_mutability(mutability), inner_ty).intern(Interner) } - TypeRef::Array(inner, len) => { - let inner_ty = self.lower_ty(*inner); - let const_len = self.lower_const(len, TyBuilder::usize()); + TypeRef::Array(array) => { + let inner_ty = self.lower_ty(array.ty); + let const_len = self.lower_const(&array.len, TyBuilder::usize()); TyKind::Array(inner_ty, const_len).intern(Interner) } &TypeRef::Slice(inner) => { let inner_ty = self.lower_ty(inner); TyKind::Slice(inner_ty).intern(Interner) } - TypeRef::Reference(inner, lifetime, mutability) => { - let inner_ty = self.lower_ty(*inner); + TypeRef::Reference(ref_) => { + let inner_ty = self.lower_ty(ref_.ty); // FIXME: It should infer the eldided lifetimes instead of stubbing with static - let lifetime = - lifetime.as_ref().map_or_else(error_lifetime, |lr| self.lower_lifetime(lr)); - TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty) + let lifetime = ref_ + .lifetime + .as_ref() + .map_or_else(error_lifetime, |lr| self.lower_lifetime(lr)); + TyKind::Ref(lower_to_chalk_mutability(ref_.mutability), lifetime, inner_ty) .intern(Interner) } TypeRef::Placeholder => TyKind::Error.intern(Interner), - &TypeRef::Fn { ref params, is_varargs: variadic, is_unsafe, ref abi } => { + TypeRef::Fn(fn_) => { let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { Substitution::from_iter( Interner, - params.iter().map(|&(_, tr)| ctx.lower_ty(tr)), + fn_.params().iter().map(|&(_, tr)| ctx.lower_ty(tr)), ) }); TyKind::Function(FnPointer { num_binders: 0, // FIXME lower `for<'a> fn()` correctly sig: FnSig { - abi: abi.as_ref().map_or(FnAbi::Rust, FnAbi::from_symbol), - safety: if is_unsafe { Safety::Unsafe } else { Safety::Safe }, - variadic, + abi: fn_.abi().as_ref().map_or(FnAbi::Rust, FnAbi::from_symbol), + safety: if fn_.is_unsafe() { Safety::Unsafe } else { Safety::Safe }, + variadic: fn_.is_varargs(), }, substitution: FnSubst(substs), }) diff --git a/src/tools/rust-analyzer/crates/hir/src/display.rs b/src/tools/rust-analyzer/crates/hir/src/display.rs index 80370c7421e6..9275f45d881b 100644 --- a/src/tools/rust-analyzer/crates/hir/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir/src/display.rs @@ -196,13 +196,13 @@ impl HirDisplay for SelfParam { let param = *data.params.first().unwrap(); match &data.types_map[param] { TypeRef::Path(p) if p.is_self_type() => f.write_str("self"), - TypeRef::Reference(inner, lifetime, mut_) if matches!(&data.types_map[*inner], TypeRef::Path(p) if p.is_self_type()) => + TypeRef::Reference(ref_) if matches!(&data.types_map[ref_.ty], TypeRef::Path(p) if p.is_self_type()) => { f.write_char('&')?; - if let Some(lifetime) = lifetime { + if let Some(lifetime) = &ref_.lifetime { write!(f, "{} ", lifetime.name.display(f.db.upcast(), f.edition()))?; } - if let hir_def::type_ref::Mutability::Mut = mut_ { + if let hir_def::type_ref::Mutability::Mut = ref_.mutability { f.write_str("mut ")?; } f.write_str("self") diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index d264bb3901f0..4e994cae849f 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -2420,8 +2420,8 @@ impl SelfParam { func_data .params .first() - .map(|¶m| match func_data.types_map[param] { - TypeRef::Reference(.., mutability) => match mutability { + .map(|¶m| match &func_data.types_map[param] { + TypeRef::Reference(ref_) => match ref_.mutability { hir_def::type_ref::Mutability::Shared => Access::Shared, hir_def::type_ref::Mutability::Mut => Access::Exclusive, }, From 1613548cdb8f001e8afd19d56fe52ba379555e24 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 25 Oct 2024 07:28:29 +0200 Subject: [PATCH 239/366] Don't compute diagnostics for non local files --- .../rust-analyzer/src/handlers/dispatch.rs | 4 ++-- .../rust-analyzer/src/handlers/request.rs | 20 ++++++++++++------- .../crates/rust-analyzer/src/main_loop.rs | 2 +- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs index 21f95a945d9a..c2cf41757248 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs @@ -121,8 +121,8 @@ impl RequestDispatcher<'_> { } /// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not - /// ready this will return a default constructed [`R::Result`]. - pub(crate) fn on_or( + /// ready this will return a `default` constructed [`R::Result`]. + pub(crate) fn on_with( &mut self, f: fn(GlobalStateSnapshot, R::Params) -> anyhow::Result, default: impl FnOnce() -> R::Result, diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs index 35c61a336e7a..fa584ab4d21b 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs @@ -479,12 +479,8 @@ pub(crate) fn handle_document_diagnostics( snap: GlobalStateSnapshot, params: lsp_types::DocumentDiagnosticParams, ) -> anyhow::Result { - let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?; - let source_root = snap.analysis.source_root_id(file_id)?; - let line_index = snap.file_line_index(file_id)?; - let config = snap.config.diagnostics(Some(source_root)); - if !config.enabled { - return Ok(lsp_types::DocumentDiagnosticReportResult::Report( + const EMPTY: lsp_types::DocumentDiagnosticReportResult = + lsp_types::DocumentDiagnosticReportResult::Report( lsp_types::DocumentDiagnosticReport::Full( lsp_types::RelatedFullDocumentDiagnosticReport { related_documents: None, @@ -494,8 +490,18 @@ pub(crate) fn handle_document_diagnostics( }, }, ), - )); + ); + + let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?; + let source_root = snap.analysis.source_root_id(file_id)?; + if !snap.analysis.is_local_source_root(source_root)? { + return Ok(EMPTY); } + let config = snap.config.diagnostics(Some(source_root)); + if !config.enabled { + return Ok(EMPTY); + } + let line_index = snap.file_line_index(file_id)?; let supports_related = snap.config.text_document_diagnostic_related_document_support(); let mut related_documents = FxHashMap::default(); diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index c531cd8d114e..9ade3be5d688 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -1092,7 +1092,7 @@ impl GlobalState { .on_latency_sensitive::(handlers::handle_semantic_tokens_range) // FIXME: Some of these NO_RETRY could be retries if the file they are interested didn't change. // All other request handlers - .on_or::(handlers::handle_document_diagnostics, || lsp_types::DocumentDiagnosticReportResult::Report( + .on_with::(handlers::handle_document_diagnostics, || lsp_types::DocumentDiagnosticReportResult::Report( lsp_types::DocumentDiagnosticReport::Full( lsp_types::RelatedFullDocumentDiagnosticReport { related_documents: None, From bf77cf7f90428c612835ae4fd08991de07b52ac7 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 25 Oct 2024 07:39:28 +0200 Subject: [PATCH 240/366] Add server cancellation support to pull diagnostic handler --- .../rust-analyzer/src/handlers/dispatch.rs | 49 ++++++++++++++----- .../crates/rust-analyzer/src/main_loop.rs | 10 +++- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs index c2cf41757248..03759b036b4a 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs @@ -5,7 +5,7 @@ use std::{ }; use ide::Cancelled; -use lsp_server::ExtractError; +use lsp_server::{ExtractError, Response, ResponseError}; use serde::{de::DeserializeOwned, Serialize}; use stdx::thread::ThreadIntent; @@ -117,15 +117,20 @@ impl RequestDispatcher<'_> { } return self; } - self.on_with_thread_intent::(ThreadIntent::Worker, f) + self.on_with_thread_intent::( + ThreadIntent::Worker, + f, + Self::content_modified_error, + ) } /// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not /// ready this will return a `default` constructed [`R::Result`]. - pub(crate) fn on_with( + pub(crate) fn on_with( &mut self, f: fn(GlobalStateSnapshot, R::Params) -> anyhow::Result, default: impl FnOnce() -> R::Result, + on_cancelled: fn() -> ResponseError, ) -> &mut Self where R: lsp_types::request::Request< @@ -141,7 +146,7 @@ impl RequestDispatcher<'_> { } return self; } - self.on_with_thread_intent::(ThreadIntent::Worker, f) + self.on_with_thread_intent::(ThreadIntent::Worker, f, on_cancelled) } /// Dispatches a non-latency-sensitive request onto the thread pool. When the VFS is marked not @@ -160,7 +165,11 @@ impl RequestDispatcher<'_> { } return self; } - self.on_with_thread_intent::(ThreadIntent::Worker, f) + self.on_with_thread_intent::( + ThreadIntent::Worker, + f, + Self::content_modified_error, + ) } /// Dispatches a latency-sensitive request onto the thread pool. When the VFS is marked not @@ -183,7 +192,11 @@ impl RequestDispatcher<'_> { } return self; } - self.on_with_thread_intent::(ThreadIntent::LatencySensitive, f) + self.on_with_thread_intent::( + ThreadIntent::LatencySensitive, + f, + Self::content_modified_error, + ) } /// Formatting requests should never block on waiting a for task thread to open up, editors will wait @@ -198,7 +211,11 @@ impl RequestDispatcher<'_> { R::Params: DeserializeOwned + panic::UnwindSafe + Send + fmt::Debug, R::Result: Serialize, { - self.on_with_thread_intent::(ThreadIntent::LatencySensitive, f) + self.on_with_thread_intent::( + ThreadIntent::LatencySensitive, + f, + Self::content_modified_error, + ) } pub(crate) fn finish(&mut self) { @@ -217,6 +234,7 @@ impl RequestDispatcher<'_> { &mut self, intent: ThreadIntent, f: fn(GlobalStateSnapshot, R::Params) -> anyhow::Result, + on_cancelled: fn() -> ResponseError, ) -> &mut Self where R: lsp_types::request::Request + 'static, @@ -245,11 +263,10 @@ impl RequestDispatcher<'_> { match thread_result_to_response::(req.id.clone(), result) { Ok(response) => Task::Response(response), Err(_cancelled) if ALLOW_RETRYING => Task::Retry(req), - Err(_cancelled) => Task::Response(lsp_server::Response::new_err( - req.id, - lsp_server::ErrorCode::ContentModified as i32, - "content modified".to_owned(), - )), + Err(_cancelled) => { + let error = on_cancelled(); + Task::Response(Response { id: req.id, result: None, error: Some(error) }) + } } }); @@ -280,6 +297,14 @@ impl RequestDispatcher<'_> { } } } + + fn content_modified_error() -> ResponseError { + ResponseError { + code: lsp_server::ErrorCode::ContentModified as i32, + message: "content modified".to_owned(), + data: None, + } + } } fn thread_result_to_response( diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index 9ade3be5d688..9a51df80fe1f 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -1092,7 +1092,7 @@ impl GlobalState { .on_latency_sensitive::(handlers::handle_semantic_tokens_range) // FIXME: Some of these NO_RETRY could be retries if the file they are interested didn't change. // All other request handlers - .on_with::(handlers::handle_document_diagnostics, || lsp_types::DocumentDiagnosticReportResult::Report( + .on_with::(handlers::handle_document_diagnostics, || lsp_types::DocumentDiagnosticReportResult::Report( lsp_types::DocumentDiagnosticReport::Full( lsp_types::RelatedFullDocumentDiagnosticReport { related_documents: None, @@ -1102,7 +1102,13 @@ impl GlobalState { }, }, ), - )) + ), || lsp_server::ResponseError { + code: lsp_server::ErrorCode::ServerCancelled as i32, + message: "server cancelled the request".to_owned(), + data: serde_json::to_value(lsp_types::DiagnosticServerCancellationData { + retrigger_request: true + }).ok(), + }) .on::(handlers::handle_document_symbol) .on::(handlers::handle_folding_range) .on::(handlers::handle_signature_help) From 5af56cac38fa48e4228e5e123d060e85eb1acbf7 Mon Sep 17 00:00:00 2001 From: Luca Versari Date: Sat, 13 Jul 2024 19:35:05 +0200 Subject: [PATCH 241/366] Emit error when calling/declaring functions with unavailable vectors. On some architectures, vector types may have a different ABI when relevant target features are enabled. As discussed in https://github.com/rust-lang/lang-team/issues/235, this turns out to very easily lead to unsound code. This commit makes it an error to declare or call functions using those vector types in a context in which the corresponding target features are disabled, if using an ABI for which the difference is relevant. --- compiler/rustc_lint_defs/src/builtin.rs | 67 +++++++++++ compiler/rustc_monomorphize/messages.ftl | 9 ++ compiler/rustc_monomorphize/src/collector.rs | 5 + .../src/collector/abi_check.rs | 111 ++++++++++++++++++ compiler/rustc_monomorphize/src/errors.rs | 18 +++ compiler/rustc_target/src/target_features.rs | 17 +++ tests/crashes/131342-2.rs | 40 ------- tests/crashes/131342.rs | 1 - tests/ui/layout/post-mono-layout-cycle-2.rs | 1 - .../ui/layout/post-mono-layout-cycle-2.stderr | 10 +- tests/ui/layout/post-mono-layout-cycle.rs | 1 - tests/ui/layout/post-mono-layout-cycle.stderr | 10 +- tests/ui/simd-abi-checks.rs | 81 +++++++++++++ tests/ui/simd-abi-checks.stderr | 93 +++++++++++++++ tests/ui/sse-abi-checks.rs | 24 ++++ tests/ui/sse-abi-checks.stderr | 13 ++ 16 files changed, 448 insertions(+), 53 deletions(-) create mode 100644 compiler/rustc_monomorphize/src/collector/abi_check.rs delete mode 100644 tests/crashes/131342-2.rs create mode 100644 tests/ui/simd-abi-checks.rs create mode 100644 tests/ui/simd-abi-checks.stderr create mode 100644 tests/ui/sse-abi-checks.rs create mode 100644 tests/ui/sse-abi-checks.stderr diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 45a5ce0ca20e..2dd4a3f02690 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -16,6 +16,7 @@ declare_lint_pass! { /// that are used by other parts of the compiler. HardwiredLints => [ // tidy-alphabetical-start + ABI_UNSUPPORTED_VECTOR_TYPES, ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_ASSOCIATED_ITEMS, AMBIGUOUS_GLOB_IMPORTS, @@ -5078,3 +5079,69 @@ declare_lint! { }; crate_level_only } + +declare_lint! { + /// The `abi_unsupported_vector_types` lint detects function definitions and calls + /// whose ABI depends on enabling certain target features, but those features are not enabled. + /// + /// ### Example + /// + /// ```rust,ignore (fails on non-x86_64) + /// extern "C" fn missing_target_feature(_: std::arch::x86_64::__m256) { + /// todo!() + /// } + /// + /// #[target_feature(enable = "avx")] + /// unsafe extern "C" fn with_target_feature(_: std::arch::x86_64::__m256) { + /// todo!() + /// } + /// + /// fn main() { + /// let v = unsafe { std::mem::zeroed() }; + /// unsafe { with_target_feature(v); } + /// } + /// ``` + /// + /// ```text + /// warning: ABI error: this function call uses a avx vector type, which is not enabled in the caller + /// --> lint_example.rs:18:12 + /// | + /// | unsafe { with_target_feature(v); } + /// | ^^^^^^^^^^^^^^^^^^^^^^ function called here + /// | + /// = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + /// = note: for more information, see issue #116558 + /// = help: consider enabling it globally (-C target-feature=+avx) or locally (#[target_feature(enable="avx")]) + /// = note: `#[warn(abi_unsupported_vector_types)]` on by default + /// + /// + /// warning: ABI error: this function definition uses a avx vector type, which is not enabled + /// --> lint_example.rs:3:1 + /// | + /// | pub extern "C" fn with_target_feature(_: std::arch::x86_64::__m256) { + /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here + /// | + /// = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + /// = note: for more information, see issue #116558 + /// = help: consider enabling it globally (-C target-feature=+avx) or locally (#[target_feature(enable="avx")]) + /// ``` + /// + /// + /// + /// ### Explanation + /// + /// The C ABI for `__m256` requires the value to be passed in an AVX register, + /// which is only possible when the `avx` target feature is enabled. + /// Therefore, `missing_target_feature` cannot be compiled without that target feature. + /// A similar (but complementary) message is triggered when `with_target_feature` is called + /// by a function that does not enable the `avx` target feature. + /// + /// Note that this lint is very similar to the `-Wpsabi` warning in `gcc`/`clang`. + pub ABI_UNSUPPORTED_VECTOR_TYPES, + Warn, + "this function call or definition uses a vector type which is not enabled", + @future_incompatible = FutureIncompatibleInfo { + reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps, + reference: "issue #116558 ", + }; +} diff --git a/compiler/rustc_monomorphize/messages.ftl b/compiler/rustc_monomorphize/messages.ftl index 7210701d4828..6da387bbebcc 100644 --- a/compiler/rustc_monomorphize/messages.ftl +++ b/compiler/rustc_monomorphize/messages.ftl @@ -1,3 +1,12 @@ +monomorphize_abi_error_disabled_vector_type_call = + ABI error: this function call uses a vector type that requires the `{$required_feature}` target feature, which is not enabled in the caller + .label = function called here + .help = consider enabling it globally (`-C target-feature=+{$required_feature}`) or locally (`#[target_feature(enable="{$required_feature}")]`) +monomorphize_abi_error_disabled_vector_type_def = + ABI error: this function definition uses a vector type that requires the `{$required_feature}` target feature, which is not enabled + .label = function defined here + .help = consider enabling it globally (`-C target-feature=+{$required_feature}`) or locally (`#[target_feature(enable="{$required_feature}")]`) + monomorphize_couldnt_dump_mono_stats = unexpected error occurred while dumping monomorphization stats: {$error} diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index b4d084d4dffc..82de64cbce04 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -205,6 +205,7 @@ //! this is not implemented however: a mono item will be produced //! regardless of whether it is actually needed or not. +mod abi_check; mod move_check; use std::path::PathBuf; @@ -766,6 +767,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty)); let callee_ty = self.monomorphize(callee_ty); self.check_fn_args_move_size(callee_ty, args, *fn_span, location); + abi_check::check_call_site_abi(tcx, callee_ty, *fn_span, self.body.source.instance); visit_fn_use(self.tcx, callee_ty, true, source, &mut self.used_items) } mir::TerminatorKind::Drop { ref place, .. } => { @@ -1207,6 +1209,9 @@ fn collect_items_of_instance<'tcx>( mentioned_items: &mut MonoItems<'tcx>, mode: CollectionMode, ) { + // Check the instance for feature-dependent ABI. + abi_check::check_instance_abi(tcx, instance); + let body = tcx.instance_mir(instance.def); // Naively, in "used" collection mode, all functions get added to *both* `used_items` and // `mentioned_items`. Mentioned items processing will then notice that they have already been diff --git a/compiler/rustc_monomorphize/src/collector/abi_check.rs b/compiler/rustc_monomorphize/src/collector/abi_check.rs new file mode 100644 index 000000000000..6b825019f202 --- /dev/null +++ b/compiler/rustc_monomorphize/src/collector/abi_check.rs @@ -0,0 +1,111 @@ +//! This module ensures that if a function's ABI requires a particular target feature, +//! that target feature is enabled both on the callee and all callers. +use rustc_hir::CRATE_HIR_ID; +use rustc_middle::ty::{self, Instance, InstanceKind, ParamEnv, Ty, TyCtxt}; +use rustc_session::lint::builtin::ABI_UNSUPPORTED_VECTOR_TYPES; +use rustc_span::def_id::DefId; +use rustc_span::{Span, Symbol}; +use rustc_target::abi::call::{FnAbi, PassMode}; +use rustc_target::abi::{Abi, RegKind}; + +use crate::errors::{AbiErrorDisabledVectorTypeCall, AbiErrorDisabledVectorTypeDef}; + +fn uses_vector_registers(mode: &PassMode, abi: &Abi) -> bool { + match mode { + PassMode::Ignore | PassMode::Indirect { .. } => false, + PassMode::Cast { pad_i32: _, cast } => { + cast.prefix.iter().any(|r| r.is_some_and(|x| x.kind == RegKind::Vector)) + || cast.rest.unit.kind == RegKind::Vector + } + PassMode::Direct(..) | PassMode::Pair(..) => matches!(abi, Abi::Vector { .. }), + } +} + +fn do_check_abi<'tcx>( + tcx: TyCtxt<'tcx>, + abi: &FnAbi<'tcx, Ty<'tcx>>, + target_feature_def: DefId, + emit_err: impl Fn(&'static str), +) { + let Some(feature_def) = tcx.sess.target.features_for_correct_vector_abi() else { + return; + }; + let codegen_attrs = tcx.codegen_fn_attrs(target_feature_def); + for arg_abi in abi.args.iter().chain(std::iter::once(&abi.ret)) { + let size = arg_abi.layout.size; + if uses_vector_registers(&arg_abi.mode, &arg_abi.layout.abi) { + // Find the first feature that provides at least this vector size. + let feature = match feature_def.iter().find(|(bits, _)| size.bits() <= *bits) { + Some((_, feature)) => feature, + None => { + emit_err(""); + continue; + } + }; + let feature_sym = Symbol::intern(feature); + if !tcx.sess.unstable_target_features.contains(&feature_sym) + && !codegen_attrs.target_features.iter().any(|x| x.name == feature_sym) + { + emit_err(feature); + } + } + } +} + +/// Checks that the ABI of a given instance of a function does not contain vector-passed arguments +/// or return values for which the corresponding target feature is not enabled. +pub(super) fn check_instance_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) { + let param_env = ParamEnv::reveal_all(); + let Ok(abi) = tcx.fn_abi_of_instance(param_env.and((instance, ty::List::empty()))) else { + // An error will be reported during codegen if we cannot determine the ABI of this + // function. + return; + }; + do_check_abi(tcx, abi, instance.def_id(), |required_feature| { + let span = tcx.def_span(instance.def_id()); + tcx.emit_node_span_lint( + ABI_UNSUPPORTED_VECTOR_TYPES, + CRATE_HIR_ID, + span, + AbiErrorDisabledVectorTypeDef { span, required_feature }, + ); + }) +} + +/// Checks that a call expression does not try to pass a vector-passed argument which requires a +/// target feature that the caller does not have, as doing so causes UB because of ABI mismatch. +pub(super) fn check_call_site_abi<'tcx>( + tcx: TyCtxt<'tcx>, + ty: Ty<'tcx>, + span: Span, + caller: InstanceKind<'tcx>, +) { + let param_env = ParamEnv::reveal_all(); + let callee_abi = match *ty.kind() { + ty::FnPtr(..) => tcx.fn_abi_of_fn_ptr(param_env.and((ty.fn_sig(tcx), ty::List::empty()))), + ty::FnDef(def_id, args) => { + // Intrinsics are handled separately by the compiler. + if tcx.intrinsic(def_id).is_some() { + return; + } + let instance = ty::Instance::expect_resolve(tcx, param_env, def_id, args, span); + tcx.fn_abi_of_instance(param_env.and((instance, ty::List::empty()))) + } + _ => { + panic!("Invalid function call"); + } + }; + + let Ok(callee_abi) = callee_abi else { + // ABI failed to compute; this will not get through codegen. + return; + }; + do_check_abi(tcx, callee_abi, caller.def_id(), |required_feature| { + tcx.emit_node_span_lint( + ABI_UNSUPPORTED_VECTOR_TYPES, + CRATE_HIR_ID, + span, + AbiErrorDisabledVectorTypeCall { span, required_feature }, + ); + }) +} diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index d5fae6e23cb4..5048a8d5d993 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -92,3 +92,21 @@ pub(crate) struct StartNotFound; pub(crate) struct UnknownCguCollectionMode<'a> { pub mode: &'a str, } + +#[derive(LintDiagnostic)] +#[diag(monomorphize_abi_error_disabled_vector_type_def)] +#[help] +pub(crate) struct AbiErrorDisabledVectorTypeDef<'a> { + #[label] + pub span: Span, + pub required_feature: &'a str, +} + +#[derive(LintDiagnostic)] +#[diag(monomorphize_abi_error_disabled_vector_type_call)] +#[help] +pub(crate) struct AbiErrorDisabledVectorTypeCall<'a> { + #[label] + pub span: Span, + pub required_feature: &'a str, +} diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index e92366d5c5c3..0d16c9a96aa6 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -522,6 +522,13 @@ pub fn all_known_features() -> impl Iterator { .map(|(f, s, _)| (f, s)) } +// These arrays represent the least-constraining feature that is required for vector types up to a +// certain size to have their "proper" ABI on each architecture. +// Note that they must be kept sorted by vector size. +const X86_FEATURES_FOR_CORRECT_VECTOR_ABI: &'static [(u64, &'static str)] = + &[(128, "sse"), (256, "avx"), (512, "avx512f")]; +const AARCH64_FEATURES_FOR_CORRECT_VECTOR_ABI: &'static [(u64, &'static str)] = &[(128, "neon")]; + impl super::spec::Target { pub fn supported_target_features( &self, @@ -543,6 +550,16 @@ impl super::spec::Target { } } + // Returns None if we do not support ABI checks on the given target yet. + pub fn features_for_correct_vector_abi(&self) -> Option<&'static [(u64, &'static str)]> { + match &*self.arch { + "x86" | "x86_64" => Some(X86_FEATURES_FOR_CORRECT_VECTOR_ABI), + "aarch64" => Some(AARCH64_FEATURES_FOR_CORRECT_VECTOR_ABI), + // FIXME: add support for non-tier1 architectures + _ => None, + } + } + pub fn tied_target_features(&self) -> &'static [&'static [&'static str]] { match &*self.arch { "aarch64" | "arm64ec" => AARCH64_TIED_FEATURES, diff --git a/tests/crashes/131342-2.rs b/tests/crashes/131342-2.rs deleted file mode 100644 index 79b6a837a49f..000000000000 --- a/tests/crashes/131342-2.rs +++ /dev/null @@ -1,40 +0,0 @@ -//@ known-bug: #131342 -// see also: 131342.rs - -fn main() { - problem_thingy(Once); -} - -struct Once; - -impl Iterator for Once { - type Item = (); -} - -fn problem_thingy(items: impl Iterator) { - let peeker = items.peekable(); - problem_thingy(&peeker); -} - -trait Iterator { - type Item; - - fn peekable(self) -> Peekable - where - Self: Sized, - { - loop {} - } -} - -struct Peekable { - _peeked: I::Item, -} - -impl Iterator for Peekable { - type Item = I::Item; -} - -impl Iterator for &I { - type Item = I::Item; -} diff --git a/tests/crashes/131342.rs b/tests/crashes/131342.rs index 7f7ee9c9ac11..266aa0da97d1 100644 --- a/tests/crashes/131342.rs +++ b/tests/crashes/131342.rs @@ -1,5 +1,4 @@ //@ known-bug: #131342 -// see also: 131342-2.rs fn main() { let mut items = vec![1, 2, 3, 4, 5].into_iter(); diff --git a/tests/ui/layout/post-mono-layout-cycle-2.rs b/tests/ui/layout/post-mono-layout-cycle-2.rs index 356f1e777c7d..e9a5292fbbdf 100644 --- a/tests/ui/layout/post-mono-layout-cycle-2.rs +++ b/tests/ui/layout/post-mono-layout-cycle-2.rs @@ -45,7 +45,6 @@ where T: Blah, { async fn ice(&mut self) { - //~^ ERROR a cycle occurred during layout computation let arr: [(); 0] = []; self.t.iter(arr.into_iter()).await; } diff --git a/tests/ui/layout/post-mono-layout-cycle-2.stderr b/tests/ui/layout/post-mono-layout-cycle-2.stderr index ad01c2694faf..ea69b39706f4 100644 --- a/tests/ui/layout/post-mono-layout-cycle-2.stderr +++ b/tests/ui/layout/post-mono-layout-cycle-2.stderr @@ -12,12 +12,12 @@ LL | Blah::iter(self, iterator).await | = note: a recursive `async fn` call must introduce indirection such as `Box::pin` to avoid an infinitely sized future -error: a cycle occurred during layout computation - --> $DIR/post-mono-layout-cycle-2.rs:47:5 +note: the above error was encountered while instantiating `fn main::{closure#0}` + --> $DIR/post-mono-layout-cycle-2.rs:16:15 | -LL | async fn ice(&mut self) { - | ^^^^^^^^^^^^^^^^^^^^^^^ +LL | match fut.as_mut().poll(ctx) { + | ^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/layout/post-mono-layout-cycle.rs b/tests/ui/layout/post-mono-layout-cycle.rs index 8d136190c005..6753c01267ec 100644 --- a/tests/ui/layout/post-mono-layout-cycle.rs +++ b/tests/ui/layout/post-mono-layout-cycle.rs @@ -14,7 +14,6 @@ struct Wrapper { } fn abi(_: Option>) {} -//~^ ERROR a cycle occurred during layout computation fn indirect() { abi::(None); diff --git a/tests/ui/layout/post-mono-layout-cycle.stderr b/tests/ui/layout/post-mono-layout-cycle.stderr index 47f7f30b1cb4..e2f6ac595d00 100644 --- a/tests/ui/layout/post-mono-layout-cycle.stderr +++ b/tests/ui/layout/post-mono-layout-cycle.stderr @@ -5,12 +5,12 @@ error[E0391]: cycle detected when computing layout of `Wrapper<()>` = note: cycle used when computing layout of `core::option::Option>` = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information -error: a cycle occurred during layout computation - --> $DIR/post-mono-layout-cycle.rs:16:1 +note: the above error was encountered while instantiating `fn indirect::<()>` + --> $DIR/post-mono-layout-cycle.rs:23:5 | -LL | fn abi(_: Option>) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | indirect::<()>(); + | ^^^^^^^^^^^^^^^^ -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0391`. diff --git a/tests/ui/simd-abi-checks.rs b/tests/ui/simd-abi-checks.rs new file mode 100644 index 000000000000..094c89930b75 --- /dev/null +++ b/tests/ui/simd-abi-checks.rs @@ -0,0 +1,81 @@ +//@ only-x86_64 +//@ build-pass +//@ ignore-pass (test emits codegen-time warnings) + +#![feature(avx512_target_feature)] +#![feature(portable_simd)] +#![allow(improper_ctypes_definitions)] + +use std::arch::x86_64::*; + +#[repr(transparent)] +struct Wrapper(__m256); + +unsafe extern "C" fn w(_: Wrapper) { + //~^ ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled + //~| WARNING this was previously accepted by the compiler + todo!() +} + +unsafe extern "C" fn f(_: __m256) { + //~^ ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled + //~| WARNING this was previously accepted by the compiler + todo!() +} + +unsafe extern "C" fn g() -> __m256 { + //~^ ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled + //~| WARNING this was previously accepted by the compiler + todo!() +} + +#[target_feature(enable = "avx")] +unsafe extern "C" fn favx() -> __m256 { + todo!() +} + +// avx2 implies avx, so no error here. +#[target_feature(enable = "avx2")] +unsafe extern "C" fn gavx(_: __m256) { + todo!() +} + +// No error because of "Rust" ABI. +fn as_f64x8(d: __m512d) -> std::simd::f64x8 { + unsafe { std::mem::transmute(d) } +} + +unsafe fn test() { + let arg = std::mem::transmute([0.0f64; 8]); + as_f64x8(arg); +} + +fn main() { + unsafe { + f(g()); + //~^ WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + //~| WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + //~| WARNING this was previously accepted by the compiler + //~| WARNING this was previously accepted by the compiler + } + + unsafe { + gavx(favx()); + //~^ WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + //~| WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + //~| WARNING this was previously accepted by the compiler + //~| WARNING this was previously accepted by the compiler + } + + unsafe { + test(); + } + + unsafe { + w(Wrapper(g())); + //~^ WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + //~| WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + //~| WARNING this was previously accepted by the compiler + //~| WARNING this was previously accepted by the compiler + } +} diff --git a/tests/ui/simd-abi-checks.stderr b/tests/ui/simd-abi-checks.stderr new file mode 100644 index 000000000000..aa7e94001698 --- /dev/null +++ b/tests/ui/simd-abi-checks.stderr @@ -0,0 +1,93 @@ +warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + --> $DIR/simd-abi-checks.rs:55:11 + | +LL | f(g()); + | ^^^ function called here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + = note: `#[warn(abi_unsupported_vector_types)]` on by default + +warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + --> $DIR/simd-abi-checks.rs:55:9 + | +LL | f(g()); + | ^^^^^^ function called here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + --> $DIR/simd-abi-checks.rs:63:14 + | +LL | gavx(favx()); + | ^^^^^^ function called here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + --> $DIR/simd-abi-checks.rs:63:9 + | +LL | gavx(favx()); + | ^^^^^^^^^^^^ function called here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + --> $DIR/simd-abi-checks.rs:75:19 + | +LL | w(Wrapper(g())); + | ^^^ function called here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller + --> $DIR/simd-abi-checks.rs:75:9 + | +LL | w(Wrapper(g())); + | ^^^^^^^^^^^^^^^ function called here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled + --> $DIR/simd-abi-checks.rs:26:1 + | +LL | unsafe extern "C" fn g() -> __m256 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled + --> $DIR/simd-abi-checks.rs:20:1 + | +LL | unsafe extern "C" fn f(_: __m256) { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled + --> $DIR/simd-abi-checks.rs:14:1 + | +LL | unsafe extern "C" fn w(_: Wrapper) { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) + +warning: 9 warnings emitted + diff --git a/tests/ui/sse-abi-checks.rs b/tests/ui/sse-abi-checks.rs new file mode 100644 index 000000000000..d2afd38fcc85 --- /dev/null +++ b/tests/ui/sse-abi-checks.rs @@ -0,0 +1,24 @@ +//! Ensure we trigger abi_unsupported_vector_types for target features that are usually enabled +//! on a target, but disabled in this file via a `-C` flag. +//@ compile-flags: --crate-type=rlib --target=i686-unknown-linux-gnu -C target-feature=-sse,-sse2 +//@ build-pass +//@ ignore-pass (test emits codegen-time warnings) +//@ needs-llvm-components: x86 +#![feature(no_core, lang_items, repr_simd)] +#![no_core] +#![allow(improper_ctypes_definitions)] + +#[lang = "sized"] +trait Sized {} + +#[lang = "copy"] +trait Copy {} + +#[repr(simd)] +pub struct SseVector([i64; 2]); + +#[no_mangle] +pub unsafe extern "C" fn f(_: SseVector) { + //~^ ABI error: this function definition uses a vector type that requires the `sse` target feature, which is not enabled + //~| WARNING this was previously accepted by the compiler +} diff --git a/tests/ui/sse-abi-checks.stderr b/tests/ui/sse-abi-checks.stderr new file mode 100644 index 000000000000..77c4e1fc07ab --- /dev/null +++ b/tests/ui/sse-abi-checks.stderr @@ -0,0 +1,13 @@ +warning: ABI error: this function definition uses a vector type that requires the `sse` target feature, which is not enabled + --> $DIR/sse-abi-checks.rs:21:1 + | +LL | pub unsafe extern "C" fn f(_: SseVector) { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116558 + = help: consider enabling it globally (`-C target-feature=+sse`) or locally (`#[target_feature(enable="sse")]`) + = note: `#[warn(abi_unsupported_vector_types)]` on by default + +warning: 1 warning emitted + From 03d23a797d259567f306139124f01b38bac77a9b Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Sat, 14 Sep 2024 22:52:52 +0300 Subject: [PATCH 242/366] remove `change-id` from CI script Signed-off-by: onur-ozkan --- src/ci/run.sh | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/ci/run.sh b/src/ci/run.sh index 3962c354c10e..8e2f525db68f 100755 --- a/src/ci/run.sh +++ b/src/ci/run.sh @@ -47,11 +47,6 @@ source "$ci_dir/shared.sh" export CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse -# suppress change-tracker warnings on CI -if [ "$CI" != "" ]; then - RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --set change-id=99999999" -fi - # If runner uses an incompatible option and `FORCE_CI_RUSTC` is not defined, # switch to in-tree rustc. if [ "$FORCE_CI_RUSTC" == "" ]; then From c6d1f78fa39753f8966bb30a632a77b55d485d4e Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 23 Oct 2024 22:17:13 +0200 Subject: [PATCH 243/366] Only construct a resolver in macro descension when needed --- .../crates/hir-def/src/resolver.rs | 2 +- .../rust-analyzer/crates/hir/src/semantics.rs | 32 +++++++++++-------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs index 266851e3c0d5..d491042eabfc 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs @@ -1043,12 +1043,12 @@ impl HasResolver for ModuleId { fn resolver(self, db: &dyn DefDatabase) -> Resolver { let mut def_map = self.def_map(db); let mut module_id = self.local_id; - let mut modules: SmallVec<[_; 1]> = smallvec![]; if !self.is_block_module() { return Resolver { scopes: vec![], module_scope: ModuleItemMap { def_map, module_id } }; } + let mut modules: SmallVec<[_; 1]> = smallvec![]; while let Some(parent) = def_map.parent() { let block_def_map = mem::replace(&mut def_map, parent.def_map(db)); modules.push(block_def_map); diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index 860754d5e704..d9d50c447317 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -936,16 +936,7 @@ impl<'db> SemanticsImpl<'db> { } } - let (file_id, tokens) = stack.first()?; - // make sure we pick the token in the expanded include if we encountered an include, - // otherwise we'll get the wrong semantics - let sa = - tokens.first()?.0.parent().and_then(|parent| { - self.analyze_impl(InFile::new(*file_id, &parent), None, false) - })?; - let mut m_cache = self.macro_call_cache.borrow_mut(); - let def_map = sa.resolver.def_map(); // Filters out all tokens that contain the given range (usually the macro call), any such // token is redundant as the corresponding macro call has already been processed @@ -1024,8 +1015,16 @@ impl<'db> SemanticsImpl<'db> { ) { call.as_macro_file() } else { - // FIXME: This is wrong, the SourceAnalyzer might be invalid here - sa.expand(self.db, mcall.as_ref())? + token + .parent() + .and_then(|parent| { + self.analyze_impl( + InFile::new(expansion, &parent), + None, + false, + ) + })? + .expand(self.db, mcall.as_ref())? }; m_cache.insert(mcall, it); it @@ -1095,9 +1094,16 @@ impl<'db> SemanticsImpl<'db> { attr.path().and_then(|it| it.as_single_name_ref())?.as_name(); // Not an attribute, nor a derive, so it's either an intert attribute or a derive helper // Try to resolve to a derive helper and downmap + let resolver = &token + .parent() + .and_then(|parent| { + self.analyze_impl(InFile::new(expansion, &parent), None, false) + })? + .resolver; let id = self.db.ast_id_map(expansion).ast_id(&adt); - let helpers = - def_map.derive_helpers_in_scope(InFile::new(expansion, id))?; + let helpers = resolver + .def_map() + .derive_helpers_in_scope(InFile::new(expansion, id))?; if !helpers.is_empty() { let text_range = attr.syntax().text_range(); From 854e3c43e005c992542a80bea9bbe16230470362 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 25 Oct 2024 12:01:08 +0200 Subject: [PATCH 244/366] library: consistently use American spelling for 'behavior' --- .../alloc/src/collections/binary_heap/tests.rs | 4 ++-- library/alloc/src/collections/btree/map/tests.rs | 2 +- library/alloc/src/rc.rs | 2 +- library/alloc/src/sync.rs | 4 ++-- library/alloc/src/vec/is_zero.rs | 2 +- library/core/src/alloc/global.rs | 4 ++-- library/core/src/cell.rs | 2 +- library/core/src/cmp.rs | 2 +- library/core/src/intrinsics.rs | 4 ++-- library/core/src/intrinsics/mir.rs | 2 +- library/core/src/mem/maybe_uninit.rs | 2 +- library/core/src/num/nonzero.rs | 16 ++++++++-------- library/core/src/num/uint_macros.rs | 2 +- library/core/src/num/wrapping.rs | 2 +- library/core/src/ops/deref.rs | 6 +++--- library/core/src/option.rs | 2 +- library/core/src/primitive_docs.rs | 10 +++++----- library/core/src/ptr/mod.rs | 4 ++-- library/core/src/str/pattern.rs | 4 ++-- library/core/tests/num/int_macros.rs | 2 +- library/core/tests/num/uint_macros.rs | 2 +- library/proc_macro/src/bridge/symbol.rs | 2 +- library/std/src/collections/hash/map/tests.rs | 2 +- library/std/src/env.rs | 2 +- library/std/src/os/unix/fs.rs | 2 +- library/std/src/path.rs | 4 ++-- library/std/src/process.rs | 4 ++-- library/std/src/sync/mpmc/array.rs | 2 +- library/std/src/sync/once.rs | 2 +- .../src/sys/pal/unix/process/process_fuchsia.rs | 2 +- library/std/src/sys/pal/windows/fs.rs | 2 +- library/std/src/sys/pal/windows/process.rs | 8 ++++---- library/std/src/sys/pal/windows/process/tests.rs | 2 +- library/std/src/sys/pal/windows/thread.rs | 2 +- library/std/src/sys/path/windows/tests.rs | 2 +- library/std/src/sys/random/linux.rs | 4 ++-- library/std/src/sys/sync/condvar/pthread.rs | 2 +- library/std/src/sys/sync/mutex/pthread.rs | 4 ++-- library/std/src/sys/sync/once_box.rs | 2 +- library/std/src/sys/sync/rwlock/futex.rs | 2 +- library/std/src/sys/sync/rwlock/queue.rs | 2 +- .../std/src/sys/sync/thread_parking/darwin.rs | 2 +- .../std/src/sys/sync/thread_parking/pthread.rs | 2 +- .../std/src/sys/sync/thread_parking/windows7.rs | 4 ++-- library/std/src/thread/mod.rs | 4 ++-- library/std/src/time.rs | 4 ++-- 46 files changed, 75 insertions(+), 75 deletions(-) diff --git a/library/alloc/src/collections/binary_heap/tests.rs b/library/alloc/src/collections/binary_heap/tests.rs index c18318724a4e..ad0a020a1a96 100644 --- a/library/alloc/src/collections/binary_heap/tests.rs +++ b/library/alloc/src/collections/binary_heap/tests.rs @@ -350,7 +350,7 @@ fn test_drain_forget() { mem::forget(it); })) .unwrap(); - // Behaviour after leaking is explicitly unspecified and order is arbitrary, + // Behavior after leaking is explicitly unspecified and order is arbitrary, // so it's fine if these start failing, but probably worth knowing. assert!(q.is_empty()); assert_eq!(a.dropped() + b.dropped() + c.dropped(), 1); @@ -377,7 +377,7 @@ fn test_drain_sorted_forget() { mem::forget(it); })) .unwrap(); - // Behaviour after leaking is explicitly unspecified, + // Behavior after leaking is explicitly unspecified, // so it's fine if these start failing, but probably worth knowing. assert_eq!(q.len(), 2); assert_eq!(a.dropped(), 0); diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index d0e413778f87..db16d82be7dc 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -1216,7 +1216,7 @@ mod test_extract_if { { let mut it = map.extract_if(|dummy, _| dummy.query(true)); catch_unwind(AssertUnwindSafe(|| while it.next().is_some() {})).unwrap_err(); - // Iterator behaviour after a panic is explicitly unspecified, + // Iterator behavior after a panic is explicitly unspecified, // so this is just the current implementation: let result = catch_unwind(AssertUnwindSafe(|| it.next())); assert!(matches!(result, Ok(None))); diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 128503284cd8..9fdd51ce331f 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -3075,7 +3075,7 @@ impl Weak { /// /// drop(strong); /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to - /// // undefined behaviour. + /// // undefined behavior. /// // assert_eq!("hello", unsafe { &*weak.as_ptr() }); /// ``` /// diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 220b79eaf8ae..15a1b0f28344 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -804,7 +804,7 @@ impl Arc { // observe a non-zero strong count. Therefore we need at least "Release" ordering // in order to synchronize with the `compare_exchange_weak` in `Weak::upgrade`. // - // "Acquire" ordering is not required. When considering the possible behaviours + // "Acquire" ordering is not required. When considering the possible behaviors // of `data_fn` we only need to look at what it could do with a reference to a // non-upgradeable `Weak`: // - It can *clone* the `Weak`, increasing the weak reference count. @@ -2788,7 +2788,7 @@ impl Weak { /// /// drop(strong); /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to - /// // undefined behaviour. + /// // undefined behavior. /// // assert_eq!("hello", unsafe { &*weak.as_ptr() }); /// ``` /// diff --git a/library/alloc/src/vec/is_zero.rs b/library/alloc/src/vec/is_zero.rs index bcc5bf4d65bb..ba57d940d8c9 100644 --- a/library/alloc/src/vec/is_zero.rs +++ b/library/alloc/src/vec/is_zero.rs @@ -172,7 +172,7 @@ macro_rules! impl_is_zero_option_of_bool { fn is_zero(&self) -> bool { // SAFETY: This is *not* a stable layout guarantee, but // inside `core` we're allowed to rely on the current rustc - // behaviour that options of bools will be one byte with + // behavior that options of bools will be one byte with // no padding, so long as they're nested less than 254 deep. let raw: u8 = unsafe { core::mem::transmute(*self) }; raw == 0 diff --git a/library/core/src/alloc/global.rs b/library/core/src/alloc/global.rs index 68f00d07529b..8f48af24557d 100644 --- a/library/core/src/alloc/global.rs +++ b/library/core/src/alloc/global.rs @@ -173,7 +173,7 @@ pub unsafe trait GlobalAlloc { /// # Safety /// /// The caller has to ensure that `layout` has non-zero size. Like `alloc` - /// zero sized `layout` can result in undefined behaviour. + /// zero sized `layout` can result in undefined behavior. /// However the allocated block of memory is guaranteed to be initialized. /// /// # Errors @@ -234,7 +234,7 @@ pub unsafe trait GlobalAlloc { /// does not overflow `isize` (i.e., the rounded value must be less than or /// equal to `isize::MAX`). /// - /// If these are not followed, undefined behaviour can result. + /// If these are not followed, undefined behavior can result. /// /// (Extension subtraits might provide more specific bounds on /// behavior, e.g., guarantee a sentinel address or a null pointer diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index e1fa43296d02..1b63e2614cc2 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1221,7 +1221,7 @@ impl RefCell { /// Unlike `RefCell::borrow`, this method is unsafe because it does not /// return a `Ref`, thus leaving the borrow flag untouched. Mutably /// borrowing the `RefCell` while the reference returned by this method - /// is alive is undefined behaviour. + /// is alive is undefined behavior. /// /// # Examples /// diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 4377b4993b8f..5a3b9365cd22 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -380,7 +380,7 @@ pub struct AssertParamIsEq { #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] #[stable(feature = "rust1", since = "1.0.0")] // This is a lang item only so that `BinOp::Cmp` in MIR can return it. -// It has no special behaviour, but does require that the three variants +// It has no special behavior, but does require that the three variants // `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8` respectively. #[lang = "Ordering"] #[repr(i8)] diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 97e727633c5f..fa0706302d03 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -930,7 +930,7 @@ extern "rust-intrinsic" { /// on most platforms. /// On Unix, the /// process will probably terminate with a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or - /// `SIGBUS`. The precise behaviour is not guaranteed and not stable. + /// `SIGBUS`. The precise behavior is not guaranteed and not stable. #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn abort() -> !; @@ -1384,7 +1384,7 @@ extern "rust-intrinsic" { /// Like [`transmute`], but even less checked at compile-time: rather than /// giving an error for `size_of::() != size_of::()`, it's - /// **Undefined Behaviour** at runtime. + /// **Undefined Behavior** at runtime. /// /// Prefer normal `transmute` where possible, for the extra checking, since /// both do exactly the same thing at runtime, if they both compile. diff --git a/library/core/src/intrinsics/mir.rs b/library/core/src/intrinsics/mir.rs index a2ab39caade5..6539964bc095 100644 --- a/library/core/src/intrinsics/mir.rs +++ b/library/core/src/intrinsics/mir.rs @@ -298,7 +298,7 @@ define!( ); define!( "mir_unwind_unreachable", - /// An unwind action that triggers undefined behaviour. + /// An unwind action that triggers undefined behavior. fn UnwindUnreachable() -> UnwindActionArg ); define!( diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index ea73cfc37810..b4252ef0103f 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -723,7 +723,7 @@ impl MaybeUninit { /// this does not constitute a stable guarantee), because the only /// requirement the compiler knows about it is that the data pointer must be /// non-null. Dropping such a `Vec` however will cause undefined - /// behaviour. + /// behavior. /// /// [`assume_init`]: MaybeUninit::assume_init /// [`Vec`]: ../../std/vec/struct.Vec.html diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index e5c9a7e086ac..fdb84827e273 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -355,7 +355,7 @@ where } /// Creates a non-zero without checking whether the value is non-zero. - /// This results in undefined behaviour if the value is zero. + /// This results in undefined behavior if the value is zero. /// /// # Safety /// @@ -952,9 +952,9 @@ macro_rules! nonzero_integer { /// Multiplies two non-zero integers together, /// assuming overflow cannot occur. - /// Overflow is unchecked, and it is undefined behaviour to overflow + /// Overflow is unchecked, and it is undefined behavior to overflow /// *even if the result would wrap to a non-zero value*. - /// The behaviour is undefined as soon as + /// The behavior is undefined as soon as #[doc = sign_dependent_expr!{ $signedness ? if signed { @@ -1323,9 +1323,9 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// Adds an unsigned integer to a non-zero value, /// assuming overflow cannot occur. - /// Overflow is unchecked, and it is undefined behaviour to overflow + /// Overflow is unchecked, and it is undefined behavior to overflow /// *even if the result would wrap to a non-zero value*. - /// The behaviour is undefined as soon as + /// The behavior is undefined as soon as #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")] /// /// # Examples @@ -1599,7 +1599,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// Computes the absolute value of self. #[doc = concat!("See [`", stringify!($Int), "::abs`]")] - /// for documentation on overflow behaviour. + /// for documentation on overflow behavior. /// /// # Example /// @@ -1878,7 +1878,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// Negates self, overflowing if this is equal to the minimum value. /// #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")] - /// for documentation on overflow behaviour. + /// for documentation on overflow behavior. /// /// # Example /// @@ -1943,7 +1943,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// of the type. /// #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")] - /// for documentation on overflow behaviour. + /// for documentation on overflow behavior. /// /// # Example /// diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index d9036abecc59..0a46ff0ae6b9 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -3086,7 +3086,7 @@ macro_rules! uint_impl { /// ``` #[inline] #[unstable(feature = "wrapping_next_power_of_two", issue = "32463", - reason = "needs decision on wrapping behaviour")] + reason = "needs decision on wrapping behavior")] #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")] #[must_use = "this returns the result of the operation, \ without modifying the original"] diff --git a/library/core/src/num/wrapping.rs b/library/core/src/num/wrapping.rs index 1ac6d3161c2f..1156b389e286 100644 --- a/library/core/src/num/wrapping.rs +++ b/library/core/src/num/wrapping.rs @@ -1043,7 +1043,7 @@ macro_rules! wrapping_int_impl_unsigned { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[unstable(feature = "wrapping_next_power_of_two", issue = "32463", - reason = "needs decision on wrapping behaviour")] + reason = "needs decision on wrapping behavior")] pub fn next_power_of_two(self) -> Self { Wrapping(self.0.wrapping_next_power_of_two()) } diff --git a/library/core/src/ops/deref.rs b/library/core/src/ops/deref.rs index 49b380e45749..1ef9990c00af 100644 --- a/library/core/src/ops/deref.rs +++ b/library/core/src/ops/deref.rs @@ -15,7 +15,7 @@ /// /// Types that implement `Deref` or `DerefMut` are often called "smart /// pointers" and the mechanism of deref coercion has been specifically designed -/// to facilitate the pointer-like behaviour that name suggests. Often, the +/// to facilitate the pointer-like behavior that name suggests. Often, the /// purpose of a "smart pointer" type is to change the ownership semantics /// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the /// storage semantics of a contained value (for example, [`Box`][box]). @@ -42,7 +42,7 @@ /// 1. a value of the type transparently behaves like a value of the target /// type; /// 1. the implementation of the deref function is cheap; and -/// 1. users of the type will not be surprised by any deref coercion behaviour. +/// 1. users of the type will not be surprised by any deref coercion behavior. /// /// In general, deref traits **should not** be implemented if: /// @@ -185,7 +185,7 @@ impl Deref for &mut T { /// /// Types that implement `DerefMut` or `Deref` are often called "smart /// pointers" and the mechanism of deref coercion has been specifically designed -/// to facilitate the pointer-like behaviour that name suggests. Often, the +/// to facilitate the pointer-like behavior that name suggests. Often, the /// purpose of a "smart pointer" type is to change the ownership semantics /// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the /// storage semantics of a contained value (for example, [`Box`][box]). diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 0b996c40c04c..2aa4f1723680 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -150,7 +150,7 @@ //! It is further guaranteed that, for the cases above, one can //! [`mem::transmute`] from all valid values of `T` to `Option` and //! from `Some::(_)` to `T` (but transmuting `None::` to `T` -//! is undefined behaviour). +//! is undefined behavior). //! //! # Method overview //! diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 95fa6c9c9507..bf9bfd84b565 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -100,7 +100,7 @@ mod prim_bool {} /// /// Both match arms must produce values of type [`u32`], but since `break` never produces a value /// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another -/// behaviour of the `!` type - expressions with type `!` will coerce into any other type. +/// behavior of the `!` type - expressions with type `!` will coerce into any other type. /// /// [`u32`]: prim@u32 /// [`exit`]: ../std/process/fn.exit.html @@ -134,7 +134,7 @@ mod prim_bool {} /// /// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns` /// feature is present this means we can exhaustively match on [`Result`] by just taking the -/// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain +/// [`Ok`] variant. This illustrates another behavior of `!` - it can be used to "delete" certain /// enum variants from generic types like `Result`. /// /// ## Infinite loops @@ -351,7 +351,7 @@ mod prim_never {} /// ``` /// /// ```no_run -/// // Undefined behaviour +/// // Undefined behavior /// let _ = unsafe { char::from_u32_unchecked(0x110000) }; /// ``` /// @@ -568,7 +568,7 @@ impl () {} /// Instead of coercing a reference to a raw pointer, you can use the macros /// [`ptr::addr_of!`] (for `*const T`) and [`ptr::addr_of_mut!`] (for `*mut T`). /// These macros allow you to create raw pointers to fields to which you cannot -/// create a reference (without causing undefined behaviour), such as an +/// create a reference (without causing undefined behavior), such as an /// unaligned field. This might be necessary if packed structs or uninitialized /// memory is involved. /// @@ -1453,7 +1453,7 @@ mod prim_usize {} /// &[bool] can only point to an allocation containing the integer values `1` /// ([`true`](../std/keyword.true.html)) or `0` ([`false`](../std/keyword.false.html)), but /// creating a &[bool] that points to an allocation containing -/// the value `3` causes undefined behaviour. +/// the value `3` causes undefined behavior. /// In fact, [Option]\<&T> has the same memory representation as a /// nullable but aligned pointer, and can be passed across FFI boundaries as such. /// diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index ea185f0fbe58..2237dc08bd23 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -134,7 +134,7 @@ //! # Provenance //! //! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial -//! to say that a Use After Free is clearly Undefined Behaviour, even if you "get lucky" +//! to say that a Use After Free is clearly Undefined Behavior, even if you "get lucky" //! and the freed memory gets reallocated before your read/write (in fact this is the //! worst-case scenario, UAFs would be much less concerning if this didn't happen!). //! As another example, consider that [`wrapping_offset`] is documented to "remember" @@ -1125,7 +1125,7 @@ pub const unsafe fn swap_nonoverlapping(x: *mut T, y: *mut T, count: usize) { unsafe { swap_nonoverlapping_simple_untyped(x, y, count) } } -/// Same behaviour and safety conditions as [`swap_nonoverlapping`] +/// Same behavior and safety conditions as [`swap_nonoverlapping`] /// /// LLVM can vectorize this (at least it can for the power-of-two-sized types /// `swap_nonoverlapping` tries to use) so no need to manually SIMD it. diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index f68465c9bdac..665c9fc67d01 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -57,9 +57,9 @@ use crate::{cmp, fmt}; /// [`Searcher`] type, which does the actual work of finding /// occurrences of the pattern in a string. /// -/// Depending on the type of the pattern, the behaviour of methods like +/// Depending on the type of the pattern, the behavior of methods like /// [`str::find`] and [`str::contains`] can change. The table below describes -/// some of those behaviours. +/// some of those behaviors. /// /// | Pattern type | Match condition | /// |--------------------------|-------------------------------------------| diff --git a/library/core/tests/num/int_macros.rs b/library/core/tests/num/int_macros.rs index 7d3381ee5044..1608080d6b60 100644 --- a/library/core/tests/num/int_macros.rs +++ b/library/core/tests/num/int_macros.rs @@ -113,7 +113,7 @@ macro_rules! int_module { // Rotating these should make no difference // // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. + // not cause undefined behavior. See #10183. assert_eq_const_safe!(_0.rotate_left(124), _0); assert_eq_const_safe!(_1.rotate_left(124), _1); assert_eq_const_safe!(_0.rotate_right(124), _0); diff --git a/library/core/tests/num/uint_macros.rs b/library/core/tests/num/uint_macros.rs index 105aad4522d7..ad8e48491e82 100644 --- a/library/core/tests/num/uint_macros.rs +++ b/library/core/tests/num/uint_macros.rs @@ -79,7 +79,7 @@ macro_rules! uint_module { // Rotating these should make no difference // // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. + // not cause undefined behavior. See #10183. assert_eq_const_safe!(_0.rotate_left(124), _0); assert_eq_const_safe!(_1.rotate_left(124), _1); assert_eq_const_safe!(_0.rotate_right(124), _0); diff --git a/library/proc_macro/src/bridge/symbol.rs b/library/proc_macro/src/bridge/symbol.rs index 37aaee6b2155..edad6e7ac393 100644 --- a/library/proc_macro/src/bridge/symbol.rs +++ b/library/proc_macro/src/bridge/symbol.rs @@ -76,7 +76,7 @@ impl Symbol { .all(|b| matches!(b, b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9')) } - // Mimics the behaviour of `Symbol::can_be_raw` from `rustc_span` + // Mimics the behavior of `Symbol::can_be_raw` from `rustc_span` fn can_be_raw(string: &str) -> bool { match string { "_" | "super" | "self" | "Self" | "crate" => false, diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index fa8ea95b8914..b79ad1c3119f 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -1098,7 +1098,7 @@ mod test_extract_if { _ => panic!(), }); catch_unwind(AssertUnwindSafe(|| while it.next().is_some() {})).unwrap_err(); - // Iterator behaviour after a panic is explicitly unspecified, + // Iterator behavior after a panic is explicitly unspecified, // so this is just the current implementation: let result = catch_unwind(AssertUnwindSafe(|| it.next())); assert!(result.is_err()); diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 97a1b846a91a..d732a15117e9 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -618,7 +618,7 @@ impl Error for JoinPathsError { /// /// # Deprecation /// -/// This function is deprecated because the behaviour on Windows is not correct. +/// This function is deprecated because the behavior on Windows is not correct. /// The 'HOME' environment variable is not standard on Windows, and may not produce /// desired results; for instance, under Cygwin or Mingw it will return `/home/you` /// when it should return `C:\Users\you`. diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index a964db2e0ac3..ba6481f052cd 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -153,7 +153,7 @@ pub trait FileExt { /// /// It is possible to inadvertently set this flag, like in the example below. /// Therefore, it is important to be vigilant while changing options to mitigate - /// unexpected behaviour. + /// unexpected behavior. /// /// ```no_run /// use std::fs::File; diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 63edfdb82f36..62125f885b2f 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -1167,7 +1167,7 @@ impl FusedIterator for Ancestors<'_> {} /// path.push(r"..\otherdir"); /// path.push("system32"); /// -/// The behaviour of `PathBuf` may be changed to a panic on such inputs +/// The behavior of `PathBuf` may be changed to a panic on such inputs /// in the future. [`Extend::extend`] should be used to add multi-part paths. #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")] #[stable(feature = "rust1", since = "1.0.0")] @@ -1409,7 +1409,7 @@ impl PathBuf { /// (That is, it will have the same parent.) /// /// The argument is not sanitized, so can include separators. This - /// behaviour may be changed to a panic in the future. + /// behavior may be changed to a panic in the future. /// /// [`self.file_name`]: Path::file_name /// [`pop`]: PathBuf::pop diff --git a/library/std/src/process.rs b/library/std/src/process.rs index f24fe353e55b..6933528cdbd0 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -119,7 +119,7 @@ //! when given a `.bat` file as the application to run, it will automatically //! convert that into running `cmd.exe /c` with the batch file as the next argument. //! -//! For historical reasons Rust currently preserves this behaviour when using +//! For historical reasons Rust currently preserves this behavior when using //! [`Command::new`], and escapes the arguments according to `cmd.exe` rules. //! Due to the complexity of `cmd.exe` argument handling, it might not be //! possible to safely escape some special characters, and using them will result @@ -2318,7 +2318,7 @@ pub fn exit(code: i32) -> ! { /// Rust IO buffers (eg, from `BufWriter`) will not be flushed. /// Likewise, C stdio buffers will (on most platforms) not be flushed. /// -/// This is in contrast to the default behaviour of [`panic!`] which unwinds +/// This is in contrast to the default behavior of [`panic!`] which unwinds /// the current thread's stack and calls all destructors. /// When `panic="abort"` is set, either as an argument to `rustc` or in a /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However, diff --git a/library/std/src/sync/mpmc/array.rs b/library/std/src/sync/mpmc/array.rs index 34acd9c9a943..2c8ba411f302 100644 --- a/library/std/src/sync/mpmc/array.rs +++ b/library/std/src/sync/mpmc/array.rs @@ -484,7 +484,7 @@ impl Channel { /// /// # Panicking /// If a destructor panics, the remaining messages are leaked, matching the - /// behaviour of the unbounded channel. + /// behavior of the unbounded channel. /// /// # Safety /// This method must only be called when dropping the last receiver. The diff --git a/library/std/src/sync/once.rs b/library/std/src/sync/once.rs index 993df9314fce..27db4b634fb2 100644 --- a/library/std/src/sync/once.rs +++ b/library/std/src/sync/once.rs @@ -288,7 +288,7 @@ impl Once { /// /// If this [`Once`] has been poisoned because an initialization closure has /// panicked, this method will also panic. Use [`wait_force`](Self::wait_force) - /// if this behaviour is not desired. + /// if this behavior is not desired. #[unstable(feature = "once_wait", issue = "127527")] pub fn wait(&self) { if !self.inner.is_completed() { diff --git a/library/std/src/sys/pal/unix/process/process_fuchsia.rs b/library/std/src/sys/pal/unix/process/process_fuchsia.rs index 5d0110cf55dc..8f7d786e32fc 100644 --- a/library/std/src/sys/pal/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/pal/unix/process/process_fuchsia.rs @@ -273,7 +273,7 @@ impl ExitStatus { // We don't know what someone who calls into_raw() will do with this value, but it should // have the conventional Unix representation. Despite the fact that this is not // standardised in SuS or POSIX, all Unix systems encode the signal and exit status the - // same way. (Ie the WIFEXITED, WEXITSTATUS etc. macros have identical behaviour on every + // same way. (Ie the WIFEXITED, WEXITSTATUS etc. macros have identical behavior on every // Unix.) // // The caller of `std::os::unix::into_raw` is probably wanting a Unix exit status, and may diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index b237fa481e28..5a9bfccc1fab 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1159,7 +1159,7 @@ pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be - // added to dwFlags to opt into this behaviour. + // added to dwFlags to opt into this behavior. let result = cvt(unsafe { c::CreateSymbolicLinkW( link.as_ptr(), diff --git a/library/std/src/sys/pal/windows/process.rs b/library/std/src/sys/pal/windows/process.rs index 95b51e704f9d..17bb03fe7af0 100644 --- a/library/std/src/sys/pal/windows/process.rs +++ b/library/std/src/sys/pal/windows/process.rs @@ -47,7 +47,7 @@ impl EnvKey { } } -// Comparing Windows environment variable keys[1] are behaviourally the +// Comparing Windows environment variable keys[1] are behaviorally the // composition of two operations[2]: // // 1. Case-fold both strings. This is done using a language-independent @@ -338,8 +338,8 @@ impl Command { // If at least one of stdin, stdout or stderr are set (i.e. are non null) // then set the `hStd` fields in `STARTUPINFO`. - // Otherwise skip this and allow the OS to apply its default behaviour. - // This provides more consistent behaviour between Win7 and Win8+. + // Otherwise skip this and allow the OS to apply its default behavior. + // This provides more consistent behavior between Win7 and Win8+. let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null(); if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) { si.dwFlags |= c::STARTF_USESTDHANDLES; @@ -507,7 +507,7 @@ where Exists: FnMut(PathBuf) -> Option>, { // 1. Child paths - // This is for consistency with Rust's historic behaviour. + // This is for consistency with Rust's historic behavior. if let Some(paths) = child_paths { for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) { if let Some(path) = exists(path) { diff --git a/library/std/src/sys/pal/windows/process/tests.rs b/library/std/src/sys/pal/windows/process/tests.rs index b567151b7214..1bcc5fa6b204 100644 --- a/library/std/src/sys/pal/windows/process/tests.rs +++ b/library/std/src/sys/pal/windows/process/tests.rs @@ -191,7 +191,7 @@ fn windows_exe_resolver() { /* Some of the following tests may need to be changed if you are deliberately - changing the behaviour of `resolve_exe`. + changing the behavior of `resolve_exe`. */ let empty_paths = || None; diff --git a/library/std/src/sys/pal/windows/thread.rs b/library/std/src/sys/pal/windows/thread.rs index 28bce529cd99..2c8ce42f4148 100644 --- a/library/std/src/sys/pal/windows/thread.rs +++ b/library/std/src/sys/pal/windows/thread.rs @@ -99,7 +99,7 @@ impl Thread { } // Attempt to use high-precision sleep (Windows 10, version 1803+). // On error fallback to the standard `Sleep` function. - // Also preserves the zero duration behaviour of `Sleep`. + // Also preserves the zero duration behavior of `Sleep`. if dur.is_zero() || high_precision_sleep(dur).is_err() { unsafe { c::Sleep(super::dur2timeout(dur)) } } diff --git a/library/std/src/sys/path/windows/tests.rs b/library/std/src/sys/path/windows/tests.rs index 623c6236166d..f2a60e30bc61 100644 --- a/library/std/src/sys/path/windows/tests.rs +++ b/library/std/src/sys/path/windows/tests.rs @@ -119,7 +119,7 @@ fn test_windows_prefix_components() { /// See #101358. /// -/// Note that the exact behaviour here may change in the future. +/// Note that the exact behavior here may change in the future. /// In which case this test will need to adjusted. #[test] fn broken_unc_path() { diff --git a/library/std/src/sys/random/linux.rs b/library/std/src/sys/random/linux.rs index 073fdc45e611..e3cb79285cd1 100644 --- a/library/std/src/sys/random/linux.rs +++ b/library/std/src/sys/random/linux.rs @@ -30,7 +30,7 @@ //! data the system has available at the time. //! //! So in conclusion, we always want the output of the non-blocking pool, but -//! may need to wait until it is initalized. The default behaviour of `getrandom` +//! may need to wait until it is initalized. The default behavior of `getrandom` //! is to wait until the non-blocking pool is initialized and then draw from there, //! so if `getrandom` is available, we use its default to generate the bytes. For //! `HashMap`, however, we need to specify the `GRND_INSECURE` flags, but that @@ -39,7 +39,7 @@ //! succeed if the pool is initialized. If it isn't, we fall back to the file //! access method. //! -//! The behaviour of `/dev/urandom` is inverse to that of `getrandom`: it always +//! The behavior of `/dev/urandom` is inverse to that of `getrandom`: it always //! yields data, even when the pool is not initialized. For generating `HashMap` //! keys, this is not important, so we can use it directly. For secure data //! however, we need to wait until initialization, which we can do by `poll`ing diff --git a/library/std/src/sys/sync/condvar/pthread.rs b/library/std/src/sys/sync/condvar/pthread.rs index 986cd0cb7d18..cee728e35cdf 100644 --- a/library/std/src/sys/sync/condvar/pthread.rs +++ b/library/std/src/sys/sync/condvar/pthread.rs @@ -66,7 +66,7 @@ impl Drop for AllocatedCondvar { // On DragonFly pthread_cond_destroy() returns EINVAL if called on // a condvar that was just initialized with // libc::PTHREAD_COND_INITIALIZER. Once it is used or - // pthread_cond_init() is called, this behaviour no longer occurs. + // pthread_cond_init() is called, this behavior no longer occurs. debug_assert!(r == 0 || r == libc::EINVAL); } else { debug_assert_eq!(r, 0); diff --git a/library/std/src/sys/sync/mutex/pthread.rs b/library/std/src/sys/sync/mutex/pthread.rs index 87c95f45f964..abd58122523c 100644 --- a/library/std/src/sys/sync/mutex/pthread.rs +++ b/library/std/src/sys/sync/mutex/pthread.rs @@ -65,7 +65,7 @@ impl Drop for AllocatedMutex { // On DragonFly pthread_mutex_destroy() returns EINVAL if called on a // mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER. // Once it is used (locked/unlocked) or pthread_mutex_init() is called, - // this behaviour no longer occurs. + // this behavior no longer occurs. debug_assert!(r == 0 || r == libc::EINVAL); } else { debug_assert_eq!(r, 0); @@ -88,7 +88,7 @@ impl Mutex { /// since the `lock` and the lock must have occurred on the current thread. /// /// # Safety - /// Causes undefined behaviour if the mutex is not locked. + /// Causes undefined behavior if the mutex is not locked. #[inline] pub(crate) unsafe fn get_assert_locked(&self) -> *mut libc::pthread_mutex_t { unsafe { self.inner.get_unchecked().0.get() } diff --git a/library/std/src/sys/sync/once_box.rs b/library/std/src/sys/sync/once_box.rs index 9d24db2245a0..4105af503295 100644 --- a/library/std/src/sys/sync/once_box.rs +++ b/library/std/src/sys/sync/once_box.rs @@ -36,7 +36,7 @@ impl OnceBox { /// ``` /// /// # Safety - /// This causes undefined behaviour if the assumption above is violated. + /// This causes undefined behavior if the assumption above is violated. #[inline] pub unsafe fn get_unchecked(&self) -> &T { unsafe { &*self.ptr.load(Relaxed) } diff --git a/library/std/src/sys/sync/rwlock/futex.rs b/library/std/src/sys/sync/rwlock/futex.rs index df22c36dd5a2..447048edf762 100644 --- a/library/std/src/sys/sync/rwlock/futex.rs +++ b/library/std/src/sys/sync/rwlock/futex.rs @@ -283,7 +283,7 @@ impl RwLock { futex_wake(&self.writer_notify) // Note that FreeBSD and DragonFlyBSD don't tell us whether they woke // up any threads or not, and always return `false` here. That still - // results in correct behaviour: it just means readers get woken up as + // results in correct behavior: it just means readers get woken up as // well in case both readers and writers were waiting. } diff --git a/library/std/src/sys/sync/rwlock/queue.rs b/library/std/src/sys/sync/rwlock/queue.rs index 733f51cae8c1..889961915f4e 100644 --- a/library/std/src/sys/sync/rwlock/queue.rs +++ b/library/std/src/sys/sync/rwlock/queue.rs @@ -8,7 +8,7 @@ //! * `pthread` is an external library, meaning the fast path of acquiring an //! uncontended lock cannot be inlined. //! * Some platforms (at least glibc before version 2.25) have buggy implementations -//! that can easily lead to undefined behaviour in safe Rust code when not properly +//! that can easily lead to undefined behavior in safe Rust code when not properly //! guarded against. //! * On some platforms (e.g. macOS), the lock is very slow. //! diff --git a/library/std/src/sys/sync/thread_parking/darwin.rs b/library/std/src/sys/sync/thread_parking/darwin.rs index 96e3d23c332c..0553c5e19a91 100644 --- a/library/std/src/sys/sync/thread_parking/darwin.rs +++ b/library/std/src/sys/sync/thread_parking/darwin.rs @@ -5,7 +5,7 @@ //! rejection from the App Store). //! //! Therefore, we need to look for other synchronization primitives. Luckily, Darwin -//! supports semaphores, which allow us to implement the behaviour we need with +//! supports semaphores, which allow us to implement the behavior we need with //! only one primitive (as opposed to a mutex-condvar pair). We use the semaphore //! provided by libdispatch, as the underlying Mach semaphore is only dubiously //! public. diff --git a/library/std/src/sys/sync/thread_parking/pthread.rs b/library/std/src/sys/sync/thread_parking/pthread.rs index 5f195d0bb0cf..76df73b2a8e0 100644 --- a/library/std/src/sys/sync/thread_parking/pthread.rs +++ b/library/std/src/sys/sync/thread_parking/pthread.rs @@ -97,7 +97,7 @@ impl Parker { /// The constructed parker must never be moved. pub unsafe fn new_in_place(parker: *mut Parker) { // Use the default mutex implementation to allow for simpler initialization. - // This could lead to undefined behaviour when deadlocking. This is avoided + // This could lead to undefined behavior when deadlocking. This is avoided // by not deadlocking. Note in particular the unlocking operation before any // panic, as code after the panic could try to park again. (&raw mut (*parker).state).write(AtomicUsize::new(EMPTY)); diff --git a/library/std/src/sys/sync/thread_parking/windows7.rs b/library/std/src/sys/sync/thread_parking/windows7.rs index 8f7e66c46ef7..f7585e882f05 100644 --- a/library/std/src/sys/sync/thread_parking/windows7.rs +++ b/library/std/src/sys/sync/thread_parking/windows7.rs @@ -35,7 +35,7 @@ // different implementations. // // Unfortunately, NT Keyed Events are an undocumented Windows API. However: -// - This API is relatively simple with obvious behaviour, and there are +// - This API is relatively simple with obvious behavior, and there are // several (unofficial) articles documenting the details. [1] // - `parking_lot` has been using this API for years (on Windows versions // before Windows 8). [2] Many big projects extensively use parking_lot, @@ -43,7 +43,7 @@ // - It is the underlying API used by Windows SRW locks and Windows critical // sections. [3] [4] // - The source code of the implementations of Wine, ReactOs, and Windows XP -// are available and match the expected behaviour. +// are available and match the expected behavior. // - The main risk with an undocumented API is that it might change in the // future. But since we only use it for older versions of Windows, that's not // a problem. diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 70aa3170c6eb..227ee9d64f37 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -878,7 +878,7 @@ pub fn sleep(dur: Duration) { /// /// # Platform-specific behavior /// -/// This function uses [`sleep`] internally, see its platform-specific behaviour. +/// This function uses [`sleep`] internally, see its platform-specific behavior. /// /// /// # Examples @@ -949,7 +949,7 @@ pub fn sleep_until(deadline: Instant) { } /// Used to ensure that `park` and `park_timeout` do not unwind, as that can -/// cause undefined behaviour if not handled correctly (see #102398 for context). +/// cause undefined behavior if not handled correctly (see #102398 for context). struct PanicGuard; impl Drop for PanicGuard { diff --git a/library/std/src/time.rs b/library/std/src/time.rs index f28a0568a3c3..9f4f8a0d0880 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -178,9 +178,9 @@ pub struct Instant(time::Instant); /// system. /// /// A `SystemTime` does not count leap seconds. -/// `SystemTime::now()`'s behaviour around a leap second +/// `SystemTime::now()`'s behavior around a leap second /// is the same as the operating system's wall clock. -/// The precise behaviour near a leap second +/// The precise behavior near a leap second /// (e.g. whether the clock appears to run slow or fast, or stop, or jump) /// depends on platform and configuration, /// so should not be relied on. From 57683cfe1f7159576b11354777cc7a59e635d279 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 25 Oct 2024 12:02:48 +0200 Subject: [PATCH 245/366] Factor out token ranking --- .../rust-analyzer/crates/ide-db/src/lib.rs | 30 +++++++++++++++++++ .../rust-analyzer/crates/ide/src/hover.rs | 22 +++----------- .../crates/ide/src/syntax_highlighting.rs | 20 ++----------- src/tools/rust-analyzer/rust-bors.toml | 1 - 4 files changed, 37 insertions(+), 36 deletions(-) delete mode 100644 src/tools/rust-analyzer/rust-bors.toml diff --git a/src/tools/rust-analyzer/crates/ide-db/src/lib.rs b/src/tools/rust-analyzer/crates/ide-db/src/lib.rs index aed093f0ebfc..b7b133ac10ea 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/lib.rs @@ -293,3 +293,33 @@ impl SnippetCap { } } } + +pub struct Ranker<'a> { + pub kind: parser::SyntaxKind, + pub text: &'a str, + pub ident_kind: bool, +} + +impl<'a> Ranker<'a> { + pub fn from_token(token: &'a syntax::SyntaxToken) -> Self { + let kind = token.kind(); + Ranker { kind, text: token.text(), ident_kind: kind.is_any_identifier() } + } + + /// A utility function that ranks a token again a given kind and text, returning a number that + /// represents how close the token is to the given kind and text. + pub fn rank_token(&self, tok: &syntax::SyntaxToken) -> usize { + let tok_kind = tok.kind(); + + let exact_same_kind = tok_kind == self.kind; + let both_idents = exact_same_kind || (tok_kind.is_any_identifier() && self.ident_kind); + let same_text = tok.text() == self.text; + // anything that mapped into a token tree has likely no semantic information + let no_tt_parent = + tok.parent().map_or(false, |it| it.kind() != parser::SyntaxKind::TOKEN_TREE); + !((both_idents as usize) + | ((exact_same_kind as usize) << 1) + | ((same_text as usize) << 2) + | ((no_tt_parent as usize) << 3)) + } +} diff --git a/src/tools/rust-analyzer/crates/ide/src/hover.rs b/src/tools/rust-analyzer/crates/ide/src/hover.rs index 124db2985bf0..91ec672febac 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover.rs @@ -11,7 +11,7 @@ use ide_db::{ defs::{Definition, IdentClass, NameRefClass, OperatorClass}, famous_defs::FamousDefs, helpers::pick_best_token, - FileRange, FxIndexSet, RootDatabase, + FileRange, FxIndexSet, Ranker, RootDatabase, }; use itertools::{multizip, Itertools}; use span::Edition; @@ -182,27 +182,13 @@ fn hover_offset( // equivalency is more important let mut descended = sema.descend_into_macros(original_token.clone()); - let kind = original_token.kind(); - let text = original_token.text(); - let ident_kind = kind.is_any_identifier(); + let ranker = Ranker::from_token(&original_token); - descended.sort_by_cached_key(|tok| { - let tok_kind = tok.kind(); - - let exact_same_kind = tok_kind == kind; - let both_idents = exact_same_kind || (tok_kind.is_any_identifier() && ident_kind); - let same_text = tok.text() == text; - // anything that mapped into a token tree has likely no semantic information - let no_tt_parent = tok.parent().map_or(false, |it| it.kind() != TOKEN_TREE); - !((both_idents as usize) - | ((exact_same_kind as usize) << 1) - | ((same_text as usize) << 2) - | ((no_tt_parent as usize) << 3)) - }); + descended.sort_by_cached_key(|tok| ranker.rank_token(tok)); let mut res = vec![]; for token in descended { - let is_same_kind = token.kind() == kind; + let is_same_kind = token.kind() == ranker.kind; let lint_hover = (|| { // FIXME: Definition should include known lints and the like instead of having this special case here let attr = token.parent_ancestors().find_map(ast::Attr::cast)?; diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs index 961b2a4c9384..54d5307adff1 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs @@ -16,7 +16,7 @@ mod tests; use std::ops::ControlFlow; use hir::{InRealFile, Name, Semantics}; -use ide_db::{FxHashMap, RootDatabase, SymbolKind}; +use ide_db::{FxHashMap, Ranker, RootDatabase, SymbolKind}; use span::EditionedFileId; use syntax::{ ast::{self, IsString}, @@ -401,9 +401,7 @@ fn traverse( // Attempt to descend tokens into macro-calls. let res = match element { NodeOrToken::Token(token) if token.kind() != COMMENT => { - let kind = token.kind(); - let text = token.text(); - let ident_kind = kind.is_any_identifier(); + let ranker = Ranker::from_token(&token); let mut t = None; let mut r = 0; @@ -412,19 +410,7 @@ fn traverse( |tok, _ctx| { // FIXME: Consider checking ctx transparency for being opaque? let tok = tok.value; - let tok_kind = tok.kind(); - - let exact_same_kind = tok_kind == kind; - let both_idents = - exact_same_kind || (tok_kind.is_any_identifier() && ident_kind); - let same_text = tok.text() == text; - // anything that mapped into a token tree has likely no semantic information - let no_tt_parent = - tok.parent().map_or(false, |it| it.kind() != TOKEN_TREE); - let my_rank = (both_idents as usize) - | ((exact_same_kind as usize) << 1) - | ((same_text as usize) << 2) - | ((no_tt_parent as usize) << 3); + let my_rank = ranker.rank_token(&tok); if my_rank > 0b1110 { // a rank of 0b1110 means that we have found a maximally interesting diff --git a/src/tools/rust-analyzer/rust-bors.toml b/src/tools/rust-analyzer/rust-bors.toml deleted file mode 100644 index c31ba66c50f4..000000000000 --- a/src/tools/rust-analyzer/rust-bors.toml +++ /dev/null @@ -1 +0,0 @@ -timeout = 3600 From 08b504ae8fb5adfbe4df23f80d87bbc2b42c52cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Fri, 25 Oct 2024 15:14:52 +0300 Subject: [PATCH 246/366] Stop producing .gz artifacts for Windows --- src/tools/rust-analyzer/xtask/src/dist.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/xtask/src/dist.rs b/src/tools/rust-analyzer/xtask/src/dist.rs index 742cf7f609a1..c6a0be8aeb99 100644 --- a/src/tools/rust-analyzer/xtask/src/dist.rs +++ b/src/tools/rust-analyzer/xtask/src/dist.rs @@ -101,9 +101,10 @@ fn dist_server( cmd!(sh, "cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --target {target_name} {features...} --release").run()?; let dst = Path::new("dist").join(&target.artifact_name); - gzip(&target.server_path, &dst.with_extension("gz"))?; if target_name.contains("-windows-") { zip(&target.server_path, target.symbols_path.as_ref(), &dst.with_extension("zip"))?; + } else { + gzip(&target.server_path, &dst.with_extension("gz"))?; } Ok(()) From baa3b6d95e049ae335843e6133fb7b5ba544e0a6 Mon Sep 17 00:00:00 2001 From: WANG Rui Date: Fri, 25 Oct 2024 19:56:55 +0800 Subject: [PATCH 247/366] Enable LSX feature for LoongArch Linux targets --- .../src/spec/targets/loongarch64_unknown_linux_gnu.rs | 2 +- .../src/spec/targets/loongarch64_unknown_linux_musl.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs index 68d511935644..603c0f99314b 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs @@ -15,7 +15,7 @@ pub(crate) fn target() -> Target { options: TargetOptions { code_model: Some(CodeModel::Medium), cpu: "generic".into(), - features: "+f,+d".into(), + features: "+f,+d,+lsx".into(), llvm_abiname: "lp64d".into(), max_atomic_width: Some(64), supported_sanitizers: SanitizerSet::ADDRESS diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs index 25d3559d920b..d7044dde0f17 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs @@ -15,7 +15,7 @@ pub(crate) fn target() -> Target { options: TargetOptions { code_model: Some(CodeModel::Medium), cpu: "generic".into(), - features: "+f,+d".into(), + features: "+f,+d,+lsx".into(), llvm_abiname: "lp64d".into(), max_atomic_width: Some(64), crt_static_default: false, From 09773b4f24841c5ff3b2ba035e3b9772a58f6178 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 24 Oct 2024 19:50:54 -0500 Subject: [PATCH 248/366] allow type-based search on foreign functions fixes https://github.com/rust-lang/rust/issues/131804 --- src/librustdoc/html/render/search_index.rs | 5 ++++- tests/rustdoc-js/extern-func.js | 8 ++++++++ tests/rustdoc-js/extern-func.rs | 5 +++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tests/rustdoc-js/extern-func.js create mode 100644 tests/rustdoc-js/extern-func.rs diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index c958458b662c..d1939adc1a50 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -759,7 +759,10 @@ pub(crate) fn get_function_type_for_search<'tcx>( } }); let (mut inputs, mut output, where_clause) = match item.kind { - clean::FunctionItem(ref f) | clean::MethodItem(ref f, _) | clean::TyMethodItem(ref f) => { + clean::ForeignFunctionItem(ref f, _) + | clean::FunctionItem(ref f) + | clean::MethodItem(ref f, _) + | clean::TyMethodItem(ref f) => { get_fn_inputs_and_outputs(f, tcx, impl_or_trait_generics, cache) } _ => return None, diff --git a/tests/rustdoc-js/extern-func.js b/tests/rustdoc-js/extern-func.js new file mode 100644 index 000000000000..a3fe2d8ea427 --- /dev/null +++ b/tests/rustdoc-js/extern-func.js @@ -0,0 +1,8 @@ +const EXPECTED = [ + { + 'query': 'c_float -> c_float', + 'others': [ + { 'path': 'extern_func', 'name': 'sqrt' } + ], + }, +]; diff --git a/tests/rustdoc-js/extern-func.rs b/tests/rustdoc-js/extern-func.rs new file mode 100644 index 000000000000..ab1e3e75da7f --- /dev/null +++ b/tests/rustdoc-js/extern-func.rs @@ -0,0 +1,5 @@ +use std::ffi::c_float; + +extern "C" { + pub fn sqrt(x: c_float) -> c_float; +} From 24ac777a641c7efc6d2f6e9a69617800314119f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 25 Oct 2024 17:01:20 +0000 Subject: [PATCH 249/366] Add test for #132013 --- ...-between-expected-trait-and-found-trait.rs | 20 ++++++ ...between-expected-trait-and-found-trait.svg | 62 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.rs create mode 100644 tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg diff --git a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.rs b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.rs new file mode 100644 index 000000000000..f1c196a154d5 --- /dev/null +++ b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.rs @@ -0,0 +1,20 @@ +//@ only-linux +//@ compile-flags: --error-format=human --color=always +//@ error-pattern: the trait bound + +trait Foo: Bar {} + +trait Bar {} + +struct Struct; + +impl Foo for T where T: Bar +{} + +impl<'a> Bar<()> for Struct {} + +fn foo() -> impl Foo { + Struct +} + +fn main() {} diff --git a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg new file mode 100644 index 000000000000..aaf08b9a246c --- /dev/null +++ b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg @@ -0,0 +1,62 @@ + + + + + + + error[E0277]: the trait bound `Struct: Foo<i32>` is not satisfied + + --> $DIR/highlight-difference-between-expected-trait-and-found-trait.rs:16:13 + + | + + LL | fn foo() -> impl Foo<i32> { + + | ^^^^^^^^^^^^^ the trait `Bar<i32>` is not implemented for `Struct`, which is required by `Struct: Foo<i32>` + + | + + = help: the trait `Bar<()>` is implemented for `Struct` + + = help: for that trait implementation, expected `()`, found `i32` + + note: required for `Struct` to implement `Foo<i32>` + + --> $DIR/highlight-difference-between-expected-trait-and-found-trait.rs:11:12 + + | + + LL | impl<T, K> Foo<K> for T where T: Bar<K> + + | ^^^^^^ ^ ------ unsatisfied trait bound introduced here + + + + error: aborting due to 1 previous error + + + + For more information about this error, try `rustc --explain E0277`. + + + + + + From aa82fd6d1dd2f2ac6a44dbfa99e1de779b58428a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 24 Oct 2024 00:20:04 +0000 Subject: [PATCH 250/366] Tweak highlighting when trait is available for different type When printing ``` = help: the trait `chumsky::private::ParserSealed<'_, &'a str, ((), ()), chumsky::extra::Full>` is implemented for `Then>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full>` = help: for that trait implementation, expected `((), ())`, found `()` ``` Highlight only the `expected` and `found` types, instead of the full type in the first `help`. --- .../traits/fulfillment_errors.rs | 19 ++++++++++++++----- ...between-expected-trait-and-found-trait.svg | 4 ++-- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index b7e2ed391cd4..1852837d5c72 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -1835,6 +1835,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if impl_trait_ref.references_error() { return false; } + let self_ty = impl_trait_ref.self_ty().to_string(); err.highlighted_help(vec![ StringPart::normal(format!( "the trait `{}` ", @@ -1842,16 +1843,24 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { )), StringPart::highlighted("is"), StringPart::normal(" implemented for `"), - StringPart::highlighted(impl_trait_ref.self_ty().to_string()), + if let [TypeError::Sorts(_)] = &terrs[..] { + StringPart::normal(self_ty) + } else { + StringPart::highlighted(self_ty) + }, StringPart::normal("`"), ]); if let [TypeError::Sorts(exp_found)] = &terrs[..] { let exp_found = self.resolve_vars_if_possible(*exp_found); - err.help(format!( - "for that trait implementation, expected `{}`, found `{}`", - exp_found.expected, exp_found.found - )); + err.highlighted_help(vec![ + StringPart::normal("for that trait implementation, "), + StringPart::normal("expected `"), + StringPart::highlighted(exp_found.expected.to_string()), + StringPart::normal("`, found `"), + StringPart::highlighted(exp_found.found.to_string()), + StringPart::normal("`"), + ]); } true diff --git a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg index aaf08b9a246c..e09b96e5ff2c 100644 --- a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg +++ b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg @@ -33,9 +33,9 @@ | - = help: the trait `Bar<()>` is implemented for `Struct` + = help: the trait `Bar<()>` is implemented for `Struct` - = help: for that trait implementation, expected `()`, found `i32` + = help: for that trait implementation, expected `()`, found `i32` note: required for `Struct` to implement `Foo<i32>` From 5980a32ef1b8a542bbf64e685af09d5a87d9b501 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 24 Oct 2024 00:22:37 +0000 Subject: [PATCH 251/366] Pass long type path into `note_obligation_cause_code` to avoid printing same path multiple times Because `note_obligation_cause_code` is recursive, if multiple types are too long to print to the terminal, a `long_ty_file` will be created. Before, one was created *per recursion*. Now, it is passed in so it gets printed only once. Part of #132013. --- .../traits/fulfillment_errors.rs | 9 +++++ .../src/error_reporting/traits/mod.rs | 11 ++++++ .../src/error_reporting/traits/overflow.rs | 11 ++++++ .../src/error_reporting/traits/suggestions.rs | 38 +++++++++---------- 4 files changed, 49 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 1852837d5c72..6014ed555b64 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -2169,6 +2169,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // First, attempt to add note to this error with an async-await-specific // message, and fall back to regular note otherwise. if !self.maybe_note_obligation_cause_for_async_await(err, obligation) { + let mut long_ty_file = None; self.note_obligation_cause_code( obligation.cause.body_id, err, @@ -2177,7 +2178,15 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { obligation.cause.code(), &mut vec![], &mut Default::default(), + &mut long_ty_file, ); + if let Some(file) = long_ty_file { + err.note(format!( + "the full name for the type has been written to '{}'", + file.display(), + )); + err.note("consider using `--verbose` to print the full type name to the console"); + } self.suggest_unsized_bound_if_applicable(err, obligation); if let Some(span) = err.span.primary_span() && let Some(mut diag) = diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs index ca23f7765819..b108a9352a53 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs @@ -305,6 +305,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if let ObligationCauseCode::WhereClause(..) | ObligationCauseCode::WhereClauseInExpr(..) = code { + let mut long_ty_file = None; self.note_obligation_cause_code( error.obligation.cause.body_id, &mut diag, @@ -313,7 +314,17 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { code, &mut vec![], &mut Default::default(), + &mut long_ty_file, ); + if let Some(file) = long_ty_file { + diag.note(format!( + "the full name for the type has been written to '{}'", + file.display(), + )); + diag.note( + "consider using `--verbose` to print the full type name to the console", + ); + } } diag.emit() } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs index f4c5733d4a6d..c47c21696911 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs @@ -144,6 +144,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { obligation.cause.span, suggest_increasing_limit, |err| { + let mut long_ty_file = None; self.note_obligation_cause_code( obligation.cause.body_id, err, @@ -152,7 +153,17 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { obligation.cause.code(), &mut vec![], &mut Default::default(), + &mut long_ty_file, ); + if let Some(file) = long_ty_file { + err.note(format!( + "the full name for the type has been written to '{}'", + file.display(), + )); + err.note( + "consider using `--verbose` to print the full type name to the console", + ); + } }, ); } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 1fe93cb017ab..a7d1f1bd8d04 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -3,6 +3,7 @@ use std::assert_matches::debug_assert_matches; use std::borrow::Cow; use std::iter; +use std::path::PathBuf; use itertools::{EitherOrBoth, Itertools}; use rustc_data_structures::fx::FxHashSet; @@ -2703,6 +2704,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Add a note for the item obligation that remains - normally a note pointing to the // bound that introduced the obligation (e.g. `T: Send`). debug!(?next_code); + let mut long_ty_file = None; self.note_obligation_cause_code( obligation.cause.body_id, err, @@ -2711,6 +2713,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { next_code.unwrap(), &mut Vec::new(), &mut Default::default(), + &mut long_ty_file, ); } @@ -2723,11 +2726,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { cause_code: &ObligationCauseCode<'tcx>, obligated_types: &mut Vec>, seen_requirements: &mut FxHashSet, + long_ty_file: &mut Option, ) where T: Upcast, ty::Predicate<'tcx>>, { - let mut long_ty_file = None; - let tcx = self.tcx; let predicate = predicate.upcast(tcx); let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| { @@ -2957,9 +2959,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } ObligationCauseCode::Coercion { source, target } => { let source = - tcx.short_ty_string(self.resolve_vars_if_possible(source), &mut long_ty_file); + tcx.short_ty_string(self.resolve_vars_if_possible(source), long_ty_file); let target = - tcx.short_ty_string(self.resolve_vars_if_possible(target), &mut long_ty_file); + tcx.short_ty_string(self.resolve_vars_if_possible(target), long_ty_file); err.note(with_forced_trimmed_paths!(format!( "required for the cast from `{source}` to `{target}`", ))); @@ -3249,7 +3251,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; if !is_upvar_tys_infer_tuple { - let ty_str = tcx.short_ty_string(ty, &mut long_ty_file); + let ty_str = tcx.short_ty_string(ty, long_ty_file); let msg = format!("required because it appears within the type `{ty_str}`"); match ty.kind() { ty::Adt(def, _) => match tcx.opt_item_ident(def.did()) { @@ -3327,6 +3329,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &data.parent_code, obligated_types, seen_requirements, + long_ty_file, ) }); } else { @@ -3339,6 +3342,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { cause_code.peel_derives(), obligated_types, seen_requirements, + long_ty_file, ) }); } @@ -3347,8 +3351,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let mut parent_trait_pred = self.resolve_vars_if_possible(data.derived.parent_trait_pred); let parent_def_id = parent_trait_pred.def_id(); - let self_ty_str = tcx - .short_ty_string(parent_trait_pred.skip_binder().self_ty(), &mut long_ty_file); + let self_ty_str = + tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty(), long_ty_file); let trait_name = parent_trait_pred.print_modifiers_and_trait_path().to_string(); let msg = format!("required for `{self_ty_str}` to implement `{trait_name}`"); let mut is_auto_trait = false; @@ -3444,10 +3448,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { count, pluralize!(count) )); - let self_ty = tcx.short_ty_string( - parent_trait_pred.skip_binder().self_ty(), - &mut long_ty_file, - ); + let self_ty = tcx + .short_ty_string(parent_trait_pred.skip_binder().self_ty(), long_ty_file); err.note(format!( "required for `{self_ty}` to implement `{}`", parent_trait_pred.print_modifiers_and_trait_path() @@ -3463,6 +3465,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &data.parent_code, obligated_types, seen_requirements, + long_ty_file, ) }); } @@ -3479,6 +3482,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &data.parent_code, obligated_types, seen_requirements, + long_ty_file, ) }); } @@ -3493,6 +3497,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { nested, obligated_types, seen_requirements, + long_ty_file, ) }); let mut multispan = MultiSpan::from(span); @@ -3523,6 +3528,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { parent_code, obligated_types, seen_requirements, + long_ty_file, ) }); } @@ -3562,7 +3568,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } ObligationCauseCode::OpaqueReturnType(expr_info) => { if let Some((expr_ty, hir_id)) = expr_info { - let expr_ty = self.tcx.short_ty_string(expr_ty, &mut long_ty_file); + let expr_ty = self.tcx.short_ty_string(expr_ty, long_ty_file); let expr = self.infcx.tcx.hir().expect_expr(hir_id); err.span_label( expr.span, @@ -3574,14 +3580,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } } - - if let Some(file) = long_ty_file { - err.note(format!( - "the full name for the type has been written to '{}'", - file.display(), - )); - err.note("consider using `--verbose` to print the full type name to the console"); - } } #[instrument( From a0215d8e46aab41219dea0bb1cbaaf97dafe2f89 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 6 Oct 2024 19:59:19 +0200 Subject: [PATCH 252/366] Re-do recursive const stability checks Fundamentally, we have *three* disjoint categories of functions: 1. const-stable functions 2. private/unstable functions that are meant to be callable from const-stable functions 3. functions that can make use of unstable const features This PR implements the following system: - `#[rustc_const_stable]` puts functions in the first category. It may only be applied to `#[stable]` functions. - `#[rustc_const_unstable]` by default puts functions in the third category. The new attribute `#[rustc_const_stable_indirect]` can be added to such a function to move it into the second category. - `const fn` without a const stability marker are in the second category if they are still unstable. They automatically inherit the feature gate for regular calls, it can now also be used for const-calls. Also, several holes in recursive const stability checking are being closed. There's still one potential hole that is hard to avoid, which is when MIR building automatically inserts calls to a particular function in stable functions -- which happens in the panic machinery. Those need to *not* be `rustc_const_unstable` (or manually get a `rustc_const_stable_indirect`) to be sure they follow recursive const stability. But that's a fairly rare and special case so IMO it's fine. The net effect of this is that a `#[unstable]` or unmarked function can be constified simply by marking it as `const fn`, and it will then be const-callable from stable `const fn` and subject to recursive const stability requirements. If it is publicly reachable (which implies it cannot be unmarked), it will be const-unstable under the same feature gate. Only if the function ever becomes `#[stable]` does it need a `#[rustc_const_unstable]` or `#[rustc_const_stable]` marker to decide if this should also imply const-stability. Adding `#[rustc_const_unstable]` is only needed for (a) functions that need to use unstable const lang features (including intrinsics), or (b) `#[stable]` functions that are not yet intended to be const-stable. Adding `#[rustc_const_stable]` is only needed for functions that are actually meant to be directly callable from stable const code. `#[rustc_const_stable_indirect]` is used to mark intrinsics as const-callable and for `#[rustc_const_unstable]` functions that are actually called from other, exposed-on-stable `const fn`. No other attributes are required. --- compiler/rustc_attr/messages.ftl | 3 + compiler/rustc_attr/src/builtin.rs | 78 ++++++- .../rustc_attr/src/session_diagnostics.rs | 7 + ...0027-stdlib-128bit-atomic-operations.patch | 8 +- compiler/rustc_const_eval/messages.ftl | 25 +- .../src/check_consts/check.rs | 220 ++++++++++++------ .../rustc_const_eval/src/check_consts/mod.rs | 60 ++--- .../rustc_const_eval/src/check_consts/ops.rs | 98 ++++++-- .../src/check_consts/post_drop_elaboration.rs | 2 +- .../src/const_eval/fn_queries.rs | 19 +- .../src/const_eval/machine.rs | 2 +- compiler/rustc_const_eval/src/errors.rs | 47 +++- compiler/rustc_expand/src/base.rs | 4 +- compiler/rustc_feature/src/builtin_attrs.rs | 14 +- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_passes/messages.ftl | 8 +- compiler/rustc_passes/src/errors.rs | 8 + compiler/rustc_passes/src/stability.rs | 118 +++++++--- compiler/rustc_span/src/symbol.rs | 1 + library/alloc/src/raw_vec.rs | 6 +- library/core/src/alloc/layout.rs | 4 +- library/core/src/cell.rs | 1 + library/core/src/cell/lazy.rs | 1 + library/core/src/char/methods.rs | 2 +- library/core/src/ffi/c_str.rs | 6 +- library/core/src/fmt/mod.rs | 6 +- library/core/src/hint.rs | 2 +- library/core/src/intrinsics.rs | 181 +++++++++----- library/core/src/iter/traits/collect.rs | 1 - library/core/src/lib.rs | 6 +- library/core/src/net/ip_addr.rs | 1 + library/core/src/num/f128.rs | 14 -- library/core/src/num/f16.rs | 14 -- library/core/src/num/mod.rs | 5 +- library/core/src/num/uint_macros.rs | 2 +- library/core/src/panic/panic_info.rs | 1 + library/core/src/panicking.rs | 30 ++- library/core/src/ptr/alignment.rs | 14 +- library/core/src/ptr/const_ptr.rs | 8 +- library/core/src/ptr/metadata.rs | 6 +- library/core/src/ptr/mod.rs | 9 +- library/core/src/ptr/mut_ptr.rs | 6 +- library/core/src/ptr/non_null.rs | 1 - library/core/src/ptr/unique.rs | 1 + library/core/src/slice/ascii.rs | 2 + library/core/src/slice/index.rs | 4 +- library/core/src/slice/memchr.rs | 8 +- library/core/src/slice/mod.rs | 6 + library/core/src/sync/atomic.rs | 23 +- library/core/src/sync/exclusive.rs | 3 + library/core/src/task/wake.rs | 4 +- library/core/src/ub_checks.rs | 10 +- library/core/tests/lib.rs | 2 +- library/std/src/sys/sync/once/queue.rs | 2 +- library/std/src/sys/thread_local/key/racy.rs | 2 +- library/std/src/sys/thread_local/os.rs | 2 +- library/std/src/thread/local.rs | 2 +- src/librustdoc/clean/types.rs | 16 +- src/librustdoc/html/render/mod.rs | 4 +- src/librustdoc/lib.rs | 1 - tests/rustdoc/const-display.rs | 6 - tests/ui/borrowck/issue-64453.rs | 1 - tests/ui/borrowck/issue-64453.stderr | 13 +- .../auxiliary/unstable_but_const_stable.rs | 13 -- .../ui/consts/auxiliary/unstable_intrinsic.rs | 26 +++ .../dont_promote_unstable_const_fn.rs | 4 +- .../dont_promote_unstable_const_fn.stderr | 14 +- .../consts/const-eval/simd/insert_extract.rs | 3 + tests/ui/consts/const-unstable-intrinsic.rs | 76 ++++++ .../ui/consts/const-unstable-intrinsic.stderr | 127 ++++++++++ tests/ui/consts/copy-intrinsic.rs | 2 + tests/ui/consts/copy-intrinsic.stderr | 8 +- .../ui/consts/intrinsic_without_const_stab.rs | 17 -- .../intrinsic_without_const_stab.stderr | 11 - .../intrinsic_without_const_stab_fail.rs | 15 -- .../intrinsic_without_const_stab_fail.stderr | 11 - .../min_const_fn_libstd_stability.rs | 34 ++- .../min_const_fn_libstd_stability.stderr | 108 +++++++-- .../min_const_unsafe_fn_libstd_stability.rs | 8 +- ...in_const_unsafe_fn_libstd_stability.stderr | 46 +++- .../min_const_unsafe_fn_libstd_stability2.rs | 8 +- ...n_const_unsafe_fn_libstd_stability2.stderr | 46 +++- .../rustc-const-stability-require-const.rs | 31 ++- ...rustc-const-stability-require-const.stderr | 54 +++-- tests/ui/consts/unstable-const-stable.rs | 14 -- tests/ui/consts/unstable-const-stable.stderr | 43 ---- ...ute-rejects-already-stable-features.stderr | 28 +-- .../intrinsics/const-eval-select-stability.rs | 2 +- .../const-eval-select-stability.stderr | 13 +- ...nst-stability-attribute-implies-missing.rs | 1 - ...stability-attribute-implies-missing.stderr | 10 +- .../missing-const-stability.rs | 13 +- .../missing-const-stability.stderr | 10 +- tests/ui/target-feature/feature-hierarchy.rs | 1 + tests/ui/target-feature/no-llvm-leaks.rs | 1 + .../const-traits/auxiliary/staged-api.rs | 9 + .../traits/const-traits/effects/minicore.rs | 2 +- tests/ui/traits/const-traits/issue-79450.rs | 1 - .../ui/traits/const-traits/issue-79450.stderr | 2 +- tests/ui/traits/const-traits/staged-api.rs | 34 ++- .../const-traits/staged-api.stable.stderr | 56 ++++- .../const-traits/staged-api.unstable.stderr | 118 +++++++--- 102 files changed, 1520 insertions(+), 663 deletions(-) delete mode 100644 tests/ui/consts/auxiliary/unstable_but_const_stable.rs create mode 100644 tests/ui/consts/auxiliary/unstable_intrinsic.rs create mode 100644 tests/ui/consts/const-unstable-intrinsic.rs create mode 100644 tests/ui/consts/const-unstable-intrinsic.stderr delete mode 100644 tests/ui/consts/intrinsic_without_const_stab.rs delete mode 100644 tests/ui/consts/intrinsic_without_const_stab.stderr delete mode 100644 tests/ui/consts/intrinsic_without_const_stab_fail.rs delete mode 100644 tests/ui/consts/intrinsic_without_const_stab_fail.stderr delete mode 100644 tests/ui/consts/unstable-const-stable.rs delete mode 100644 tests/ui/consts/unstable-const-stable.stderr diff --git a/compiler/rustc_attr/messages.ftl b/compiler/rustc_attr/messages.ftl index adabf18ca85d..235ab7572c41 100644 --- a/compiler/rustc_attr/messages.ftl +++ b/compiler/rustc_attr/messages.ftl @@ -91,6 +91,9 @@ attr_non_ident_feature = attr_rustc_allowed_unstable_pairing = `rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute +attr_rustc_const_stable_indirect_pairing = + `const_stable_indirect` attribute does not make sense on `rustc_const_stable` function, its behavior is already implied + attr_rustc_promotable_pairing = `rustc_promotable` attribute must be paired with either a `rustc_const_unstable` or a `rustc_const_stable` attribute diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 537d8e045311..6af75bc94bb6 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -16,9 +16,9 @@ use rustc_session::lint::BuiltinLintDiag; use rustc_session::lint::builtin::UNEXPECTED_CFGS; use rustc_session::parse::feature_err; use rustc_session::{RustcVersion, Session}; -use rustc_span::Span; use rustc_span::hygiene::Transparency; use rustc_span::symbol::{Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; use crate::fluent_generated; use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause}; @@ -92,7 +92,11 @@ impl Stability { #[derive(HashStable_Generic)] pub struct ConstStability { pub level: StabilityLevel, - pub feature: Symbol, + /// This can be `None` for functions that do not have an explicit const feature. + /// We still track them for recursive const stability checks. + pub feature: Option, + /// This is true iff the `const_stable_indirect` attribute is present. + pub const_stable_indirect: bool, /// whether the function has a `#[rustc_promotable]` attribute pub promotable: bool, } @@ -268,17 +272,23 @@ pub fn find_stability( /// Collects stability info from `rustc_const_stable`/`rustc_const_unstable`/`rustc_promotable` /// attributes in `attrs`. Returns `None` if no stability attributes are found. +/// +/// `is_const_fn` indicates whether this is a function marked as `const`. It will always +/// be false for intrinsics in an `extern` block! pub fn find_const_stability( sess: &Session, attrs: &[Attribute], item_sp: Span, + is_const_fn: bool, ) -> Option<(ConstStability, Span)> { let mut const_stab: Option<(ConstStability, Span)> = None; let mut promotable = false; + let mut const_stable_indirect = None; for attr in attrs { match attr.name_or_empty() { sym::rustc_promotable => promotable = true, + sym::rustc_const_stable_indirect => const_stable_indirect = Some(attr.span), sym::rustc_const_unstable => { if const_stab.is_some() { sess.dcx() @@ -287,8 +297,15 @@ pub fn find_const_stability( } if let Some((feature, level)) = parse_unstability(sess, attr) { - const_stab = - Some((ConstStability { level, feature, promotable: false }, attr.span)); + const_stab = Some(( + ConstStability { + level, + feature: Some(feature), + const_stable_indirect: false, + promotable: false, + }, + attr.span, + )); } } sym::rustc_const_stable => { @@ -298,15 +315,22 @@ pub fn find_const_stability( break; } if let Some((feature, level)) = parse_stability(sess, attr) { - const_stab = - Some((ConstStability { level, feature, promotable: false }, attr.span)); + const_stab = Some(( + ConstStability { + level, + feature: Some(feature), + const_stable_indirect: false, + promotable: false, + }, + attr.span, + )); } } _ => {} } } - // Merge the const-unstable info into the stability info + // Merge promotable and not_exposed_on_stable into stability info if promotable { match &mut const_stab { Some((stab, _)) => stab.promotable = promotable, @@ -317,6 +341,46 @@ pub fn find_const_stability( } } } + if const_stable_indirect.is_some() { + match &mut const_stab { + Some((stab, _)) => { + if stab.is_const_unstable() { + stab.const_stable_indirect = true; + } else { + _ = sess.dcx().emit_err(session_diagnostics::RustcConstStableIndirectPairing { + span: item_sp, + }) + } + } + _ => { + // We ignore the `#[rustc_const_stable_indirect]` here, it should be picked up by + // the `default_const_unstable` logic. + } + } + } + // Make sure if `const_stable_indirect` is present, that is recorded. Also make sure all `const + // fn` get *some* marker, since we are a staged_api crate and therefore will do recursive const + // stability checks for them. We need to do this because the default for whether an unmarked + // function enforces recursive stability differs between staged-api crates and force-unmarked + // crates: in force-unmarked crates, only functions *explicitly* marked `const_stable_indirect` + // enforce recursive stability. Therefore when `lookup_const_stability` is `None`, we have to + // assume the function does not have recursive stability. All functions that *do* have recursive + // stability must explicitly record this, and so that's what we do for all `const fn` in a + // staged_api crate. + if (is_const_fn || const_stable_indirect.is_some()) && const_stab.is_none() { + let c = ConstStability { + feature: None, + const_stable_indirect: const_stable_indirect.is_some(), + promotable: false, + level: StabilityLevel::Unstable { + reason: UnstableReason::Default, + issue: None, + is_soft: false, + implied_by: None, + }, + }; + const_stab = Some((c, const_stable_indirect.unwrap_or(DUMMY_SP))); + } const_stab } diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 626840aa6a3c..9d08a9f57542 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -318,6 +318,13 @@ pub(crate) struct RustcPromotablePairing { pub span: Span, } +#[derive(Diagnostic)] +#[diag(attr_rustc_const_stable_indirect_pairing)] +pub(crate) struct RustcConstStableIndirectPairing { + #[primary_span] + pub span: Span, +} + #[derive(Diagnostic)] #[diag(attr_rustc_allowed_unstable_pairing, code = E0789)] pub(crate) struct RustcAllowedUnstablePairing { diff --git a/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch b/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch index 646928893e96..3c81b04c0ead 100644 --- a/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch +++ b/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch @@ -38,7 +38,7 @@ diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index d9de37e..8293fce 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs -@@ -2996,42 +2996,6 @@ atomic_int! { +@@ -2996,44 +2996,6 @@ atomic_int! { 8, u64 AtomicU64 } @@ -52,7 +52,8 @@ index d9de37e..8293fce 100644 - unstable(feature = "integer_atomics", issue = "99069"), - unstable(feature = "integer_atomics", issue = "99069"), - unstable(feature = "integer_atomics", issue = "99069"), -- rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), +- rustc_const_unstable(feature = "integer_atomics", issue = "99069"), +- rustc_const_unstable(feature = "integer_atomics", issue = "99069"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicI128"), - "i128", - "#![feature(integer_atomics)]\n\n", @@ -70,7 +71,8 @@ index d9de37e..8293fce 100644 - unstable(feature = "integer_atomics", issue = "99069"), - unstable(feature = "integer_atomics", issue = "99069"), - unstable(feature = "integer_atomics", issue = "99069"), -- rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), +- rustc_const_unstable(feature = "integer_atomics", issue = "99069"), +- rustc_const_unstable(feature = "integer_atomics", issue = "99069"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicU128"), - "u128", - "#![feature(integer_atomics)]\n\n", diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index 24dbe688f363..3e4f83c8242e 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -41,8 +41,6 @@ const_eval_const_context = {$kind -> *[other] {""} } -const_eval_const_stable = const-stable functions can only call other const-stable functions - const_eval_copy_nonoverlapping_overlapping = `copy_nonoverlapping` called on overlapping ranges @@ -259,6 +257,9 @@ const_eval_non_const_fn_call = const_eval_non_const_impl = impl defined here, but it is not `const` +const_eval_non_const_intrinsic = + cannot call non-const intrinsic `{$name}` in {const_eval_const_context}s + const_eval_not_enough_caller_args = calling a function with fewer arguments than it requires @@ -397,17 +398,29 @@ const_eval_uninhabited_enum_variant_read = read discriminant of an uninhabited enum variant const_eval_uninhabited_enum_variant_written = writing discriminant of an uninhabited enum variant + +const_eval_unmarked_const_fn_exposed = `{$def_path}` cannot be (indirectly) exposed to stable + .help = either mark the callee as `#[rustc_const_stable_indirect]`, or the caller as `#[rustc_const_unstable]` +const_eval_unmarked_intrinsic_exposed = intrinsic `{$def_path}` cannot be (indirectly) exposed to stable + .help = mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_const_stable_indirect]` (but this requires team approval) + const_eval_unreachable = entering unreachable code const_eval_unreachable_unwind = unwinding past a stack frame that does not allow unwinding const_eval_unsized_local = unsized locals are not supported const_eval_unstable_const_fn = `{$def_path}` is not yet stable as a const fn +const_eval_unstable_in_stable_exposed = + const function that might be (indirectly) exposed to stable cannot use `#[feature({$gate})]` + .is_function_call = mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features + .unstable_sugg = if the {$is_function_call2 -> + [true] caller + *[false] function + } is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + .bypass_sugg = otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) -const_eval_unstable_in_stable = - const-stable function cannot use `#[feature({$gate})]` - .unstable_sugg = if the function is not (yet) meant to be stable, make this function unstably const - .bypass_sugg = otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (but requires team approval) +const_eval_unstable_intrinsic = `{$name}` is not yet stable as a const intrinsic + .help = add `#![feature({$feature})]` to the crate attributes to enable const_eval_unterminated_c_string = reading a null-terminated string starting at {$pointer} with no null found before end of allocation diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 288798bf0c27..ef01fe88979a 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -5,6 +5,7 @@ use std::borrow::Cow; use std::mem; use std::ops::Deref; +use rustc_attr::{ConstStability, StabilityLevel}; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem}; @@ -28,8 +29,8 @@ use super::ops::{self, NonConstOp, Status}; use super::qualifs::{self, HasMutInterior, NeedsDrop, NeedsNonConstDrop}; use super::resolver::FlowSensitiveAnalysis; use super::{ConstCx, Qualif}; -use crate::const_eval::is_unstable_const_fn; -use crate::errors::UnstableInStable; +use crate::check_consts::is_safe_to_expose_on_stable_const_fn; +use crate::errors; type QualifResults<'mir, 'tcx, Q> = rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'mir, 'tcx, Q>>; @@ -274,19 +275,22 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { /// context. pub fn check_op_spanned>(&mut self, op: O, span: Span) { let gate = match op.status_in_item(self.ccx) { - Status::Allowed => return, - - Status::Unstable(gate) if self.tcx.features().enabled(gate) => { - let unstable_in_stable = self.ccx.is_const_stable_const_fn() - && !super::rustc_allow_const_fn_unstable(self.tcx, self.def_id(), gate); - if unstable_in_stable { - emit_unstable_in_stable_error(self.ccx, span, gate); + Status::Unstable { gate, safe_to_expose_on_stable, is_function_call } + if self.tcx.features().enabled(gate) => + { + // Generally this is allowed since the feature gate is enabled -- except + // if this function wants to be safe-to-expose-on-stable. + if !safe_to_expose_on_stable + && self.enforce_recursive_const_stability() + && !super::rustc_allow_const_fn_unstable(self.tcx, self.def_id(), gate) + { + emit_unstable_in_stable_exposed_error(self.ccx, span, gate, is_function_call); } return; } - Status::Unstable(gate) => Some(gate), + Status::Unstable { gate, .. } => Some(gate), Status::Forbidden => None, }; @@ -304,7 +308,13 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { self.error_emitted = Some(reported); } - ops::DiagImportance::Secondary => self.secondary_errors.push(err), + ops::DiagImportance::Secondary => { + self.secondary_errors.push(err); + self.tcx.dcx().span_delayed_bug( + span, + "compilation must fail when there is a secondary const checker error", + ); + } } } @@ -569,6 +579,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { ty::FnPtr(..) => { self.check_op(ops::FnCallIndirect); + // We can get here without an error in miri-unleashed mode... might as well + // skip the rest of the checks as well then. return; } _ => { @@ -612,6 +624,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // checks. // FIXME(effects) we might consider moving const stability checks to typeck as well. if tcx.features().effects() { + // This skips the check below that ensures we only call `const fn`. is_trait = true; if let Ok(Some(instance)) = @@ -637,6 +650,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { sym::const_trait_impl }), }); + // If we allowed this, we're in miri-unleashed mode, so we might + // as well skip the remaining checks. return; } } @@ -650,28 +665,72 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // const-eval of the `begin_panic` fn assumes the argument is `&str` if tcx.is_lang_item(callee, LangItem::BeginPanic) { match args[0].node.ty(&self.ccx.body.local_decls, tcx).kind() { - ty::Ref(_, ty, _) if ty.is_str() => return, + ty::Ref(_, ty, _) if ty.is_str() => {} _ => self.check_op(ops::PanicNonStr), } + // Allow this call, skip all the checks below. + return; } // const-eval of `#[rustc_const_panic_str]` functions assumes the argument is `&&str` if tcx.has_attr(callee, sym::rustc_const_panic_str) { match args[0].node.ty(&self.ccx.body.local_decls, tcx).kind() { ty::Ref(_, ty, _) if matches!(ty.kind(), ty::Ref(_, ty, _) if ty.is_str()) => - { - return; + {} + _ => { + self.check_op(ops::PanicNonStr); } - _ => self.check_op(ops::PanicNonStr), } + // Allow this call, skip all the checks below. + return; } // This can be called on stable via the `vec!` macro. if tcx.is_lang_item(callee, LangItem::ExchangeMalloc) { self.check_op(ops::HeapAllocation); + // Allow this call, skip all the checks below. return; } + // Intrinsics are language primitives, not regular calls, so treat them separately. + if let Some(intrinsic) = tcx.intrinsic(callee) { + match tcx.lookup_const_stability(callee) { + None => { + // Non-const intrinsic. + self.check_op(ops::IntrinsicNonConst { name: intrinsic.name }); + } + Some(ConstStability { feature: None, const_stable_indirect, .. }) => { + // Intrinsic does not need a separate feature gate (we rely on the + // regular stability checker). However, we have to worry about recursive + // const stability. + if !const_stable_indirect && self.enforce_recursive_const_stability() { + self.dcx().emit_err(errors::UnmarkedIntrinsicExposed { + span: self.span, + def_path: self.tcx.def_path_str(callee), + }); + } + } + Some(ConstStability { + feature: Some(feature), + level: StabilityLevel::Unstable { .. }, + const_stable_indirect, + .. + }) => { + self.check_op(ops::IntrinsicUnstable { + name: intrinsic.name, + feature, + const_stable_indirect, + }); + } + Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }) => { + // All good. + } + } + // This completes the checks for intrinsics. + return; + } + + // Trait functions are not `const fn` so we have to skip them here. if !tcx.is_const_fn_raw(callee) && !is_trait { self.check_op(ops::FnCallNonConst { caller, @@ -681,66 +740,68 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { call_source, feature: None, }); + // If we allowed this, we're in miri-unleashed mode, so we might + // as well skip the remaining checks. return; } - // If the `const fn` we are trying to call is not const-stable, ensure that we have - // the proper feature gate enabled. - if let Some((gate, implied_by)) = is_unstable_const_fn(tcx, callee) { - trace!(?gate, "calling unstable const fn"); - if self.span.allows_unstable(gate) { - return; + // Finally, stability for regular function calls -- this is the big one. + match tcx.lookup_const_stability(callee) { + Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }) => { + // All good. } - if let Some(implied_by_gate) = implied_by - && self.span.allows_unstable(implied_by_gate) - { - return; + None | Some(ConstStability { feature: None, .. }) => { + // This doesn't need a separate const-stability check -- const-stability equals + // regular stability, and regular stability is checked separately. + // However, we *do* have to worry about *recursive* const stability. + if self.enforce_recursive_const_stability() + && !is_safe_to_expose_on_stable_const_fn(tcx, callee) + { + self.dcx().emit_err(errors::UnmarkedConstFnExposed { + span: self.span, + def_path: self.tcx.def_path_str(callee), + }); + } } + Some(ConstStability { + feature: Some(feature), + level: StabilityLevel::Unstable { implied_by: implied_feature, .. }, + .. + }) => { + // An unstable const fn with a feature gate. + let callee_safe_to_expose_on_stable = + is_safe_to_expose_on_stable_const_fn(tcx, callee); - // Calling an unstable function *always* requires that the corresponding gate - // (or implied gate) be enabled, even if the function has - // `#[rustc_allow_const_fn_unstable(the_gate)]`. - let gate_enabled = |gate| tcx.features().enabled(gate); - let feature_gate_enabled = gate_enabled(gate); - let implied_gate_enabled = implied_by.is_some_and(gate_enabled); - if !feature_gate_enabled && !implied_gate_enabled { - self.check_op(ops::FnCallUnstable(callee, Some(gate))); - return; - } + // We only honor `span.allows_unstable` aka `#[allow_internal_unstable]` if + // the callee is safe to expose, to avoid bypassing recursive stability. + if (self.span.allows_unstable(feature) + || implied_feature.is_some_and(|f| self.span.allows_unstable(f))) + && callee_safe_to_expose_on_stable + { + return; + } - // If this crate is not using stability attributes, or the caller is not claiming to be a - // stable `const fn`, that is all that is required. - if !self.ccx.is_const_stable_const_fn() { - trace!("crate not using stability attributes or caller not stably const"); - return; - } - - // Otherwise, we are something const-stable calling a const-unstable fn. - if super::rustc_allow_const_fn_unstable(tcx, caller, gate) { - trace!("rustc_allow_const_fn_unstable gate enabled"); - return; - } - - self.check_op(ops::FnCallUnstable(callee, Some(gate))); - return; - } - - // FIXME(ecstaticmorse); For compatibility, we consider `unstable` callees that - // have no `rustc_const_stable` attributes to be const-unstable as well. This - // should be fixed later. - let callee_is_unstable_unmarked = tcx.lookup_const_stability(callee).is_none() - && tcx.lookup_stability(callee).is_some_and(|s| s.is_unstable()); - if callee_is_unstable_unmarked { - trace!("callee_is_unstable_unmarked"); - // We do not use `const` modifiers for intrinsic "functions", as intrinsics are - // `extern` functions, and these have no way to get marked `const`. So instead we - // use `rustc_const_(un)stable` attributes to mean that the intrinsic is `const` - if self.ccx.is_const_stable_const_fn() || tcx.intrinsic(callee).is_some() { - self.check_op(ops::FnCallUnstable(callee, None)); - return; + // We can't use `check_op` to check whether the feature is enabled because + // the logic is a bit different than elsewhere: local functions don't need + // the feature gate, and there might be an "implied" gate that also suffices + // to allow this. + let feature_enabled = callee.is_local() + || tcx.features().enabled(feature) + || implied_feature.is_some_and(|f| tcx.features().enabled(f)); + // We do *not* honor this if we are in the "danger zone": we have to enforce + // recursive const-stability and the callee is not safe-to-expose. In that + // case we need `check_op` to do the check. + let danger_zone = !callee_safe_to_expose_on_stable + && self.enforce_recursive_const_stability(); + if danger_zone || !feature_enabled { + self.check_op(ops::FnCallUnstable { + def_id: callee, + feature, + safe_to_expose_on_stable: callee_safe_to_expose_on_stable, + }); + } } } - trace!("permitting call"); } // Forbid all `Drop` terminators unless the place being dropped is a local with no @@ -785,11 +846,13 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { TerminatorKind::InlineAsm { .. } => self.check_op(ops::InlineAsm), - TerminatorKind::Yield { .. } => self.check_op(ops::Coroutine( - self.tcx - .coroutine_kind(self.body.source.def_id()) - .expect("Only expected to have a yield in a coroutine"), - )), + TerminatorKind::Yield { .. } => { + self.check_op(ops::Coroutine( + self.tcx + .coroutine_kind(self.body.source.def_id()) + .expect("Only expected to have a yield in a coroutine"), + )); + } TerminatorKind::CoroutineDrop => { span_bug!( @@ -819,8 +882,19 @@ fn is_int_bool_float_or_char(ty: Ty<'_>) -> bool { ty.is_bool() || ty.is_integral() || ty.is_char() || ty.is_floating_point() } -fn emit_unstable_in_stable_error(ccx: &ConstCx<'_, '_>, span: Span, gate: Symbol) { +fn emit_unstable_in_stable_exposed_error( + ccx: &ConstCx<'_, '_>, + span: Span, + gate: Symbol, + is_function_call: bool, +) -> ErrorGuaranteed { let attr_span = ccx.tcx.def_span(ccx.def_id()).shrink_to_lo(); - ccx.dcx().emit_err(UnstableInStable { gate: gate.to_string(), span, attr_span }); + ccx.dcx().emit_err(errors::UnstableInStableExposed { + gate: gate.to_string(), + span, + attr_span, + is_function_call, + is_function_call2: is_function_call, + }) } diff --git a/compiler/rustc_const_eval/src/check_consts/mod.rs b/compiler/rustc_const_eval/src/check_consts/mod.rs index 3720418d4f01..146b559f2d74 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -59,10 +59,12 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> { self.const_kind.expect("`const_kind` must not be called on a non-const fn") } - pub fn is_const_stable_const_fn(&self) -> bool { + pub fn enforce_recursive_const_stability(&self) -> bool { + // We can skip this if `staged_api` is not enabled, since in such crates + // `lookup_const_stability` will always be `None`. self.const_kind == Some(hir::ConstContext::ConstFn) && self.tcx.features().staged_api() - && is_const_stable_const_fn(self.tcx, self.def_id().to_def_id()) + && is_safe_to_expose_on_stable_const_fn(self.tcx, self.def_id().to_def_id()) } fn is_async(&self) -> bool { @@ -90,50 +92,38 @@ pub fn rustc_allow_const_fn_unstable( attr::rustc_allow_const_fn_unstable(tcx.sess, attrs).any(|name| name == feature_gate) } -/// Returns `true` if the given `const fn` is "const-stable". +/// Returns `true` if the given `const fn` is "safe to expose on stable". /// /// Panics if the given `DefId` does not refer to a `const fn`. /// -/// Const-stability is only relevant for `const fn` within a `staged_api` crate. Only "const-stable" -/// functions can be called in a const-context by users of the stable compiler. "const-stable" -/// functions are subject to more stringent restrictions than "const-unstable" functions: They -/// cannot use unstable features and can only call other "const-stable" functions. -pub fn is_const_stable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - // A default body in a `#[const_trait]` is not const-stable because const - // trait fns currently cannot be const-stable. We shouldn't - // restrict default bodies to only call const-stable functions. +/// This is relevant within a `staged_api` crate. Unlike with normal features, the use of unstable +/// const features *recursively* taints the functions that use them. This is to avoid accidentally +/// exposing e.g. the implementation of an unstable const intrinsic on stable. So we partition the +/// world into two functions: those that are safe to expose on stable (and hence may not use +/// unstable features, not even recursively), and those that are not. +pub fn is_safe_to_expose_on_stable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool { + // A default body in a `#[const_trait]` is not const-stable because const trait fns currently + // cannot be const-stable. These functions can't be called from anything stable, so we shouldn't + // restrict them to only call const-stable functions. if tcx.is_const_default_method(def_id) { + // FIXME(const_trait_impl): we have to eventually allow some of these if these things can ever be stable. + // They should probably behave like regular `const fn` for that... return false; } // Const-stability is only relevant for `const fn`. assert!(tcx.is_const_fn_raw(def_id)); - // A function is only const-stable if it has `#[rustc_const_stable]` or it the trait it belongs - // to is const-stable. match tcx.lookup_const_stability(def_id) { - Some(stab) => stab.is_const_stable(), - None if is_parent_const_stable_trait(tcx, def_id) => { - // Remove this when `#![feature(const_trait_impl)]` is stabilized, - // returning `true` unconditionally. - tcx.dcx().span_delayed_bug( - tcx.def_span(def_id), - "trait implementations cannot be const stable yet", - ); - true + None => { + // Only marked functions can be trusted. Note that this may be a function in a + // non-staged-API crate where no recursive checks were done! + false + } + Some(stab) => { + // We consider things safe-to-expose if they are stable, if they don't have any explicit + // const stability attribute, or if they are marked as `const_stable_indirect`. + stab.is_const_stable() || stab.feature.is_none() || stab.const_stable_indirect } - None => false, // By default, items are not const stable. } } - -fn is_parent_const_stable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - let local_def_id = def_id.expect_local(); - let hir_id = tcx.local_def_id_to_hir_id(local_def_id); - - let parent_owner_id = tcx.parent_hir_id(hir_id).owner; - if !tcx.is_const_trait_impl_raw(parent_owner_id.to_def_id()) { - return false; - } - - tcx.lookup_const_stability(parent_owner_id).is_some_and(|stab| stab.is_const_stable()) -} diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index 5c4a899f28a1..0f151dcdb034 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -26,8 +26,16 @@ use crate::{errors, fluent_generated}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Status { - Allowed, - Unstable(Symbol), + Unstable { + /// The feature that must be enabled to use this operation. + gate: Symbol, + /// Whether it is allowed to use this operation from stable `const fn`. + /// This will usually be `false`. + safe_to_expose_on_stable: bool, + /// We indicate whether this is a function call, since we can use targeted + /// diagnostics for "callee is not safe to expose om stable". + is_function_call: bool, + }, Forbidden, } @@ -40,9 +48,9 @@ pub enum DiagImportance { Secondary, } -/// An operation that is not *always* allowed in a const context. +/// An operation that is *not allowed* in a const context. pub trait NonConstOp<'tcx>: std::fmt::Debug { - /// Returns an enum indicating whether this operation is allowed within the given item. + /// Returns an enum indicating whether this operation can be enabled with a feature gate. fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status { Status::Forbidden } @@ -298,30 +306,78 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { /// /// Contains the name of the feature that would allow the use of this function. #[derive(Debug)] -pub(crate) struct FnCallUnstable(pub DefId, pub Option); +pub(crate) struct FnCallUnstable { + pub def_id: DefId, + pub feature: Symbol, + pub safe_to_expose_on_stable: bool, +} impl<'tcx> NonConstOp<'tcx> for FnCallUnstable { + fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status { + Status::Unstable { + gate: self.feature, + safe_to_expose_on_stable: self.safe_to_expose_on_stable, + is_function_call: true, + } + } + fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - let FnCallUnstable(def_id, feature) = *self; - - let mut err = ccx - .dcx() - .create_err(errors::UnstableConstFn { span, def_path: ccx.tcx.def_path_str(def_id) }); - + let mut err = ccx.dcx().create_err(errors::UnstableConstFn { + span, + def_path: ccx.tcx.def_path_str(self.def_id), + }); // FIXME: make this translatable #[allow(rustc::untranslatable_diagnostic)] - if ccx.is_const_stable_const_fn() { - err.help(fluent_generated::const_eval_const_stable); - } else if ccx.tcx.sess.is_nightly_build() { - if let Some(feature) = feature { - err.help(format!("add `#![feature({feature})]` to the crate attributes to enable")); - } - } + err.help(format!("add `#![feature({})]` to the crate attributes to enable", self.feature)); err } } +/// A call to an intrinsic that is just not const-callable at all. +#[derive(Debug)] +pub(crate) struct IntrinsicNonConst { + pub name: Symbol, +} + +impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst { + fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { + ccx.dcx().create_err(errors::NonConstIntrinsic { + span, + name: self.name, + kind: ccx.const_kind(), + }) + } +} + +/// A call to an intrinsic that is just not const-callable at all. +#[derive(Debug)] +pub(crate) struct IntrinsicUnstable { + pub name: Symbol, + pub feature: Symbol, + pub const_stable_indirect: bool, +} + +impl<'tcx> NonConstOp<'tcx> for IntrinsicUnstable { + fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status { + Status::Unstable { + gate: self.feature, + safe_to_expose_on_stable: self.const_stable_indirect, + // We do *not* want to suggest to mark the intrinsic as `const_stable_indirect`, + // that's not a trivial change! + is_function_call: false, + } + } + + fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { + ccx.dcx().create_err(errors::UnstableIntrinsic { + span, + name: self.name, + feature: self.feature, + }) + } +} + #[derive(Debug)] pub(crate) struct Coroutine(pub hir::CoroutineKind); impl<'tcx> NonConstOp<'tcx> for Coroutine { @@ -331,7 +387,11 @@ impl<'tcx> NonConstOp<'tcx> for Coroutine { hir::CoroutineSource::Block, ) = self.0 { - Status::Unstable(sym::const_async_blocks) + Status::Unstable { + gate: sym::const_async_blocks, + safe_to_expose_on_stable: false, + is_function_call: false, + } } else { Status::Forbidden } diff --git a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs index d04d7b273f03..0173a528c22a 100644 --- a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs @@ -15,7 +15,7 @@ use crate::check_consts::rustc_allow_const_fn_unstable; /// elaboration. pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { // Const-stable functions must always use the stable live drop checker... - if ccx.is_const_stable_const_fn() { + if ccx.enforce_recursive_const_stability() { // ...except if they have the feature flag set via `rustc_allow_const_fn_unstable`. return rustc_allow_const_fn_unstable( ccx.tcx, diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index ca0993f05802..037fdcbcf9b4 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -1,25 +1,8 @@ +use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; -use rustc_span::symbol::Symbol; -use {rustc_attr as attr, rustc_hir as hir}; - -/// Whether the `def_id` is an unstable const fn and what feature gate(s) are necessary to enable -/// it. -pub fn is_unstable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<(Symbol, Option)> { - if tcx.is_const_fn_raw(def_id) { - let const_stab = tcx.lookup_const_stability(def_id)?; - match const_stab.level { - attr::StabilityLevel::Unstable { implied_by, .. } => { - Some((const_stab.feature, implied_by)) - } - attr::StabilityLevel::Stable { .. } => None, - } - } else { - None - } -} pub fn is_parent_const_impl_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { let parent_id = tcx.local_parent(def_id); diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 2db43a0f787e..7793de9c9333 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -219,7 +219,7 @@ impl<'tcx> CompileTimeInterpCx<'tcx> { } /// "Intercept" a function call, because we have something special to do for it. - /// All `#[rustc_do_not_const_check]` functions should be hooked here. + /// All `#[rustc_do_not_const_check]` functions MUST be hooked here. /// If this returns `Some` function, which may be `instance` or a different function with /// compatible arguments, then evaluation should continue with that function. /// If this returns `None`, the function call has been handled and the function has returned. diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index 211668cf055c..38b87b726341 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -14,7 +14,7 @@ use rustc_middle::mir::interpret::{ UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo, }; use rustc_middle::ty::{self, Mutability, Ty}; -use rustc_span::Span; +use rustc_span::{Span, Symbol}; use rustc_target::abi::WrappingRange; use rustc_target::abi::call::AdjustForForeignAbiError; @@ -44,11 +44,15 @@ pub(crate) struct MutablePtrInFinal { } #[derive(Diagnostic)] -#[diag(const_eval_unstable_in_stable)] -pub(crate) struct UnstableInStable { +#[diag(const_eval_unstable_in_stable_exposed)] +pub(crate) struct UnstableInStableExposed { pub gate: String, #[primary_span] pub span: Span, + #[help(const_eval_is_function_call)] + pub is_function_call: bool, + /// Need to duplicate the field so that fluent also provides it as a variable... + pub is_function_call2: bool, #[suggestion( const_eval_unstable_sugg, code = "#[rustc_const_unstable(feature = \"...\", issue = \"...\")]\n", @@ -117,6 +121,34 @@ pub(crate) struct UnstableConstFn { pub def_path: String, } +#[derive(Diagnostic)] +#[diag(const_eval_unstable_intrinsic)] +#[help] +pub(crate) struct UnstableIntrinsic { + #[primary_span] + pub span: Span, + pub name: Symbol, + pub feature: Symbol, +} + +#[derive(Diagnostic)] +#[diag(const_eval_unmarked_const_fn_exposed)] +#[help] +pub(crate) struct UnmarkedConstFnExposed { + #[primary_span] + pub span: Span, + pub def_path: String, +} + +#[derive(Diagnostic)] +#[diag(const_eval_unmarked_intrinsic_exposed)] +#[help] +pub(crate) struct UnmarkedIntrinsicExposed { + #[primary_span] + pub span: Span, + pub def_path: String, +} + #[derive(Diagnostic)] #[diag(const_eval_mutable_ref_escaping, code = E0764)] pub(crate) struct MutableRefEscaping { @@ -153,6 +185,15 @@ pub(crate) struct NonConstFnCall { pub kind: ConstContext, } +#[derive(Diagnostic)] +#[diag(const_eval_non_const_intrinsic)] +pub(crate) struct NonConstIntrinsic { + #[primary_span] + pub span: Span, + pub name: Symbol, + pub kind: ConstContext, +} + #[derive(Diagnostic)] #[diag(const_eval_unallowed_op_in_const_context)] pub(crate) struct UnallowedOpInConstContext { diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index bed500c30324..7e4bc508e5c7 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -866,7 +866,9 @@ impl SyntaxExtension { }) .unwrap_or_else(|| (None, helper_attrs)); let stability = attr::find_stability(sess, attrs, span); - let const_stability = attr::find_const_stability(sess, attrs, span); + // We set `is_const_fn` false to avoid getting any implicit const stability. + let const_stability = + attr::find_const_stability(sess, attrs, span, /* is_const_fn */ false); let body_stability = attr::find_body_stability(sess, attrs); if let Some((_, sp)) = const_stability { sess.dcx().emit_err(errors::MacroConstStability { diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 5921fbc0fd71..0069b07ad625 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -617,11 +617,6 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ DuplicatesOk, EncodeCrossCrate::Yes, "allow_internal_unstable side-steps feature gating and stability checks", ), - gated!( - rustc_allow_const_fn_unstable, Normal, - template!(Word, List: "feat1, feat2, ..."), DuplicatesOk, EncodeCrossCrate::No, - "rustc_allow_const_fn_unstable side-steps feature gating and stability checks" - ), gated!( allow_internal_unsafe, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, "allow_internal_unsafe side-steps the unsafe_code lint", @@ -838,6 +833,15 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ rustc_const_panic_str, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, INTERNAL_UNSTABLE ), + rustc_attr!( + rustc_const_stable_indirect, Normal, + template!(Word), WarnFollowing, EncodeCrossCrate::No, IMPL_DETAIL, + ), + gated!( + rustc_allow_const_fn_unstable, Normal, + template!(Word, List: "feat1, feat2, ..."), DuplicatesOk, EncodeCrossCrate::No, + "rustc_allow_const_fn_unstable side-steps feature gating and stability checks" + ), // ========================================================================== // Internal attributes, Layout related: diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index eab106a44039..1c6a5e9011f4 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -3128,7 +3128,7 @@ impl<'tcx> TyCtxt<'tcx> { Some(stability) if stability.is_const_unstable() => { // has a `rustc_const_unstable` attribute, check whether the user enabled the // corresponding feature gate. - self.features().enabled(stability.feature) + stability.feature.is_some_and(|f| self.features().enabled(f)) } // functions without const stability are either stable user written // const fn or the user is using feature gates and we thus don't diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 3f98236595bd..f8ef423a9b00 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -99,6 +99,10 @@ passes_collapse_debuginfo = passes_confusables = attribute should be applied to an inherent method .label = not an inherent method +passes_const_stable_not_stable = + attribute `#[rustc_const_stable]` can only be applied to functions that are declared `#[stable]` + .label = attribute specified here + passes_continue_labeled_block = `continue` pointing to a labeled block .label = labeled blocks cannot be `continue`'d @@ -465,10 +469,10 @@ passes_may_dangle = `#[may_dangle]` must be applied to a lifetime or type generic parameter in `Drop` impl passes_maybe_string_interpolation = you might have meant to use string interpolation in this string literal + passes_missing_const_err = - attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` + attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` .help = make the function or method const - .label = attribute specified here passes_missing_const_stab_attr = {$descr} has missing const stability attribute diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 042e50d890e9..b5f1eac1cba2 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1574,12 +1574,20 @@ pub(crate) struct DuplicateFeatureErr { pub span: Span, pub feature: Symbol, } + #[derive(Diagnostic)] #[diag(passes_missing_const_err)] pub(crate) struct MissingConstErr { #[primary_span] #[help] pub fn_sig_span: Span, +} + +#[derive(Diagnostic)] +#[diag(passes_const_stable_not_stable)] +pub(crate) struct ConstStableNotStable { + #[primary_span] + pub fn_sig_span: Span, #[label] pub const_span: Span, } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index a176b2bb1ad4..a3165410854c 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -16,7 +16,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId}; use rustc_hir::hir_id::CRATE_HIR_ID; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant}; +use rustc_hir::{Constness, FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures}; use rustc_middle::middle::privacy::EffectiveVisibilities; @@ -27,7 +27,6 @@ use rustc_session::lint; use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED}; use rustc_span::Span; use rustc_span::symbol::{Symbol, sym}; -use rustc_target::spec::abi::Abi; use tracing::{debug, info}; use crate::errors; @@ -107,6 +106,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { def_id: LocalDefId, item_sp: Span, fn_sig: Option<&'tcx hir::FnSig<'tcx>>, + is_foreign_item: bool, kind: AnnotationKind, inherit_deprecation: InheritDeprecation, inherit_const_stability: InheritConstStability, @@ -163,30 +163,62 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } let stab = attr::find_stability(self.tcx.sess, attrs, item_sp); - let const_stab = attr::find_const_stability(self.tcx.sess, attrs, item_sp); + let const_stab = attr::find_const_stability( + self.tcx.sess, + attrs, + item_sp, + fn_sig.is_some_and(|s| s.header.is_const()), + ); let body_stab = attr::find_body_stability(self.tcx.sess, attrs); - let mut const_span = None; - let const_stab = const_stab.map(|(const_stab, const_span_node)| { - self.index.const_stab_map.insert(def_id, const_stab); - const_span = Some(const_span_node); - const_stab - }); - - // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI, - // check if the function/method is const or the parent impl block is const - if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) - && fn_sig.header.abi != Abi::RustIntrinsic + // If the current node is a function with const stability attributes (directly given or + // implied), check if the function/method is const or the parent impl block is const. + if let Some(fn_sig) = fn_sig && !fn_sig.header.is_const() + // We have to exclude foreign items as they might be intrinsics. Sadly we can't check + // their ABI; `fn_sig.abi` is *not* correct for foreign functions. + && !is_foreign_item + && const_stab.is_some() && (!self.in_trait_impl || !self.tcx.is_const_fn_raw(def_id.to_def_id())) + { + self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span }); + } + + // If this is marked const *stable*, it must also be regular-stable. + if let Some((const_stab, const_span)) = const_stab + && let Some(fn_sig) = fn_sig + && const_stab.is_const_stable() + && !stab.is_some_and(|(s, _)| s.is_stable()) { self.tcx .dcx() - .emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span, const_span }); + .emit_err(errors::ConstStableNotStable { fn_sig_span: fn_sig.span, const_span }); } + // Stable *language* features shouldn't be used as unstable library features. + // (Not doing this for stable library features is checked by tidy.) + if let Some(( + ConstStability { level: Unstable { .. }, feature: Some(feature), .. }, + const_span, + )) = const_stab + { + if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { + self.tcx.dcx().emit_err(errors::UnstableAttrForAlreadyStableFeature { + span: const_span, + item_sp, + }); + } + } + + let const_stab = const_stab.map(|(const_stab, _span)| { + self.index.const_stab_map.insert(def_id, const_stab); + const_stab + }); + // `impl const Trait for Type` items forward their const stability to their // immediate children. + // FIXME(effects): how is this supposed to interact with `#[rustc_const_stable_indirect]`? + // Currently, once that is set, we do not inherit anything from the parent any more. if const_stab.is_none() { debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab); if let Some(parent) = self.parent_const_stab { @@ -247,6 +279,8 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } } + // Stable *language* features shouldn't be used as unstable library features. + // (Not doing this for stable library features is checked by tidy.) if let Stability { level: Unstable { .. }, feature } = stab { if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { self.tcx @@ -260,21 +294,13 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { self.index.implications.insert(implied_by, feature); } - if let Some(ConstStability { level: Unstable { .. }, feature, .. }) = const_stab { - if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { - self.tcx.dcx().emit_err(errors::UnstableAttrForAlreadyStableFeature { - span: const_span.unwrap(), // If const_stab contains Some(..), same is true for const_span - item_sp, - }); - } - } if let Some(ConstStability { level: Unstable { implied_by: Some(implied_by), .. }, feature, .. }) = const_stab { - self.index.implications.insert(implied_by, feature); + self.index.implications.insert(implied_by, feature.unwrap()); } self.index.stab_map.insert(def_id, stab); @@ -372,6 +398,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { ctor_def_id, i.span, None, + /* is_foreign_item */ false, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -390,6 +417,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { i.owner_id.def_id, i.span, fn_sig, + /* is_foreign_item */ false, kind, InheritDeprecation::Yes, const_stab_inherit, @@ -409,6 +437,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { ti.owner_id.def_id, ti.span, fn_sig, + /* is_foreign_item */ false, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -432,6 +461,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { ii.owner_id.def_id, ii.span, fn_sig, + /* is_foreign_item */ false, kind, InheritDeprecation::Yes, InheritConstStability::No, @@ -447,6 +477,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { var.def_id, var.span, None, + /* is_foreign_item */ false, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -457,6 +488,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { ctor_def_id, var.span, None, + /* is_foreign_item */ false, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -475,6 +507,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { s.def_id, s.span, None, + /* is_foreign_item */ false, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -486,10 +519,15 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { + let fn_sig = match &i.kind { + rustc_hir::ForeignItemKind::Fn(fn_sig, ..) => Some(fn_sig), + _ => None, + }; self.annotate( i.owner_id.def_id, i.span, - None, + fn_sig, + /* is_foreign_item */ true, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -512,6 +550,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { p.def_id, p.span, None, + /* is_foreign_item */ false, kind, InheritDeprecation::No, InheritConstStability::No, @@ -540,7 +579,9 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { } } - fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) { + fn check_missing_or_wrong_const_stability(&self, def_id: LocalDefId, span: Span) { + // The visitor runs for "unstable-if-unmarked" crates, but we don't yet support + // that on the const side. if !self.tcx.features().staged_api() { return; } @@ -553,11 +594,12 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { return; } - let is_const = self.tcx.is_const_fn(def_id.to_def_id()) + let is_const = self.tcx.is_const_fn_raw(def_id.to_def_id()) || self.tcx.is_const_trait_impl_raw(def_id.to_def_id()); let is_stable = self.tcx.lookup_stability(def_id).is_some_and(|stability| stability.level.is_stable()); - let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none(); + let missing_const_stability_attribute = + self.tcx.lookup_const_stability(def_id).is_none_or(|s| s.feature.is_none()); if is_const && is_stable && missing_const_stability_attribute { let descr = self.tcx.def_descr(def_id.to_def_id()); @@ -587,7 +629,7 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } // Ensure stable `const fn` have a const stability attribute. - self.check_missing_const_stability(i.owner_id.def_id, i.span); + self.check_missing_or_wrong_const_stability(i.owner_id.def_id, i.span); intravisit::walk_item(self, i) } @@ -601,7 +643,7 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id()); if self.tcx.impl_trait_ref(impl_def_id).is_none() { self.check_missing_stability(ii.owner_id.def_id, ii.span); - self.check_missing_const_stability(ii.owner_id.def_id, ii.span); + self.check_missing_or_wrong_const_stability(ii.owner_id.def_id, ii.span); } intravisit::walk_impl_item(self, ii); } @@ -670,6 +712,7 @@ fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index { CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID), None, + /* is_foreign_item */ false, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -732,12 +775,23 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { // For implementations of traits, check the stability of each item // individually as it's possible to have a stable trait with unstable // items. - hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => { + hir::ItemKind::Impl(hir::Impl { + constness, + of_trait: Some(ref t), + self_ty, + items, + .. + }) => { let features = self.tcx.features(); if features.staged_api() { let attrs = self.tcx.hir().attrs(item.hir_id()); let stab = attr::find_stability(self.tcx.sess, attrs, item.span); - let const_stab = attr::find_const_stability(self.tcx.sess, attrs, item.span); + let const_stab = attr::find_const_stability( + self.tcx.sess, + attrs, + item.span, + matches!(constness, Constness::Const), + ); // If this impl block has an #[unstable] attribute, give an // error if all involved types and traits are stable, because diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index bf5f948fe919..134a1a1db305 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1660,6 +1660,7 @@ symbols! { rustc_confusables, rustc_const_panic_str, rustc_const_stable, + rustc_const_stable_indirect, rustc_const_unstable, rustc_conversion_suggestion, rustc_deallocator, diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 45de0617f334..85a9120c7e25 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -103,7 +103,7 @@ impl RawVec { /// `RawVec` with capacity `usize::MAX`. Useful for implementing /// delayed allocation. #[must_use] - #[rustc_const_stable(feature = "raw_vec_internals_const", since = "1.81")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "raw_vec_internals_const", since = "1.81"))] pub const fn new() -> Self { Self::new_in(Global) } @@ -179,7 +179,7 @@ impl RawVec { /// Like `new`, but parameterized over the choice of allocator for /// the returned `RawVec`. #[inline] - #[rustc_const_stable(feature = "raw_vec_internals_const", since = "1.81")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "raw_vec_internals_const", since = "1.81"))] pub const fn new_in(alloc: A) -> Self { Self { inner: RawVecInner::new_in(alloc, align_of::()), _marker: PhantomData } } @@ -409,7 +409,7 @@ unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec { impl RawVecInner { #[inline] - #[rustc_const_stable(feature = "raw_vec_internals_const", since = "1.81")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "raw_vec_internals_const", since = "1.81"))] const fn new_in(alloc: A, align: usize) -> Self { let ptr = unsafe { core::mem::transmute(align) }; // `cap: 0` means "unallocated". zero-sized types are ignored. diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index fca32b9d3c59..95cf9427e02a 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -66,7 +66,6 @@ impl Layout { #[stable(feature = "alloc_layout", since = "1.28.0")] #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")] #[inline] - #[rustc_allow_const_fn_unstable(ptr_alignment_type)] pub const fn from_size_align(size: usize, align: usize) -> Result { if Layout::is_size_align_valid(size, align) { // SAFETY: Layout::is_size_align_valid checks the preconditions for this call. @@ -127,7 +126,6 @@ impl Layout { #[rustc_const_stable(feature = "const_alloc_layout_unchecked", since = "1.36.0")] #[must_use] #[inline] - #[rustc_allow_const_fn_unstable(ptr_alignment_type)] pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self { assert_unsafe_precondition!( check_library_ub, @@ -159,7 +157,7 @@ impl Layout { #[must_use = "this returns the minimum alignment, \ without modifying the layout"] #[inline] - #[rustc_allow_const_fn_unstable(ptr_alignment_type)] + #[cfg_attr(bootstrap, rustc_allow_const_fn_unstable(ptr_alignment_type))] pub const fn align(&self) -> usize { self.align.as_usize() } diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index e1fa43296d02..f5396af2997b 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -2287,6 +2287,7 @@ impl SyncUnsafeCell { /// Unwraps the value, consuming the cell. #[inline] + #[rustc_const_unstable(feature = "sync_unsafe_cell", issue = "95439")] pub const fn into_inner(self) -> T { self.value.into_inner() } diff --git a/library/core/src/cell/lazy.rs b/library/core/src/cell/lazy.rs index d323fbeac9c1..5ac33516684d 100644 --- a/library/core/src/cell/lazy.rs +++ b/library/core/src/cell/lazy.rs @@ -79,6 +79,7 @@ impl T> LazyCell { /// assert_eq!(LazyCell::into_inner(lazy).ok(), Some("HELLO, WORLD!".to_string())); /// ``` #[unstable(feature = "lazy_cell_into_inner", issue = "125623")] + #[rustc_const_unstable(feature = "lazy_cell_into_inner", issue = "125623")] pub const fn into_inner(this: Self) -> Result { match this.state.into_inner() { State::Init(data) => Ok(data), diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index 30c0fff3104c..9c667edb4761 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -1770,7 +1770,7 @@ const fn len_utf16(code: u32) -> usize { /// Panics if the buffer is not large enough. /// A buffer of length four is large enough to encode any `char`. #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] -#[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0"))] #[doc(hidden)] #[inline] #[rustc_allow_const_fn_unstable(const_eval_select)] diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 15b00b9aa442..0f4386190ee4 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -137,11 +137,11 @@ enum FromBytesWithNulErrorKind { // FIXME: const stability attributes should not be required here, I think impl FromBytesWithNulError { - #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0"))] const fn interior_nul(pos: usize) -> FromBytesWithNulError { FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) } } - #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0"))] const fn not_nul_terminated() -> FromBytesWithNulError { FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated } } @@ -730,7 +730,7 @@ impl AsRef for CStr { /// located within `isize::MAX` from `ptr`. #[inline] #[unstable(feature = "cstr_internals", issue = "none")] -#[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0"))] #[rustc_allow_const_fn_unstable(const_eval_select)] const unsafe fn strlen(ptr: *const c_char) -> usize { const fn strlen_ct(s: *const c_char) -> usize { diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 4cbcfb07795b..f3b54230bc1a 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -333,7 +333,10 @@ pub struct Arguments<'a> { #[unstable(feature = "fmt_internals", issue = "none")] impl<'a> Arguments<'a> { #[inline] - #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")] + #[cfg_attr( + bootstrap, + rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none") + )] pub const fn new_const(pieces: &'a [&'static str; N]) -> Self { const { assert!(N <= 1) }; Arguments { pieces, fmt: None, args: &[] } @@ -438,6 +441,7 @@ impl<'a> Arguments<'a> { #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")] #[must_use] #[inline] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] pub const fn as_str(&self) -> Option<&'static str> { match (self.pieces, self.args) { ([], []) => Some(""), diff --git a/library/core/src/hint.rs b/library/core/src/hint.rs index a69f0afdb0a5..78df51f2bc47 100644 --- a/library/core/src/hint.rs +++ b/library/core/src/hint.rs @@ -506,7 +506,7 @@ pub const fn black_box(dummy: T) -> T { /// # } /// ``` #[unstable(feature = "hint_must_use", issue = "94745")] -#[rustc_const_unstable(feature = "hint_must_use", issue = "94745")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "hint_must_use", issue = "94745"))] #[must_use] // <-- :) #[inline(always)] pub const fn must_use(value: T) -> T { diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 97e727633c5f..ff053916d96d 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -14,9 +14,10 @@ //! `#[rustc_const_unstable(feature = "const_such_and_such", issue = "01234")]` to the intrinsic declaration. //! //! If an intrinsic is supposed to be used from a `const fn` with a `rustc_const_stable` attribute, -//! the intrinsic's attribute must be `rustc_const_stable`, too. Such a change should not be done -//! without T-lang consultation, because it bakes a feature into the language that cannot be -//! replicated in user code without compiler support. +//! `#[rustc_const_stable_indirect]` needs to be added to the intrinsic (`#[rustc_const_unstable]` +//! can be removed then). Such a change should not be done without T-lang consultation, because it +//! may bake a feature into the language that cannot be replicated in user code without compiler +//! support. //! //! # Volatiles //! @@ -943,7 +944,11 @@ extern "rust-intrinsic" { /// reach code marked with this function. /// /// The stabilized version of this intrinsic is [`core::hint::unreachable_unchecked`]. - #[rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0")] + #[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0") + )] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unreachable() -> !; } @@ -958,7 +963,8 @@ extern "rust-intrinsic" { /// own, or if it does not enable any significant optimizations. /// /// The stabilized version of this intrinsic is [`core::hint::assert_unchecked`]. -#[rustc_const_stable(feature = "const_assume", since = "1.77.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_assume", since = "1.77.0"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] @@ -980,7 +986,8 @@ pub const unsafe fn assume(b: bool) { /// any safety invariants. /// /// This intrinsic does not have a stable counterpart. -#[rustc_const_unstable(feature = "const_likely", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_likely", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] #[rustc_nounwind] @@ -1000,7 +1007,8 @@ pub const fn likely(b: bool) -> bool { /// any safety invariants. /// /// This intrinsic does not have a stable counterpart. -#[rustc_const_unstable(feature = "const_likely", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_likely", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] #[rustc_nounwind] @@ -1041,7 +1049,8 @@ extern "rust-intrinsic" { /// This will statically either panic, or do nothing. /// /// This intrinsic does not have a stable counterpart. - #[rustc_const_stable(feature = "const_assert_type", since = "1.59.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_assert_type", since = "1.59.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn assert_inhabited(); @@ -1050,7 +1059,8 @@ extern "rust-intrinsic" { /// zero-initialization: This will statically either panic, or do nothing. /// /// This intrinsic does not have a stable counterpart. - #[rustc_const_stable(feature = "const_assert_type2", since = "1.75.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_assert_type2", since = "1.75.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn assert_zero_valid(); @@ -1058,7 +1068,8 @@ extern "rust-intrinsic" { /// A guard for `std::mem::uninitialized`. This will statically either panic, or do nothing. /// /// This intrinsic does not have a stable counterpart. - #[rustc_const_stable(feature = "const_assert_type2", since = "1.75.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_assert_type2", since = "1.75.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn assert_mem_uninitialized_valid(); @@ -1071,7 +1082,8 @@ extern "rust-intrinsic" { /// any safety invariants. /// /// Consider using [`core::panic::Location::caller`] instead. - #[rustc_const_stable(feature = "const_caller_location", since = "1.79.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_caller_location", since = "1.79.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn caller_location() -> &'static crate::panic::Location<'static>; @@ -1085,7 +1097,8 @@ extern "rust-intrinsic" { /// it does not require an `unsafe` block. /// Therefore, implementations must not require the user to uphold /// any safety invariants. - #[rustc_const_stable(feature = "const_intrinsic_forget", since = "1.83.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_intrinsic_forget", since = "1.83.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn forget(_: T); @@ -1391,7 +1404,8 @@ extern "rust-intrinsic" { /// /// This is not expected to ever be exposed directly to users, rather it /// may eventually be exposed through some more-constrained API. - #[rustc_const_stable(feature = "const_transmute", since = "1.56.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_transmute", since = "1.56.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn transmute_unchecked(src: Src) -> Dst; @@ -1408,7 +1422,8 @@ extern "rust-intrinsic" { /// any safety invariants. /// /// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop). - #[rustc_const_stable(feature = "const_needs_drop", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_needs_drop", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn needs_drop() -> bool; @@ -1430,7 +1445,8 @@ extern "rust-intrinsic" { /// /// The stabilized version of this intrinsic is [`pointer::offset`]. #[must_use = "returns a new pointer rather than modifying its argument"] - #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn offset(dst: Ptr, offset: Delta) -> Ptr; @@ -1448,7 +1464,8 @@ extern "rust-intrinsic" { /// /// The stabilized version of this intrinsic is [`pointer::wrapping_offset`]. #[must_use = "returns a new pointer rather than modifying its argument"] - #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn arith_offset(dst: *const T, offset: isize) -> *const T; @@ -2131,7 +2148,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `count_ones` method. For example, /// [`u32::count_ones`] - #[rustc_const_stable(feature = "const_ctpop", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ctpop", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn ctpop(x: T) -> u32; @@ -2172,7 +2190,8 @@ extern "rust-intrinsic" { /// let num_leading = ctlz(x); /// assert_eq!(num_leading, 16); /// ``` - #[rustc_const_stable(feature = "const_ctlz", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ctlz", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn ctlz(x: T) -> u32; @@ -2194,7 +2213,8 @@ extern "rust-intrinsic" { /// let num_leading = unsafe { ctlz_nonzero(x) }; /// assert_eq!(num_leading, 3); /// ``` - #[rustc_const_stable(feature = "constctlz", since = "1.50.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "constctlz", since = "1.50.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn ctlz_nonzero(x: T) -> u32; @@ -2234,7 +2254,8 @@ extern "rust-intrinsic" { /// let num_trailing = cttz(x); /// assert_eq!(num_trailing, 16); /// ``` - #[rustc_const_stable(feature = "const_cttz", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_cttz", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn cttz(x: T) -> u32; @@ -2256,7 +2277,8 @@ extern "rust-intrinsic" { /// let num_trailing = unsafe { cttz_nonzero(x) }; /// assert_eq!(num_trailing, 3); /// ``` - #[rustc_const_stable(feature = "const_cttz_nonzero", since = "1.53.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_cttz_nonzero", since = "1.53.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn cttz_nonzero(x: T) -> u32; @@ -2270,7 +2292,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `swap_bytes` method. For example, /// [`u32::swap_bytes`] - #[rustc_const_stable(feature = "const_bswap", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_bswap", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn bswap(x: T) -> T; @@ -2285,7 +2308,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `reverse_bits` method. For example, /// [`u32::reverse_bits`] - #[rustc_const_stable(feature = "const_bitreverse", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_bitreverse", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn bitreverse(x: T) -> T; @@ -2311,7 +2335,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `overflowing_add` method. For example, /// [`u32::overflowing_add`] - #[rustc_const_stable(feature = "const_int_overflow", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_overflow", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn add_with_overflow(x: T, y: T) -> (T, bool); @@ -2326,7 +2351,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `overflowing_sub` method. For example, /// [`u32::overflowing_sub`] - #[rustc_const_stable(feature = "const_int_overflow", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_overflow", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn sub_with_overflow(x: T, y: T) -> (T, bool); @@ -2341,7 +2367,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `overflowing_mul` method. For example, /// [`u32::overflowing_mul`] - #[rustc_const_stable(feature = "const_int_overflow", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_overflow", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn mul_with_overflow(x: T, y: T) -> (T, bool); @@ -2360,7 +2387,11 @@ extern "rust-intrinsic" { /// Safe wrappers for this intrinsic are available on the integer /// primitives via the `checked_div` method. For example, /// [`u32::checked_div`] - #[rustc_const_stable(feature = "const_int_unchecked_div", since = "1.52.0")] + #[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_int_unchecked_div", since = "1.52.0") + )] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_div(x: T, y: T) -> T; /// Returns the remainder of an unchecked division, resulting in @@ -2369,7 +2400,11 @@ extern "rust-intrinsic" { /// Safe wrappers for this intrinsic are available on the integer /// primitives via the `checked_rem` method. For example, /// [`u32::checked_rem`] - #[rustc_const_stable(feature = "const_int_unchecked_rem", since = "1.52.0")] + #[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_int_unchecked_rem", since = "1.52.0") + )] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_rem(x: T, y: T) -> T; @@ -2379,7 +2414,8 @@ extern "rust-intrinsic" { /// Safe wrappers for this intrinsic are available on the integer /// primitives via the `checked_shl` method. For example, /// [`u32::checked_shl`] - #[rustc_const_stable(feature = "const_int_unchecked", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_unchecked", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_shl(x: T, y: U) -> T; /// Performs an unchecked right shift, resulting in undefined behavior when @@ -2388,7 +2424,8 @@ extern "rust-intrinsic" { /// Safe wrappers for this intrinsic are available on the integer /// primitives via the `checked_shr` method. For example, /// [`u32::checked_shr`] - #[rustc_const_stable(feature = "const_int_unchecked", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_unchecked", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_shr(x: T, y: U) -> T; @@ -2397,7 +2434,8 @@ extern "rust-intrinsic" { /// /// The stable counterpart of this intrinsic is `unchecked_add` on the various /// integer types, such as [`u16::unchecked_add`] and [`i64::unchecked_add`]. - #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "unchecked_math", since = "1.79.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_add(x: T, y: T) -> T; @@ -2406,7 +2444,8 @@ extern "rust-intrinsic" { /// /// The stable counterpart of this intrinsic is `unchecked_sub` on the various /// integer types, such as [`u16::unchecked_sub`] and [`i64::unchecked_sub`]. - #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "unchecked_math", since = "1.79.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_sub(x: T, y: T) -> T; @@ -2415,7 +2454,8 @@ extern "rust-intrinsic" { /// /// The stable counterpart of this intrinsic is `unchecked_mul` on the various /// integer types, such as [`u16::unchecked_mul`] and [`i64::unchecked_mul`]. - #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "unchecked_math", since = "1.79.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn unchecked_mul(x: T, y: T) -> T; @@ -2429,7 +2469,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `rotate_left` method. For example, /// [`u32::rotate_left`] - #[rustc_const_stable(feature = "const_int_rotate", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_rotate", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn rotate_left(x: T, shift: u32) -> T; @@ -2444,7 +2485,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `rotate_right` method. For example, /// [`u32::rotate_right`] - #[rustc_const_stable(feature = "const_int_rotate", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_rotate", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn rotate_right(x: T, shift: u32) -> T; @@ -2459,7 +2501,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `wrapping_add` method. For example, /// [`u32::wrapping_add`] - #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn wrapping_add(a: T, b: T) -> T; @@ -2473,7 +2516,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `wrapping_sub` method. For example, /// [`u32::wrapping_sub`] - #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn wrapping_sub(a: T, b: T) -> T; @@ -2487,7 +2531,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `wrapping_mul` method. For example, /// [`u32::wrapping_mul`] - #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn wrapping_mul(a: T, b: T) -> T; @@ -2502,7 +2547,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `saturating_add` method. For example, /// [`u32::saturating_add`] - #[rustc_const_stable(feature = "const_int_saturating", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_saturating", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn saturating_add(a: T, b: T) -> T; @@ -2516,7 +2562,8 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `saturating_sub` method. For example, /// [`u32::saturating_sub`] - #[rustc_const_stable(feature = "const_int_saturating", since = "1.40.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_saturating", since = "1.40.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn saturating_sub(a: T, b: T) -> T; @@ -2527,7 +2574,8 @@ extern "rust-intrinsic" { /// This intrinsic can *only* be called where the pointer is a local without /// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it /// trivially obeys runtime-MIR rules about derefs in operands. - #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ptr_read", since = "1.71.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn read_via_copy(ptr: *const T) -> T; @@ -2537,7 +2585,8 @@ extern "rust-intrinsic" { /// This intrinsic can *only* be called where the pointer is a local without /// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so /// that it trivially obeys runtime-MIR rules about derefs in operands. - #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ptr_write", since = "1.83.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn write_via_move(ptr: *mut T, value: T); @@ -2550,7 +2599,8 @@ extern "rust-intrinsic" { /// any safety invariants. /// /// The stabilized version of this intrinsic is [`core::mem::discriminant`]. - #[rustc_const_stable(feature = "const_discriminant", since = "1.75.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_discriminant", since = "1.75.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_safe_intrinsic] #[rustc_nounwind] pub fn discriminant_value(v: &T) -> ::Discriminant; @@ -2584,7 +2634,8 @@ extern "rust-intrinsic" { pub fn nontemporal_store(ptr: *mut T, val: T); /// See documentation of `<*const T>::offset_from` for details. - #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn ptr_offset_from(ptr: *const T, base: *const T) -> isize; @@ -2850,7 +2901,8 @@ pub const unsafe fn typed_swap(x: *mut T, y: *mut T) { /// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the /// user has UB checks disabled, the checks will still get optimized out. This intrinsic is /// primarily used by [`ub_checks::assert_unsafe_precondition`]. -#[rustc_const_unstable(feature = "const_ub_checks", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_ub_checks", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // just for UB checks #[unstable(feature = "core_intrinsics", issue = "none")] #[inline(always)] #[rustc_intrinsic] @@ -2935,7 +2987,8 @@ pub unsafe fn vtable_align(_ptr: *const ()) -> usize { /// The stabilized version of this intrinsic is [`core::mem::size_of`]. #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] -#[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_size_of", since = "1.40.0"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] pub const fn size_of() -> usize { @@ -2952,7 +3005,8 @@ pub const fn size_of() -> usize { /// The stabilized version of this intrinsic is [`core::mem::align_of`]. #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] -#[rustc_const_stable(feature = "const_min_align_of", since = "1.40.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_min_align_of", since = "1.40.0"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] pub const fn min_align_of() -> usize { @@ -3065,7 +3119,8 @@ pub const fn type_id() -> u128 { /// change the possible layouts of pointers. #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] -#[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] pub const fn aggregate_raw_ptr, D, M>(_data: D, _meta: M) -> P { @@ -3090,7 +3145,11 @@ impl AggregateRawPtr<*mut T> for *mut P { /// This is used to implement functions like `ptr::metadata`. #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] -#[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] +#[cfg_attr( + bootstrap, + cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")) +)] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] pub const fn ptr_metadata + ?Sized, M>(_ptr: *const P) -> M { @@ -3197,7 +3256,15 @@ pub const fn ptr_metadata + ?Sized, M>(_ptr: *cons #[rustc_diagnostic_item = "ptr_copy_nonoverlapping"] pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize) { extern "rust-intrinsic" { - #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")] + #[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0") + )] + #[cfg_attr( + not(bootstrap), + rustc_const_unstable(feature = "core_intrinsics", issue = "none") + )] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] pub fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); } @@ -3301,7 +3368,15 @@ pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: us #[rustc_diagnostic_item = "ptr_copy"] pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { extern "rust-intrinsic" { - #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")] + #[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0") + )] + #[cfg_attr( + not(bootstrap), + rustc_const_unstable(feature = "core_intrinsics", issue = "none") + )] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] fn copy(src: *const T, dst: *mut T, count: usize); } @@ -3382,7 +3457,8 @@ pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { #[rustc_diagnostic_item = "ptr_write_bytes"] pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize) { extern "rust-intrinsic" { - #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_ptr_write", since = "1.83.0"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[rustc_nounwind] fn write_bytes(dst: *mut T, val: u8, count: usize); } @@ -3643,6 +3719,7 @@ pub const unsafe fn copysignf128(_x: f128, _y: f128) -> f128 { /// Inform Miri that a given pointer definitely has a certain alignment. #[cfg(miri)] +#[rustc_allow_const_fn_unstable(const_eval_select)] pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) { extern "Rust" { /// Miri-provided extern function to promise that a given pointer is properly aligned for diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index 86660f2e375c..2cf2ea58fd4e 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -346,7 +346,6 @@ pub trait IntoIterator { fn into_iter(self) -> Self::IntoIter; } -#[rustc_const_unstable(feature = "const_intoiterator_identity", issue = "90603")] #[stable(feature = "rust1", since = "1.0.0")] impl IntoIterator for I { type Item = I::Item; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 168775667651..9c3bf8274381 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -107,6 +107,7 @@ // // Library features: // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(const_fmt_arguments_new))] #![feature(array_ptr_get)] #![feature(asm_experimental_arch)] #![feature(const_align_of_val)] @@ -121,11 +122,8 @@ #![feature(const_eval_select)] #![feature(const_exact_div)] #![feature(const_float_methods)] -#![feature(const_fmt_arguments_new)] #![feature(const_hash)] #![feature(const_heap)] -#![feature(const_index_range_slice_index)] -#![feature(const_likely)] #![feature(const_nonnull_new)] #![feature(const_num_midpoint)] #![feature(const_option_ext)] @@ -144,6 +142,7 @@ #![feature(const_typed_swap)] #![feature(const_ub_checks)] #![feature(const_unicode_case_lookup)] +#![feature(core_intrinsics)] #![feature(coverage_attribute)] #![feature(do_not_recommend)] #![feature(internal_impls_macro)] @@ -159,6 +158,7 @@ #![feature(ptr_alignment_type)] #![feature(ptr_metadata)] #![feature(set_ptr_value)] +#![feature(slice_as_chunks)] #![feature(slice_ptr_get)] #![feature(str_internals)] #![feature(str_split_inclusive_remainder)] diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index d3360c182071..0d1f4a9ea3ee 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -373,6 +373,7 @@ impl IpAddr { /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0)).is_benchmarking(), true); /// ``` #[unstable(feature = "ip", issue = "27709")] + #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")] #[must_use] #[inline] pub const fn is_benchmarking(&self) -> bool { diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 5ab2ab50d7c6..e8161cce2fe2 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -288,7 +288,6 @@ impl f128 { // concerns about portability, so this implementation is for // private use internally. #[inline] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub(crate) const fn abs_private(self) -> f128 { // SAFETY: This transmutation is fine just like in `to_bits`/`from_bits`. unsafe { @@ -319,7 +318,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn is_infinite(self) -> bool { (self == f128::INFINITY) | (self == f128::NEG_INFINITY) } @@ -346,7 +344,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn is_finite(self) -> bool { // There's no need to handle NaN separately: if self is NaN, // the comparison is not true, exactly as desired. @@ -380,7 +377,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn is_subnormal(self) -> bool { matches!(self.classify(), FpCategory::Subnormal) } @@ -412,7 +408,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn is_normal(self) -> bool { matches!(self.classify(), FpCategory::Normal) } @@ -437,7 +432,6 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn classify(self) -> FpCategory { let bits = self.to_bits(); match (bits & Self::MAN_MASK, bits & Self::EXP_MASK) { @@ -915,7 +909,6 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_bits(self) -> u128 { // SAFETY: `u128` is a plain old datatype so we can always transmute to it. @@ -964,7 +957,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn from_bits(v: u128) -> Self { // It turns out the safety issues with sNaN were overblown! Hooray! // SAFETY: `u128` is a plain old datatype so we can always transmute from it. @@ -991,7 +983,6 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_be_bytes(self) -> [u8; 16] { self.to_bits().to_be_bytes() @@ -1017,7 +1008,6 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_le_bytes(self) -> [u8; 16] { self.to_bits().to_le_bytes() @@ -1054,7 +1044,6 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_ne_bytes(self) -> [u8; 16] { self.to_bits().to_ne_bytes() @@ -1082,7 +1071,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn from_be_bytes(bytes: [u8; 16]) -> Self { Self::from_bits(u128::from_be_bytes(bytes)) } @@ -1109,7 +1097,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn from_le_bytes(bytes: [u8; 16]) -> Self { Self::from_bits(u128::from_le_bytes(bytes)) } @@ -1146,7 +1133,6 @@ impl f128 { #[inline] #[must_use] #[unstable(feature = "f128", issue = "116909")] - #[rustc_const_unstable(feature = "f128", issue = "116909")] pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self { Self::from_bits(u128::from_ne_bytes(bytes)) } diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index 60a88496696c..8b3f3b7d19bf 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -282,7 +282,6 @@ impl f16 { // concerns about portability, so this implementation is for // private use internally. #[inline] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub(crate) const fn abs_private(self) -> f16 { // SAFETY: This transmutation is fine just like in `to_bits`/`from_bits`. unsafe { mem::transmute::(mem::transmute::(self) & !Self::SIGN_MASK) } @@ -310,7 +309,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn is_infinite(self) -> bool { (self == f16::INFINITY) | (self == f16::NEG_INFINITY) } @@ -336,7 +334,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn is_finite(self) -> bool { // There's no need to handle NaN separately: if self is NaN, // the comparison is not true, exactly as desired. @@ -368,7 +365,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn is_subnormal(self) -> bool { matches!(self.classify(), FpCategory::Subnormal) } @@ -398,7 +394,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn is_normal(self) -> bool { matches!(self.classify(), FpCategory::Normal) } @@ -422,7 +417,6 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn classify(self) -> FpCategory { let b = self.to_bits(); match (b & Self::MAN_MASK, b & Self::EXP_MASK) { @@ -901,7 +895,6 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_bits(self) -> u16 { // SAFETY: `u16` is a plain old datatype so we can always transmute to it. @@ -949,7 +942,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn from_bits(v: u16) -> Self { // It turns out the safety issues with sNaN were overblown! Hooray! // SAFETY: `u16` is a plain old datatype so we can always transmute from it. @@ -975,7 +967,6 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_be_bytes(self) -> [u8; 2] { self.to_bits().to_be_bytes() @@ -1000,7 +991,6 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_le_bytes(self) -> [u8; 2] { self.to_bits().to_le_bytes() @@ -1038,7 +1028,6 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub const fn to_ne_bytes(self) -> [u8; 2] { self.to_bits().to_ne_bytes() @@ -1062,7 +1051,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn from_be_bytes(bytes: [u8; 2]) -> Self { Self::from_bits(u16::from_be_bytes(bytes)) } @@ -1085,7 +1073,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn from_le_bytes(bytes: [u8; 2]) -> Self { Self::from_bits(u16::from_le_bytes(bytes)) } @@ -1119,7 +1106,6 @@ impl f16 { #[inline] #[must_use] #[unstable(feature = "f16", issue = "116909")] - #[rustc_const_unstable(feature = "f16", issue = "116909")] pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self { Self::from_bits(u16::from_ne_bytes(bytes)) } diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 5e2f45884dd7..05ecfe431d02 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -16,7 +16,7 @@ macro_rules! try_opt { }; } -#[allow_internal_unstable(const_likely)] +#[cfg_attr(bootstrap, allow_internal_unstable(const_likely))] macro_rules! unlikely { ($e: expr) => { intrinsics::unlikely($e) @@ -1397,7 +1397,7 @@ from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 } #[doc(hidden)] #[inline(always)] #[unstable(issue = "none", feature = "std_internals")] -#[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_from_str", since = "1.82.0"))] pub const fn can_not_overflow(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool { radix <= 16 && digits.len() <= mem::size_of::() * 2 - is_signed_ty as usize } @@ -1416,6 +1416,7 @@ fn from_str_radix_panic_rt(radix: u32) -> ! { #[cfg_attr(feature = "panic_immediate_abort", inline)] #[cold] #[track_caller] +#[rustc_allow_const_fn_unstable(const_eval_select)] const fn from_str_radix_panic(radix: u32) { // The only difference between these two functions is their panic message. intrinsics::const_eval_select((radix,), from_str_radix_panic_ct, from_str_radix_panic_rt); diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index d9036abecc59..8e62fd85912d 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -3009,7 +3009,7 @@ macro_rules! uint_impl { // overflow cases it instead ends up returning the maximum value // of the type, and can return 0 for 0. #[inline] - #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_int_pow", since = "1.50.0"))] const fn one_less_than_next_power_of_two(self) -> Self { if self <= 1 { return 0; } diff --git a/library/core/src/panic/panic_info.rs b/library/core/src/panic/panic_info.rs index af2c83b54607..1d950eb36250 100644 --- a/library/core/src/panic/panic_info.rs +++ b/library/core/src/panic/panic_info.rs @@ -168,6 +168,7 @@ impl<'a> PanicMessage<'a> { #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")] #[must_use] #[inline] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] pub const fn as_str(&self) -> Option<&'static str> { self.message.as_str() } diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 7420579e3ce9..9071d6719a30 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -50,7 +50,8 @@ const _: () = assert!(cfg!(panic = "abort"), "panic_immediate_abort requires -C #[track_caller] #[lang = "panic_fmt"] // needed for const-evaluated panics #[rustc_do_not_const_check] // hooked by const-eval -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! { if cfg!(feature = "panic_immediate_abort") { super::intrinsics::abort() @@ -84,7 +85,9 @@ pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! { // and unwinds anyway, we will hit the "unwinding out of nounwind function" guard, // which causes a "panic in a function that cannot unwind". #[rustc_nounwind] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable +#[rustc_allow_const_fn_unstable(const_eval_select)] pub const fn panic_nounwind_fmt(fmt: fmt::Arguments<'_>, force_no_backtrace: bool) -> ! { #[inline] // this should always be inlined into `panic_nounwind_fmt` #[track_caller] @@ -131,7 +134,8 @@ pub const fn panic_nounwind_fmt(fmt: fmt::Arguments<'_>, force_no_backtrace: boo #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] #[cfg_attr(feature = "panic_immediate_abort", inline)] #[track_caller] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable #[lang = "panic"] // used by lints and miri for panics pub const fn panic(expr: &'static str) -> ! { // Use Arguments::new_const instead of format_args!("{expr}") to potentially @@ -169,7 +173,8 @@ macro_rules! panic_const { #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] #[cfg_attr(feature = "panic_immediate_abort", inline)] #[track_caller] - #[rustc_const_unstable(feature = "panic_internals", issue = "none")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] + #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable #[lang = stringify!($lang)] pub const fn $lang() -> ! { // Use Arguments::new_const instead of format_args!("{expr}") to potentially @@ -216,7 +221,8 @@ panic_const! { #[cfg_attr(feature = "panic_immediate_abort", inline)] #[lang = "panic_nounwind"] // needed by codegen for non-unwinding panics #[rustc_nounwind] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable pub const fn panic_nounwind(expr: &'static str) -> ! { panic_nounwind_fmt(fmt::Arguments::new_const(&[expr]), /* force_no_backtrace */ false); } @@ -232,7 +238,8 @@ pub fn panic_nounwind_nobacktrace(expr: &'static str) -> ! { #[track_caller] #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] #[cfg_attr(feature = "panic_immediate_abort", inline)] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable pub const fn panic_explicit() -> ! { panic_display(&"explicit panic"); } @@ -249,7 +256,8 @@ pub fn unreachable_display(x: &T) -> ! { #[inline] #[track_caller] #[rustc_diagnostic_item = "panic_str_2015"] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable pub const fn panic_str_2015(expr: &str) -> ! { panic_display(&expr); } @@ -259,7 +267,8 @@ pub const fn panic_str_2015(expr: &str) -> ! { #[rustc_do_not_const_check] // hooked by const-eval // enforce a &&str argument in const-check and hook this by const-eval #[rustc_const_panic_str] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable pub const fn panic_display(x: &T) -> ! { panic_fmt(format_args!("{}", *x)); } @@ -327,8 +336,9 @@ fn panic_in_cleanup() -> ! { } /// This function is used instead of panic_fmt in const eval. -#[lang = "const_panic_fmt"] -#[rustc_const_unstable(feature = "panic_internals", issue = "none")] +#[lang = "const_panic_fmt"] // needed by const-eval machine to replace calls to `panic_fmt` lang item +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "panic_internals", issue = "none"))] +#[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] // must follow stable const rules since it is exposed to stable pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! { if let Some(msg) = fmt.as_str() { // The panic_display function is hooked by const eval. diff --git a/library/core/src/ptr/alignment.rs b/library/core/src/ptr/alignment.rs index 50706fca5b0f..2538d60a8eee 100644 --- a/library/core/src/ptr/alignment.rs +++ b/library/core/src/ptr/alignment.rs @@ -41,7 +41,7 @@ impl Alignment { /// This provides the same numerical value as [`mem::align_of`], /// but in an `Alignment` instead of a `usize`. #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const fn of() -> Self { // SAFETY: rustc ensures that type alignment is always a power of two. @@ -53,7 +53,7 @@ impl Alignment { /// /// Note that `0` is not a power of two, nor a valid alignment. #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const fn new(align: usize) -> Option { if align.is_power_of_two() { @@ -73,7 +73,7 @@ impl Alignment { /// Equivalently, it must be `1 << exp` for some `exp` in `0..usize::BITS`. /// It must *not* be zero. #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const unsafe fn new_unchecked(align: usize) -> Self { assert_unsafe_precondition!( @@ -89,7 +89,7 @@ impl Alignment { /// Returns the alignment as a [`usize`]. #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const fn as_usize(self) -> usize { self.0 as usize @@ -97,7 +97,7 @@ impl Alignment { /// Returns the alignment as a [NonZero]<[usize]>. #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const fn as_nonzero(self) -> NonZero { // SAFETY: All the discriminants are non-zero. @@ -118,7 +118,7 @@ impl Alignment { /// assert_eq!(Alignment::new(1024).unwrap().log2(), 10); /// ``` #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const fn log2(self) -> u32 { self.as_nonzero().trailing_zeros() @@ -148,7 +148,7 @@ impl Alignment { /// assert_ne!(one.mask(Alignment::of::().mask()), one); /// ``` #[unstable(feature = "ptr_alignment_type", issue = "102070")] - #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070"))] #[inline] pub const fn mask(self) -> usize { // SAFETY: The alignment is always nonzero, and therefore decrementing won't overflow. diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index facf38894d3b..75d681d76dfd 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -39,6 +39,7 @@ impl *const T { } #[inline] + #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")] const fn const_impl(ptr: *const u8) -> bool { match (ptr).guaranteed_eq(null_mut()) { Some(res) => res, @@ -113,7 +114,7 @@ impl *const T { /// println!("{:?}", unsafe { &*bad }); /// ``` #[unstable(feature = "set_ptr_value", issue = "75091")] - #[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0"))] #[must_use = "returns a new pointer rather than modifying its argument"] #[inline] pub const fn with_metadata_of(self, meta: *const U) -> *const U @@ -409,6 +410,7 @@ impl *const T { T: Sized, { #[inline] + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool { #[inline] fn runtime(this: *const (), count: isize, size: usize) -> bool { @@ -761,6 +763,7 @@ impl *const T { where T: Sized, { + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_ptr_ge(this: *const (), origin: *const ()) -> bool { fn runtime(this: *const (), origin: *const ()) -> bool { this >= origin @@ -902,6 +905,7 @@ impl *const T { { #[cfg(debug_assertions)] #[inline] + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool { #[inline] fn runtime(this: *const (), count: usize, size: usize) -> bool { @@ -1010,6 +1014,7 @@ impl *const T { { #[cfg(debug_assertions)] #[inline] + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool { #[inline] fn runtime(this: *const (), count: usize, size: usize) -> bool { @@ -1622,6 +1627,7 @@ impl *const T { } #[inline] + #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")] const fn const_impl(ptr: *const (), align: usize) -> bool { // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead. ptr.align_offset(align) == 0 diff --git a/library/core/src/ptr/metadata.rs b/library/core/src/ptr/metadata.rs index 09c4002dbc76..5f20cb2ee720 100644 --- a/library/core/src/ptr/metadata.rs +++ b/library/core/src/ptr/metadata.rs @@ -92,7 +92,7 @@ pub trait Thin = Pointee; /// /// assert_eq!(std::ptr::metadata("foo"), 3_usize); /// ``` -#[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0"))] #[inline] pub const fn metadata(ptr: *const T) -> ::Metadata { ptr_metadata(ptr) @@ -106,7 +106,7 @@ pub const fn metadata(ptr: *const T) -> ::Metadata { /// /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts #[unstable(feature = "ptr_metadata", issue = "81513")] -#[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0"))] #[inline] pub const fn from_raw_parts( data_pointer: *const impl Thin, @@ -120,7 +120,7 @@ pub const fn from_raw_parts( /// /// See the documentation of [`from_raw_parts`] for more details. #[unstable(feature = "ptr_metadata", issue = "81513")] -#[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0"))] #[inline] pub const fn from_raw_parts_mut( data_pointer: *mut impl Thin, diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 03cab232742a..ee04cafb8a15 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -591,8 +591,8 @@ pub const fn null_mut() -> *mut T { /// This is a [Strict Provenance][crate::ptr#strict-provenance] API. #[inline(always)] #[must_use] -#[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")] #[stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] pub const fn without_provenance(addr: usize) -> *const T { // An int-to-pointer transmute currently has exactly the intended semantics: it creates a // pointer without provenance. Note that this is *not* a stable guarantee about transmute @@ -613,8 +613,8 @@ pub const fn without_provenance(addr: usize) -> *const T { /// some other means. #[inline(always)] #[must_use] -#[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")] #[stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] pub const fn dangling() -> *const T { without_provenance(mem::align_of::()) } @@ -634,8 +634,8 @@ pub const fn dangling() -> *const T { /// This is a [Strict Provenance][crate::ptr#strict-provenance] API. #[inline(always)] #[must_use] -#[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")] #[stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] pub const fn without_provenance_mut(addr: usize) -> *mut T { // An int-to-pointer transmute currently has exactly the intended semantics: it creates a // pointer without provenance. Note that this is *not* a stable guarantee about transmute @@ -656,8 +656,8 @@ pub const fn without_provenance_mut(addr: usize) -> *mut T { /// some other means. #[inline(always)] #[must_use] -#[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")] #[stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "strict_provenance", since = "CURRENT_RUSTC_VERSION")] pub const fn dangling_mut() -> *mut T { without_provenance_mut(mem::align_of::()) } @@ -1854,6 +1854,7 @@ pub unsafe fn write_volatile(dst: *mut T, src: T) { /// Any questions go to @nagisa. #[allow(ptr_to_integer_transmute_in_consts)] #[lang = "align_offset"] +#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")] pub(crate) const unsafe fn align_offset(p: *const T, a: usize) -> usize { // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <= // 1, where the method versions of these operations are not inlined. diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 031939cf0d51..408e722267a0 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -94,7 +94,7 @@ impl *mut T { /// // This dereference is UB. The pointer only has provenance for `x` but points to `y`. /// println!("{:?}", unsafe { &*bad }); #[unstable(feature = "set_ptr_value", issue = "75091")] - #[rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "ptr_metadata_const", since = "1.83.0"))] #[must_use = "returns a new pointer rather than modifying its argument"] #[inline] pub const fn with_metadata_of(self, meta: *const U) -> *mut U @@ -405,6 +405,7 @@ impl *mut T { T: Sized, { #[inline] + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool { #[inline] fn runtime(this: *const (), count: isize, size: usize) -> bool { @@ -984,6 +985,7 @@ impl *mut T { { #[cfg(debug_assertions)] #[inline] + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool { #[inline] fn runtime(this: *const (), count: usize, size: usize) -> bool { @@ -1092,6 +1094,7 @@ impl *mut T { { #[cfg(debug_assertions)] #[inline] + #[rustc_allow_const_fn_unstable(const_eval_select)] const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool { #[inline] fn runtime(this: *const (), count: usize, size: usize) -> bool { @@ -1871,6 +1874,7 @@ impl *mut T { } #[inline] + #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")] const fn const_impl(ptr: *mut (), align: usize) -> bool { // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead. ptr.align_offset(align) == 0 diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index d80e1e700aa4..86ef1f3f005b 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -1508,7 +1508,6 @@ impl NonNull<[T]> { #[inline] #[must_use] #[unstable(feature = "slice_ptr_get", issue = "74265")] - #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] pub const fn as_non_null_ptr(self) -> NonNull { self.cast() } diff --git a/library/core/src/ptr/unique.rs b/library/core/src/ptr/unique.rs index 4810ebe01f9b..a796820a7e46 100644 --- a/library/core/src/ptr/unique.rs +++ b/library/core/src/ptr/unique.rs @@ -92,6 +92,7 @@ impl Unique { /// Creates a new `Unique` if `ptr` is non-null. #[inline] + #[rustc_const_unstable(feature = "ptr_internals", issue = "none")] pub const fn new(ptr: *mut T) -> Option { if let Some(pointer) = NonNull::new(ptr) { Some(Unique { pointer, _marker: PhantomData }) diff --git a/library/core/src/slice/ascii.rs b/library/core/src/slice/ascii.rs index a03e9fbae112..21e0460072fb 100644 --- a/library/core/src/slice/ascii.rs +++ b/library/core/src/slice/ascii.rs @@ -346,6 +346,8 @@ pub const fn is_ascii_simple(mut bytes: &[u8]) -> bool { /// If any of these loads produces something for which `contains_nonascii` /// (above) returns true, then we know the answer is false. #[inline] +#[rustc_allow_const_fn_unstable(const_raw_ptr_comparison, const_pointer_is_aligned)] // only in a debug assertion +#[rustc_allow_const_fn_unstable(const_align_offset)] // behavior does not change when `align_offset` fails const fn is_ascii(s: &[u8]) -> bool { const USIZE_SIZE: usize = mem::size_of::(); diff --git a/library/core/src/slice/index.rs b/library/core/src/slice/index.rs index bc8571c8503e..231ab7396adf 100644 --- a/library/core/src/slice/index.rs +++ b/library/core/src/slice/index.rs @@ -31,6 +31,7 @@ where #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] #[cfg_attr(feature = "panic_immediate_abort", inline)] #[track_caller] +#[rustc_allow_const_fn_unstable(const_eval_select)] const fn slice_start_index_len_fail(index: usize, len: usize) -> ! { // FIXME(const-hack): once integer formatting in panics is possible, we // should use the same implementation at compiletime and runtime. @@ -52,6 +53,7 @@ const fn slice_start_index_len_fail_ct(_: usize, _: usize) -> ! { #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] #[cfg_attr(feature = "panic_immediate_abort", inline)] #[track_caller] +#[rustc_allow_const_fn_unstable(const_eval_select)] const fn slice_end_index_len_fail(index: usize, len: usize) -> ! { // FIXME(const-hack): once integer formatting in panics is possible, we // should use the same implementation at compiletime and runtime. @@ -73,6 +75,7 @@ const fn slice_end_index_len_fail_ct(_: usize, _: usize) -> ! { #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] #[cfg_attr(feature = "panic_immediate_abort", inline)] #[track_caller] +#[rustc_allow_const_fn_unstable(const_eval_select)] const fn slice_index_order_fail(index: usize, end: usize) -> ! { // FIXME(const-hack): once integer formatting in panics is possible, we // should use the same implementation at compiletime and runtime. @@ -310,7 +313,6 @@ unsafe impl SliceIndex<[T]> for usize { /// Because `IndexRange` guarantees `start <= end`, fewer checks are needed here /// than there are for a general `Range` (which might be `100..3`). -#[rustc_const_unstable(feature = "const_index_range_slice_index", issue = "none")] unsafe impl SliceIndex<[T]> for ops::IndexRange { type Output = [T]; diff --git a/library/core/src/slice/memchr.rs b/library/core/src/slice/memchr.rs index be19c3d3bc15..576046232626 100644 --- a/library/core/src/slice/memchr.rs +++ b/library/core/src/slice/memchr.rs @@ -15,7 +15,7 @@ const USIZE_BYTES: usize = mem::size_of::(); /// bytes where the borrow propagated all the way to the most significant /// bit." #[inline] -#[rustc_const_stable(feature = "const_memchr", since = "1.65.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_memchr", since = "1.65.0"))] const fn contains_zero_byte(x: usize) -> bool { x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0 } @@ -23,7 +23,7 @@ const fn contains_zero_byte(x: usize) -> bool { /// Returns the first index matching the byte `x` in `text`. #[inline] #[must_use] -#[rustc_const_stable(feature = "const_memchr", since = "1.65.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_memchr", since = "1.65.0"))] pub const fn memchr(x: u8, text: &[u8]) -> Option { // Fast path for small slices. if text.len() < 2 * USIZE_BYTES { @@ -34,7 +34,7 @@ pub const fn memchr(x: u8, text: &[u8]) -> Option { } #[inline] -#[rustc_const_stable(feature = "const_memchr", since = "1.65.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_memchr", since = "1.65.0"))] const fn memchr_naive(x: u8, text: &[u8]) -> Option { let mut i = 0; @@ -52,7 +52,7 @@ const fn memchr_naive(x: u8, text: &[u8]) -> Option { #[rustc_allow_const_fn_unstable(const_cmp)] #[rustc_allow_const_fn_unstable(const_align_offset)] -#[rustc_const_stable(feature = "const_memchr", since = "1.65.0")] +#[cfg_attr(bootstrap, rustc_const_stable(feature = "const_memchr", since = "1.65.0"))] const fn memchr_aligned(x: u8, text: &[u8]) -> Option { // Scan for a single byte value by reading two `usize` words at a time. // diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index dbcfe9464401..27e51afa800a 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -1265,6 +1265,7 @@ impl [T] { /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed /// ``` #[unstable(feature = "slice_as_chunks", issue = "74985")] + #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")] #[inline] #[must_use] pub const unsafe fn as_chunks_unchecked(&self) -> &[[T; N]] { @@ -1310,6 +1311,7 @@ impl [T] { /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]); /// ``` #[unstable(feature = "slice_as_chunks", issue = "74985")] + #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")] #[inline] #[track_caller] #[must_use] @@ -1344,6 +1346,7 @@ impl [T] { /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); /// ``` #[unstable(feature = "slice_as_chunks", issue = "74985")] + #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")] #[inline] #[track_caller] #[must_use] @@ -1422,6 +1425,7 @@ impl [T] { /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed /// ``` #[unstable(feature = "slice_as_chunks", issue = "74985")] + #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")] #[inline] #[must_use] pub const unsafe fn as_chunks_unchecked_mut(&mut self) -> &mut [[T; N]] { @@ -1462,6 +1466,7 @@ impl [T] { /// assert_eq!(v, &[1, 1, 2, 2, 9]); /// ``` #[unstable(feature = "slice_as_chunks", issue = "74985")] + #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")] #[inline] #[track_caller] #[must_use] @@ -1502,6 +1507,7 @@ impl [T] { /// assert_eq!(v, &[9, 1, 1, 2, 2]); /// ``` #[unstable(feature = "slice_as_chunks", issue = "74985")] + #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")] #[inline] #[track_caller] #[must_use] diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 17ba18c2a669..93b4ad5c1c94 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -2122,7 +2122,8 @@ macro_rules! atomic_int { $stable_access:meta, $stable_from:meta, $stable_nand:meta, - $const_stable:meta, + $const_stable_new:meta, + $const_stable_into_inner:meta, $diagnostic_item:meta, $s_int_type:literal, $extra_feature:expr, @@ -2204,7 +2205,7 @@ macro_rules! atomic_int { /// ``` #[inline] #[$stable] - #[$const_stable] + #[$const_stable_new] #[must_use] pub const fn new(v: $int_type) -> Self { Self {v: UnsafeCell::new(v)} @@ -2406,7 +2407,7 @@ macro_rules! atomic_int { /// ``` #[inline] #[$stable_access] - #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")] + #[$const_stable_into_inner] pub const fn into_inner(self) -> $int_type { self.v.into_inner() } @@ -3054,6 +3055,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicI8"), "i8", "", @@ -3072,6 +3074,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicU8"), "u8", "", @@ -3090,6 +3093,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicI16"), "i16", "", @@ -3108,6 +3112,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicU16"), "u16", "", @@ -3126,6 +3131,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicI32"), "i32", "", @@ -3144,6 +3150,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicU32"), "u32", "", @@ -3162,6 +3169,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicI64"), "i64", "", @@ -3180,6 +3188,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicU64"), "u64", "", @@ -3197,7 +3206,8 @@ atomic_int! { unstable(feature = "integer_atomics", issue = "99069"), unstable(feature = "integer_atomics", issue = "99069"), unstable(feature = "integer_atomics", issue = "99069"), - rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicI128"), "i128", "#![feature(integer_atomics)]\n\n", @@ -3215,7 +3225,8 @@ atomic_int! { unstable(feature = "integer_atomics", issue = "99069"), unstable(feature = "integer_atomics", issue = "99069"), unstable(feature = "integer_atomics", issue = "99069"), - rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicU128"), "u128", "#![feature(integer_atomics)]\n\n", @@ -3238,6 +3249,7 @@ macro_rules! atomic_int_ptr_sized { stable(feature = "atomic_from", since = "1.23.0"), stable(feature = "atomic_nand", since = "1.27.0"), rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicIsize"), "isize", "", @@ -3256,6 +3268,7 @@ macro_rules! atomic_int_ptr_sized { stable(feature = "atomic_from", since = "1.23.0"), stable(feature = "atomic_nand", since = "1.27.0"), rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), cfg_attr(not(test), rustc_diagnostic_item = "AtomicUsize"), "usize", "", diff --git a/library/core/src/sync/exclusive.rs b/library/core/src/sync/exclusive.rs index fbf8dafad186..af25f1397391 100644 --- a/library/core/src/sync/exclusive.rs +++ b/library/core/src/sync/exclusive.rs @@ -106,6 +106,7 @@ impl Exclusive { /// Unwrap the value contained in the `Exclusive` #[unstable(feature = "exclusive_wrapper", issue = "98407")] + #[rustc_const_unstable(feature = "exclusive_wrapper", issue = "98407")] #[must_use] #[inline] pub const fn into_inner(self) -> T { @@ -129,6 +130,7 @@ impl Exclusive { /// access to the underlying value, but _pinned_ `Exclusive`s only /// produce _pinned_ access to the underlying value. #[unstable(feature = "exclusive_wrapper", issue = "98407")] + #[rustc_const_unstable(feature = "exclusive_wrapper", issue = "98407")] #[must_use] #[inline] pub const fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T> { @@ -152,6 +154,7 @@ impl Exclusive { /// a _pinned mutable_ reference to a `T`. This allows you to skip /// building an `Exclusive` with [`Exclusive::new`]. #[unstable(feature = "exclusive_wrapper", issue = "98407")] + #[rustc_const_unstable(feature = "exclusive_wrapper", issue = "98407")] #[must_use] #[inline] pub const fn from_pin_mut(r: Pin<&'_ mut T>) -> Pin<&'_ mut Exclusive> { diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index 3e795e7b5e3f..fb7af8234ddb 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -321,7 +321,7 @@ impl<'a> ContextBuilder<'a> { /// Creates a ContextBuilder from a Waker. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_stable(feature = "const_waker", since = "1.82.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_waker", since = "1.82.0"))] pub const fn from_waker(waker: &'a Waker) -> Self { // SAFETY: LocalWaker is just Waker without thread safety let local_waker = unsafe { transmute(waker) }; @@ -379,7 +379,7 @@ impl<'a> ContextBuilder<'a> { /// Builds the `Context`. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_stable(feature = "const_waker", since = "1.82.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_waker", since = "1.82.0"))] pub const fn build(self) -> Context<'a> { let ContextBuilder { waker, local_waker, ext, _marker, _marker2 } = self; Context { waker, local_waker, ext: AssertUnwindSafe(ext), _marker, _marker2 } diff --git a/library/core/src/ub_checks.rs b/library/core/src/ub_checks.rs index daaaf5a71953..91566439adea 100644 --- a/library/core/src/ub_checks.rs +++ b/library/core/src/ub_checks.rs @@ -47,7 +47,7 @@ use crate::intrinsics::{self, const_eval_select}; /// order to call it. Since the precompiled standard library is built with full debuginfo and these /// variables cannot be optimized out in MIR, an innocent-looking `let` can produce enough /// debuginfo to have a measurable compile-time impact on debug builds. -#[allow_internal_unstable(const_ub_checks)] // permit this to be called in stably-const fn +#[cfg_attr(bootstrap, allow_internal_unstable(const_ub_checks))] // permit this to be called in stably-const fn #[macro_export] #[unstable(feature = "ub_checks", issue = "none")] macro_rules! assert_unsafe_precondition { @@ -64,7 +64,8 @@ macro_rules! assert_unsafe_precondition { #[rustc_no_mir_inline] #[inline] #[rustc_nounwind] - #[rustc_const_unstable(feature = "const_ub_checks", issue = "none")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_ub_checks", issue = "none"))] + #[rustc_allow_const_fn_unstable(const_ptr_is_null, const_ub_checks)] // only for UB checks const fn precondition_check($($name:$ty),*) { if !$e { ::core::panicking::panic_nounwind( @@ -90,8 +91,9 @@ pub use intrinsics::ub_checks as check_library_ub; /// /// The intention is to not do that when running in the interpreter, as that one has its own /// language UB checks which generally produce better errors. -#[rustc_const_unstable(feature = "const_ub_checks", issue = "none")] +#[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_ub_checks", issue = "none"))] #[inline] +#[rustc_allow_const_fn_unstable(const_eval_select)] pub(crate) const fn check_language_ub() -> bool { #[inline] fn runtime() -> bool { @@ -116,6 +118,7 @@ pub(crate) const fn check_language_ub() -> bool { /// for `assert_unsafe_precondition!` with `check_language_ub`, in which case the /// check is anyway not executed in `const`. #[inline] +#[rustc_const_unstable(feature = "const_ub_checks", issue = "none")] pub(crate) const fn is_aligned_and_not_null(ptr: *const (), align: usize, is_zst: bool) -> bool { ptr.is_aligned_to(align) && (is_zst || !ptr.is_null()) } @@ -132,6 +135,7 @@ pub(crate) const fn is_valid_allocation_size(size: usize, len: usize) -> bool { /// Note that in const-eval this function just returns `true` and therefore must /// only be used with `assert_unsafe_precondition!`, similar to `is_aligned_and_not_null`. #[inline] +#[rustc_const_unstable(feature = "const_ub_checks", issue = "none")] pub(crate) const fn is_nonoverlapping( src: *const (), dst: *const (), diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 14603aa30e83..5719d29659af 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -1,4 +1,5 @@ // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(const_likely))] #![cfg_attr(bootstrap, feature(strict_provenance))] #![cfg_attr(not(bootstrap), feature(strict_provenance_lints))] #![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] @@ -22,7 +23,6 @@ #![feature(const_eval_select)] #![feature(const_hash)] #![feature(const_heap)] -#![feature(const_likely)] #![feature(const_nonnull_new)] #![feature(const_num_midpoint)] #![feature(const_option_ext)] diff --git a/library/std/src/sys/sync/once/queue.rs b/library/std/src/sys/sync/once/queue.rs index 3e83a4a088fd..177d0d7744a6 100644 --- a/library/std/src/sys/sync/once/queue.rs +++ b/library/std/src/sys/sync/once/queue.rs @@ -116,7 +116,7 @@ fn to_state(current: StateAndQueue) -> usize { impl Once { #[inline] - #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")] + #[cfg_attr(bootstrap, rustc_const_stable(feature = "const_once_new", since = "1.32.0"))] pub const fn new() -> Once { Once { state_and_queue: AtomicPtr::new(ptr::without_provenance_mut(INCOMPLETE)) } } diff --git a/library/std/src/sys/thread_local/key/racy.rs b/library/std/src/sys/thread_local/key/racy.rs index 69f11458c328..97df8997b80d 100644 --- a/library/std/src/sys/thread_local/key/racy.rs +++ b/library/std/src/sys/thread_local/key/racy.rs @@ -30,7 +30,7 @@ const KEY_SENTVAL: usize = 0; const KEY_SENTVAL: usize = libc::PTHREAD_KEYS_MAX + 1; impl LazyKey { - #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "thread_local_internals", issue = "none"))] pub const fn new(dtor: Option) -> LazyKey { LazyKey { key: atomic::AtomicUsize::new(KEY_SENTVAL), dtor } } diff --git a/library/std/src/sys/thread_local/os.rs b/library/std/src/sys/thread_local/os.rs index f5a2aaa6c6a3..58f291ffdb98 100644 --- a/library/std/src/sys/thread_local/os.rs +++ b/library/std/src/sys/thread_local/os.rs @@ -60,7 +60,7 @@ struct Value { } impl Storage { - #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "thread_local_internals", issue = "none"))] pub const fn new() -> Storage { Storage { key: LazyKey::new(Some(destroy_value::)), marker: PhantomData } } diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index 88bf186700f3..9edb3fa41933 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -237,7 +237,7 @@ impl LocalKey { reason = "recently added to create a key", issue = "none" )] - #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")] + #[cfg_attr(bootstrap, rustc_const_unstable(feature = "thread_local_internals", issue = "none"))] pub const unsafe fn new(inner: fn(Option<&mut Option>) -> *const T) -> LocalKey { LocalKey { inner } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index c8cb9267eb26..1c060fa01505 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -8,7 +8,6 @@ use arrayvec::ArrayVec; use rustc_ast::MetaItemInner; use rustc_ast_pretty::pprust; use rustc_attr::{ConstStability, Deprecation, Stability, StableSince}; -use rustc_const_eval::const_eval::is_unstable_const_fn; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; @@ -641,12 +640,11 @@ impl Item { asyncness: ty::Asyncness, ) -> hir::FnHeader { let sig = tcx.fn_sig(def_id).skip_binder(); - let constness = - if tcx.is_const_fn(def_id) || is_unstable_const_fn(tcx, def_id).is_some() { - hir::Constness::Const - } else { - hir::Constness::NotConst - }; + let constness = if tcx.is_const_fn_raw(def_id) { + hir::Constness::Const + } else { + hir::Constness::NotConst + }; let asyncness = match asyncness { ty::Asyncness::Yes => hir::IsAsync::Async(DUMMY_SP), ty::Asyncness::No => hir::IsAsync::NotAsync, @@ -664,9 +662,7 @@ impl Item { safety }, abi, - constness: if tcx.is_const_fn(def_id) - || is_unstable_const_fn(tcx, def_id).is_some() - { + constness: if tcx.is_const_fn_raw(def_id) { hir::Constness::Const } else { hir::Constness::NotConst diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index ce96d1d0a95c..8446235fb188 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1010,7 +1010,9 @@ fn render_stability_since_raw_with_extra( // don't display const unstable if entirely unstable None } else { - let unstable = if let Some(n) = issue { + let unstable = if let Some(n) = issue + && let Some(feature) = feature + { format!( " u32 { 42 } - - // Show const-stability even for unstable functions. - //@ matches 'foo/struct.Bar.html' '//span[@class="since"]' '^const: 1.3.0$' - #[unstable(feature = "foo2", issue = "none")] - #[rustc_const_stable(feature = "const3", since = "1.3.0")] - pub const fn const_stable_unstable() -> u32 { 42 } } diff --git a/tests/ui/borrowck/issue-64453.rs b/tests/ui/borrowck/issue-64453.rs index 33d55be5812e..5f1f35d6ca9b 100644 --- a/tests/ui/borrowck/issue-64453.rs +++ b/tests/ui/borrowck/issue-64453.rs @@ -3,7 +3,6 @@ struct Value; static settings_dir: String = format!(""); //~^ ERROR cannot call non-const fn -//~| ERROR is not yet stable as a const fn from_string(_: String) -> Value { Value diff --git a/tests/ui/borrowck/issue-64453.stderr b/tests/ui/borrowck/issue-64453.stderr index e671817633be..98b05ead6491 100644 --- a/tests/ui/borrowck/issue-64453.stderr +++ b/tests/ui/borrowck/issue-64453.stderr @@ -1,12 +1,3 @@ -error: `Arguments::<'a>::new_const` is not yet stable as a const fn - --> $DIR/issue-64453.rs:4:31 - | -LL | static settings_dir: String = format!(""); - | ^^^^^^^^^^^ - | - = help: add `#![feature(const_fmt_arguments_new)]` to the crate attributes to enable - = note: this error originates in the macro `$crate::__export::format_args` which comes from the expansion of the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) - error[E0015]: cannot call non-const fn `format` in statics --> $DIR/issue-64453.rs:4:31 | @@ -18,7 +9,7 @@ LL | static settings_dir: String = format!(""); = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0507]: cannot move out of static item `settings_dir` - --> $DIR/issue-64453.rs:14:37 + --> $DIR/issue-64453.rs:13:37 | LL | let settings_data = from_string(settings_dir); | ^^^^^^^^^^^^ move occurs because `settings_dir` has type `String`, which does not implement the `Copy` trait @@ -28,7 +19,7 @@ help: consider cloning the value if the performance cost is acceptable LL | let settings_data = from_string(settings_dir.clone()); | ++++++++ -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0015, E0507. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/auxiliary/unstable_but_const_stable.rs b/tests/ui/consts/auxiliary/unstable_but_const_stable.rs deleted file mode 100644 index 88044b0272c7..000000000000 --- a/tests/ui/consts/auxiliary/unstable_but_const_stable.rs +++ /dev/null @@ -1,13 +0,0 @@ -#![feature(staged_api, rustc_attrs, intrinsics)] -#![stable(since="1.0.0", feature = "stable")] - -extern "rust-intrinsic" { - #[unstable(feature = "unstable", issue = "42")] - #[rustc_const_stable(feature = "stable", since = "1.0.0")] - #[rustc_nounwind] - pub fn write_bytes(dst: *mut T, val: u8, count: usize); -} - -#[unstable(feature = "unstable", issue = "42")] -#[rustc_const_stable(feature = "stable", since = "1.0.0")] -pub const fn some_unstable_fn() {} diff --git a/tests/ui/consts/auxiliary/unstable_intrinsic.rs b/tests/ui/consts/auxiliary/unstable_intrinsic.rs new file mode 100644 index 000000000000..edef499dbb18 --- /dev/null +++ b/tests/ui/consts/auxiliary/unstable_intrinsic.rs @@ -0,0 +1,26 @@ +#![feature(staged_api, rustc_attrs, intrinsics)] +#![stable(since="1.0.0", feature = "stable")] + +#[stable(since="1.0.0", feature = "stable")] +pub mod old_way { + extern "rust-intrinsic" { + #[unstable(feature = "unstable", issue = "42")] + pub fn size_of_val(x: *const T) -> usize; + + #[unstable(feature = "unstable", issue = "42")] + #[rustc_const_unstable(feature = "unstable", issue = "42")] + pub fn min_align_of_val(x: *const T) -> usize; + } +} + +#[stable(since="1.0.0", feature = "stable")] +pub mod new_way { + #[unstable(feature = "unstable", issue = "42")] + #[rustc_intrinsic] + pub const unsafe fn size_of_val(x: *const T) -> usize { 42 } + + #[unstable(feature = "unstable", issue = "42")] + #[rustc_const_unstable(feature = "unstable", issue = "42")] + #[rustc_intrinsic] + pub const unsafe fn min_align_of_val(x: *const T) -> usize { 42 } +} diff --git a/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.rs b/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.rs index 4b3cf70739cc..6c93c0e63b60 100644 --- a/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.rs +++ b/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.rs @@ -3,7 +3,7 @@ we're apparently really bad at it", issue = "none")] -#![feature(staged_api)] +#![feature(staged_api, foo)] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature="foo", issue = "none")] @@ -11,7 +11,7 @@ const fn foo() -> u32 { 42 } fn meh() -> u32 { 42 } -const fn bar() -> u32 { foo() } //~ ERROR `foo` is not yet stable as a const fn +const fn bar() -> u32 { foo() } //~ ERROR cannot use `#[feature(foo)]` fn a() { let _: &'static u32 = &foo(); //~ ERROR temporary value dropped while borrowed diff --git a/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr b/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr index 2e697b219c5a..1de1c78faf6e 100644 --- a/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr +++ b/tests/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr @@ -1,10 +1,20 @@ -error: `foo` is not yet stable as a const fn +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo)]` --> $DIR/dont_promote_unstable_const_fn.rs:14:25 | LL | const fn bar() -> u32 { foo() } | ^^^^^ | - = help: add `#![feature(foo)]` to the crate attributes to enable + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn bar() -> u32 { foo() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo)] +LL | const fn bar() -> u32 { foo() } + | error[E0716]: temporary value dropped while borrowed --> $DIR/dont_promote_unstable_const_fn.rs:17:28 diff --git a/tests/ui/consts/const-eval/simd/insert_extract.rs b/tests/ui/consts/const-eval/simd/insert_extract.rs index f4f25327aaf1..57d4b4888caa 100644 --- a/tests/ui/consts/const-eval/simd/insert_extract.rs +++ b/tests/ui/consts/const-eval/simd/insert_extract.rs @@ -11,8 +11,11 @@ #[repr(simd)] struct f32x4([f32; 4]); extern "rust-intrinsic" { + #[stable(feature = "foo", since = "1.3.37")] #[rustc_const_stable(feature = "foo", since = "1.3.37")] fn simd_insert(x: T, idx: u32, val: U) -> T; + + #[stable(feature = "foo", since = "1.3.37")] #[rustc_const_stable(feature = "foo", since = "1.3.37")] fn simd_extract(x: T, idx: u32) -> U; } diff --git a/tests/ui/consts/const-unstable-intrinsic.rs b/tests/ui/consts/const-unstable-intrinsic.rs new file mode 100644 index 000000000000..050abc6dd461 --- /dev/null +++ b/tests/ui/consts/const-unstable-intrinsic.rs @@ -0,0 +1,76 @@ +//! Ensure that unstable intrinsics can actually not be called, +//! neither within a crate nor cross-crate. +//@ aux-build:unstable_intrinsic.rs +#![feature(staged_api, rustc_attrs, intrinsics)] +#![stable(since="1.0.0", feature = "stable")] +#![feature(local)] + +extern crate unstable_intrinsic; + +fn main() { + const_main(); +} + +const fn const_main() { + let x = 42; + unsafe { + unstable_intrinsic::old_way::size_of_val(&x); + //~^ERROR: unstable library feature 'unstable' + //~|ERROR: cannot call non-const intrinsic + unstable_intrinsic::old_way::min_align_of_val(&x); + //~^ERROR: unstable library feature 'unstable' + //~|ERROR: not yet stable as a const intrinsic + unstable_intrinsic::new_way::size_of_val(&x); + //~^ERROR: unstable library feature 'unstable' + //~|ERROR: cannot be (indirectly) exposed to stable + unstable_intrinsic::new_way::min_align_of_val(&x); + //~^ERROR: unstable library feature 'unstable' + //~|ERROR: not yet stable as a const intrinsic + + old_way::size_of_val(&x); + //~^ERROR: cannot call non-const intrinsic + old_way::min_align_of_val(&x); + //~^ERROR: cannot use `#[feature(local)]` + new_way::size_of_val(&x); + //~^ERROR: cannot be (indirectly) exposed to stable + new_way::min_align_of_val(&x); + //~^ERROR: cannot use `#[feature(local)]` + } +} + +#[stable(since="1.0.0", feature = "stable")] +pub mod old_way { + extern "rust-intrinsic" { + #[unstable(feature = "local", issue = "42")] + pub fn size_of_val(x: *const T) -> usize; + + #[unstable(feature = "local", issue = "42")] + #[rustc_const_unstable(feature = "local", issue = "42")] + pub fn min_align_of_val(x: *const T) -> usize; + } +} + +#[stable(since="1.0.0", feature = "stable")] +pub mod new_way { + #[unstable(feature = "local", issue = "42")] + #[rustc_intrinsic] + pub const unsafe fn size_of_val(x: *const T) -> usize { 42 } + + #[unstable(feature = "local", issue = "42")] + #[rustc_const_unstable(feature = "local", issue = "42")] + #[rustc_intrinsic] + pub const unsafe fn min_align_of_val(x: *const T) -> usize { 42 } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] +#[inline] +pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { + // Const stability attributes are not inherited from parent items. + extern "rust-intrinsic" { + fn copy(src: *const T, dst: *mut T, count: usize); + } + + unsafe { copy(src, dst, count) } + //~^ ERROR cannot call non-const intrinsic +} diff --git a/tests/ui/consts/const-unstable-intrinsic.stderr b/tests/ui/consts/const-unstable-intrinsic.stderr new file mode 100644 index 000000000000..33a434c503dc --- /dev/null +++ b/tests/ui/consts/const-unstable-intrinsic.stderr @@ -0,0 +1,127 @@ +error[E0658]: use of unstable library feature 'unstable' + --> $DIR/const-unstable-intrinsic.rs:17:9 + | +LL | unstable_intrinsic::old_way::size_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: use of unstable library feature 'unstable' + --> $DIR/const-unstable-intrinsic.rs:20:9 + | +LL | unstable_intrinsic::old_way::min_align_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: use of unstable library feature 'unstable' + --> $DIR/const-unstable-intrinsic.rs:23:9 + | +LL | unstable_intrinsic::new_way::size_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: use of unstable library feature 'unstable' + --> $DIR/const-unstable-intrinsic.rs:26:9 + | +LL | unstable_intrinsic::new_way::min_align_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: cannot call non-const intrinsic `size_of_val` in constant functions + --> $DIR/const-unstable-intrinsic.rs:17:9 + | +LL | unstable_intrinsic::old_way::size_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: `min_align_of_val` is not yet stable as a const intrinsic + --> $DIR/const-unstable-intrinsic.rs:20:9 + | +LL | unstable_intrinsic::old_way::min_align_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable)]` to the crate attributes to enable + +error: intrinsic `unstable_intrinsic::new_way::size_of_val` cannot be (indirectly) exposed to stable + --> $DIR/const-unstable-intrinsic.rs:23:9 + | +LL | unstable_intrinsic::new_way::size_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_const_stable_indirect]` (but this requires team approval) + +error: `min_align_of_val` is not yet stable as a const intrinsic + --> $DIR/const-unstable-intrinsic.rs:26:9 + | +LL | unstable_intrinsic::new_way::min_align_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable)]` to the crate attributes to enable + +error: cannot call non-const intrinsic `size_of_val` in constant functions + --> $DIR/const-unstable-intrinsic.rs:30:9 + | +LL | old_way::size_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:32:9 + | +LL | old_way::min_align_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_main() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(local)] +LL | const fn const_main() { + | + +error: intrinsic `new_way::size_of_val` cannot be (indirectly) exposed to stable + --> $DIR/const-unstable-intrinsic.rs:34:9 + | +LL | new_way::size_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_const_stable_indirect]` (but this requires team approval) + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:36:9 + | +LL | new_way::min_align_of_val(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_main() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(local)] +LL | const fn const_main() { + | + +error: cannot call non-const intrinsic `copy` in constant functions + --> $DIR/const-unstable-intrinsic.rs:74:14 + | +LL | unsafe { copy(src, dst, count) } + | ^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 13 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/consts/copy-intrinsic.rs b/tests/ui/consts/copy-intrinsic.rs index 805c03da546a..62917c0b98b2 100644 --- a/tests/ui/consts/copy-intrinsic.rs +++ b/tests/ui/consts/copy-intrinsic.rs @@ -5,9 +5,11 @@ use std::mem; extern "rust-intrinsic" { + #[stable(feature = "dummy", since = "1.0.0")] #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); + #[stable(feature = "dummy", since = "1.0.0")] #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] fn copy(src: *const T, dst: *mut T, count: usize); } diff --git a/tests/ui/consts/copy-intrinsic.stderr b/tests/ui/consts/copy-intrinsic.stderr index da8139129c9f..29a88f6270bc 100644 --- a/tests/ui/consts/copy-intrinsic.stderr +++ b/tests/ui/consts/copy-intrinsic.stderr @@ -1,23 +1,23 @@ error[E0080]: evaluation of constant value failed - --> $DIR/copy-intrinsic.rs:28:5 + --> $DIR/copy-intrinsic.rs:30:5 | LL | copy_nonoverlapping(0x100 as *const i32, dangle, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ memory access failed: expected a pointer to 4 bytes of memory, but got 0x100[noalloc] which is a dangling pointer (it has no provenance) error[E0080]: evaluation of constant value failed - --> $DIR/copy-intrinsic.rs:37:5 + --> $DIR/copy-intrinsic.rs:39:5 | LL | copy_nonoverlapping(dangle, 0x100 as *mut i32, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ memory access failed: expected a pointer to 4 bytes of memory, but got ALLOC0+0x28 which is at or beyond the end of the allocation of size 4 bytes error[E0080]: evaluation of constant value failed - --> $DIR/copy-intrinsic.rs:44:5 + --> $DIR/copy-intrinsic.rs:46:5 | LL | copy(&x, &mut y, 1usize << (mem::size_of::() * 8 - 1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ overflow computing total size of `copy` error[E0080]: evaluation of constant value failed - --> $DIR/copy-intrinsic.rs:50:5 + --> $DIR/copy-intrinsic.rs:52:5 | LL | copy_nonoverlapping(&x, &mut y, 1usize << (mem::size_of::() * 8 - 1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ overflow computing total size of `copy_nonoverlapping` diff --git a/tests/ui/consts/intrinsic_without_const_stab.rs b/tests/ui/consts/intrinsic_without_const_stab.rs deleted file mode 100644 index 40ec65d51bee..000000000000 --- a/tests/ui/consts/intrinsic_without_const_stab.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![feature(intrinsics, staged_api)] -#![stable(feature = "core", since = "1.6.0")] - -#[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] -#[inline] -pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { - // Const stability attributes are not inherited from parent items. - extern "rust-intrinsic" { - fn copy(src: *const T, dst: *mut T, count: usize); - } - - unsafe { copy(src, dst, count) } - //~^ ERROR cannot call non-const fn -} - -fn main() {} diff --git a/tests/ui/consts/intrinsic_without_const_stab.stderr b/tests/ui/consts/intrinsic_without_const_stab.stderr deleted file mode 100644 index e3143080c5fc..000000000000 --- a/tests/ui/consts/intrinsic_without_const_stab.stderr +++ /dev/null @@ -1,11 +0,0 @@ -error[E0015]: cannot call non-const fn `copy::copy::` in constant functions - --> $DIR/intrinsic_without_const_stab.rs:13:14 - | -LL | unsafe { copy(src, dst, count) } - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/intrinsic_without_const_stab_fail.rs b/tests/ui/consts/intrinsic_without_const_stab_fail.rs deleted file mode 100644 index 2b0745b3c110..000000000000 --- a/tests/ui/consts/intrinsic_without_const_stab_fail.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![feature(intrinsics, staged_api)] -#![stable(feature = "core", since = "1.6.0")] - -extern "rust-intrinsic" { - fn copy(src: *const T, dst: *mut T, count: usize); -} - -#[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] -#[inline] -pub const unsafe fn stuff(src: *const T, dst: *mut T, count: usize) { - unsafe { copy(src, dst, count) } //~ ERROR cannot call non-const fn -} - -fn main() {} diff --git a/tests/ui/consts/intrinsic_without_const_stab_fail.stderr b/tests/ui/consts/intrinsic_without_const_stab_fail.stderr deleted file mode 100644 index 8ade68eb2a97..000000000000 --- a/tests/ui/consts/intrinsic_without_const_stab_fail.stderr +++ /dev/null @@ -1,11 +0,0 @@ -error[E0015]: cannot call non-const fn `copy::` in constant functions - --> $DIR/intrinsic_without_const_stab_fail.rs:12:14 - | -LL | unsafe { copy(src, dst, count) } - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.rs b/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.rs index 461499e942fc..d6f07994e820 100644 --- a/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.rs +++ b/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.rs @@ -5,7 +5,7 @@ issue = "none")] #![feature(foo, foo2)] -#![feature(const_async_blocks, staged_api)] +#![feature(const_async_blocks, staged_api, rustc_attrs)] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature="foo", issue = "none")] @@ -14,33 +14,55 @@ const fn foo() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const fn bar() -> u32 { foo() } //~ ERROR not yet stable as a const fn +const fn bar() -> u32 { foo() } //~ ERROR cannot use `#[feature(foo)]` #[unstable(feature = "foo2", issue = "none")] +#[rustc_const_unstable(feature = "foo2", issue = "none")] const fn foo2() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const fn bar2() -> u32 { foo2() } //~ ERROR not yet stable as a const fn +const fn bar2() -> u32 { foo2() } //~ ERROR cannot use `#[feature(foo2)]` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // conformity is required const fn bar3() -> u32 { let x = async { 13 }; - //~^ ERROR const-stable function cannot use `#[feature(const_async_blocks)]` + //~^ ERROR cannot use `#[feature(const_async_blocks)]` foo() - //~^ ERROR is not yet stable as a const fn + //~^ ERROR cannot use `#[feature(foo)]` } // check whether this function cannot be called even with the feature gate active #[unstable(feature = "foo2", issue = "none")] +#[rustc_const_unstable(feature = "foo2", issue = "none")] const fn foo2_gated() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR not yet stable as a const fn +const fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR cannot use `#[feature(foo2)]` + +// Functions without any attribute are checked like stable functions, +// even if they are in a stable module. +mod stable { + #![stable(feature = "rust1", since = "1.0.0")] + + pub(crate) const fn bar2_gated_stable_indirect() -> u32 { super::foo2_gated() } //~ ERROR cannot use `#[feature(foo2)]` +} +// And same for const-unstable functions that are marked as "stable_indirect". +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature="foo", issue = "none")] +#[rustc_const_stable_indirect] +const fn stable_indirect() -> u32 { foo2_gated() } //~ ERROR cannot use `#[feature(foo2)]` + +// These functiuons *can* be called from fully stable functions. +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_stable(feature = "rust1", since = "1.0.0")] +const fn bar2_gated_exposed() -> u32 { + stable::bar2_gated_stable_indirect() + stable_indirect() +} fn main() {} diff --git a/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.stderr b/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.stderr index fedc5a4809d6..899cec07ac70 100644 --- a/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.stderr +++ b/tests/ui/consts/min_const_fn/min_const_fn_libstd_stability.stderr @@ -1,51 +1,127 @@ -error: `foo` is not yet stable as a const fn +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo)]` --> $DIR/min_const_fn_libstd_stability.rs:17:25 | LL | const fn bar() -> u32 { foo() } | ^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn bar() -> u32 { foo() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo)] +LL | const fn bar() -> u32 { foo() } + | -error: `foo2` is not yet stable as a const fn - --> $DIR/min_const_fn_libstd_stability.rs:25:26 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_fn_libstd_stability.rs:26:26 | LL | const fn bar2() -> u32 { foo2() } | ^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn bar2() -> u32 { foo2() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const fn bar2() -> u32 { foo2() } + | -error: const-stable function cannot use `#[feature(const_async_blocks)]` - --> $DIR/min_const_fn_libstd_stability.rs:31:13 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(const_async_blocks)]` + --> $DIR/min_const_fn_libstd_stability.rs:32:13 | LL | let x = async { 13 }; | ^^^^^^^^^^^^ | -help: if the function is not (yet) meant to be stable, make this function unstably const +help: if the function is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) | LL + #[rustc_const_unstable(feature = "...", issue = "...")] LL | const fn bar3() -> u32 { | -help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (but requires team approval) +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) | LL + #[rustc_allow_const_fn_unstable(const_async_blocks)] LL | const fn bar3() -> u32 { | -error: `foo` is not yet stable as a const fn - --> $DIR/min_const_fn_libstd_stability.rs:33:5 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo)]` + --> $DIR/min_const_fn_libstd_stability.rs:34:5 | LL | foo() | ^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn bar3() -> u32 { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo)] +LL | const fn bar3() -> u32 { + | -error: `foo2_gated` is not yet stable as a const fn - --> $DIR/min_const_fn_libstd_stability.rs:44:32 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_fn_libstd_stability.rs:46:32 | LL | const fn bar2_gated() -> u32 { foo2_gated() } | ^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn bar2_gated() -> u32 { foo2_gated() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const fn bar2_gated() -> u32 { foo2_gated() } + | -error: aborting due to 5 previous errors +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_fn_libstd_stability.rs:53:63 + | +LL | pub(crate) const fn bar2_gated_stable_indirect() -> u32 { super::foo2_gated() } + | ^^^^^^^^^^^^^^^^^^^ + | + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | pub(crate) const fn bar2_gated_stable_indirect() -> u32 { super::foo2_gated() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | pub(crate) const fn bar2_gated_stable_indirect() -> u32 { super::foo2_gated() } + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_fn_libstd_stability.rs:59:37 + | +LL | const fn stable_indirect() -> u32 { foo2_gated() } + | ^^^^^^^^^^^^ + | + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn stable_indirect() -> u32 { foo2_gated() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const fn stable_indirect() -> u32 { foo2_gated() } + | + +error: aborting due to 7 previous errors diff --git a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.rs b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.rs index 274b4444799a..3e82b9ff9245 100644 --- a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.rs +++ b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.rs @@ -13,24 +13,26 @@ const unsafe fn foo() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const unsafe fn bar() -> u32 { unsafe { foo() } } //~ ERROR not yet stable as a const fn +const unsafe fn bar() -> u32 { unsafe { foo() } } //~ ERROR cannot use `#[feature(foo)]` #[unstable(feature = "foo2", issue = "none")] +#[rustc_const_unstable(feature = "foo2", issue = "none")] const unsafe fn foo2() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const unsafe fn bar2() -> u32 { unsafe { foo2() } } //~ ERROR not yet stable as a const fn +const unsafe fn bar2() -> u32 { unsafe { foo2() } } //~ ERROR cannot use `#[feature(foo2)]` // check whether this function cannot be called even with the feature gate active #[unstable(feature = "foo2", issue = "none")] +#[rustc_const_unstable(feature = "foo2", issue = "none")] const unsafe fn foo2_gated() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn const unsafe fn bar2_gated() -> u32 { unsafe { foo2_gated() } } -//~^ ERROR not yet stable as a const fn +//~^ ERROR cannot use `#[feature(foo2)]` fn main() {} diff --git a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.stderr b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.stderr index 353b117efbc8..442a079020f1 100644 --- a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.stderr +++ b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability.stderr @@ -1,26 +1,56 @@ -error: `foo` is not yet stable as a const fn +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo)]` --> $DIR/min_const_unsafe_fn_libstd_stability.rs:16:41 | LL | const unsafe fn bar() -> u32 { unsafe { foo() } } | ^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn bar() -> u32 { unsafe { foo() } } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo)] +LL | const unsafe fn bar() -> u32 { unsafe { foo() } } + | -error: `foo2` is not yet stable as a const fn - --> $DIR/min_const_unsafe_fn_libstd_stability.rs:24:42 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_unsafe_fn_libstd_stability.rs:25:42 | LL | const unsafe fn bar2() -> u32 { unsafe { foo2() } } | ^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn bar2() -> u32 { unsafe { foo2() } } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const unsafe fn bar2() -> u32 { unsafe { foo2() } } + | -error: `foo2_gated` is not yet stable as a const fn - --> $DIR/min_const_unsafe_fn_libstd_stability.rs:33:48 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_unsafe_fn_libstd_stability.rs:35:48 | LL | const unsafe fn bar2_gated() -> u32 { unsafe { foo2_gated() } } | ^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn bar2_gated() -> u32 { unsafe { foo2_gated() } } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const unsafe fn bar2_gated() -> u32 { unsafe { foo2_gated() } } + | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.rs b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.rs index 94b620713629..cc7eaa51a6f4 100644 --- a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.rs +++ b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.rs @@ -13,23 +13,25 @@ const fn foo() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const unsafe fn bar() -> u32 { foo() } //~ ERROR not yet stable as a const fn +const unsafe fn bar() -> u32 { foo() } //~ ERROR cannot use `#[feature(foo)]` #[unstable(feature = "foo2", issue = "none")] +#[rustc_const_unstable(feature="foo2", issue = "none")] const fn foo2() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const unsafe fn bar2() -> u32 { foo2() } //~ ERROR not yet stable as a const fn +const unsafe fn bar2() -> u32 { foo2() } //~ ERROR cannot use `#[feature(foo2)]` // check whether this function cannot be called even with the feature gate active #[unstable(feature = "foo2", issue = "none")] +#[rustc_const_unstable(feature="foo2", issue = "none")] const fn foo2_gated() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn -const unsafe fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR not yet stable as a const fn +const unsafe fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR cannot use `#[feature(foo2)]` fn main() {} diff --git a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.stderr b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.stderr index e90ba9b912fe..ff37cba7b9ac 100644 --- a/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.stderr +++ b/tests/ui/consts/min_const_fn/min_const_unsafe_fn_libstd_stability2.stderr @@ -1,26 +1,56 @@ -error: `foo` is not yet stable as a const fn +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo)]` --> $DIR/min_const_unsafe_fn_libstd_stability2.rs:16:32 | LL | const unsafe fn bar() -> u32 { foo() } | ^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn bar() -> u32 { foo() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo)] +LL | const unsafe fn bar() -> u32 { foo() } + | -error: `foo2` is not yet stable as a const fn - --> $DIR/min_const_unsafe_fn_libstd_stability2.rs:24:33 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_unsafe_fn_libstd_stability2.rs:25:33 | LL | const unsafe fn bar2() -> u32 { foo2() } | ^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn bar2() -> u32 { foo2() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const unsafe fn bar2() -> u32 { foo2() } + | -error: `foo2_gated` is not yet stable as a const fn - --> $DIR/min_const_unsafe_fn_libstd_stability2.rs:33:39 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(foo2)]` + --> $DIR/min_const_unsafe_fn_libstd_stability2.rs:35:39 | LL | const unsafe fn bar2_gated() -> u32 { foo2_gated() } | ^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn bar2_gated() -> u32 { foo2_gated() } + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(foo2)] +LL | const unsafe fn bar2_gated() -> u32 { foo2_gated() } + | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/rustc-const-stability-require-const.rs b/tests/ui/consts/rustc-const-stability-require-const.rs index 4fb259b335c7..6cc3f0f0da12 100644 --- a/tests/ui/consts/rustc-const-stability-require-const.rs +++ b/tests/ui/consts/rustc-const-stability-require-const.rs @@ -1,16 +1,16 @@ #![crate_type = "lib"] -#![feature(staged_api)] +#![feature(staged_api, rustc_attrs)] #![stable(feature = "foo", since = "1.0.0")] #[stable(feature = "foo", since = "1.0.0")] #[rustc_const_unstable(feature = "const_foo", issue = "none")] pub fn foo() {} -//~^ ERROR attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +//~^ ERROR require the function or method to be `const` #[stable(feature = "bar", since = "1.0.0")] #[rustc_const_stable(feature = "const_bar", since = "1.0.0")] pub fn bar() {} -//~^ ERROR attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +//~^ ERROR require the function or method to be `const` #[stable(feature = "potato", since = "1.0.0")] pub struct Potato; @@ -19,23 +19,23 @@ impl Potato { #[stable(feature = "salad", since = "1.0.0")] #[rustc_const_unstable(feature = "const_salad", issue = "none")] pub fn salad(&self) -> &'static str { "mmmmmm" } - //~^ ERROR attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` + //~^ ERROR require the function or method to be `const` #[stable(feature = "roasted", since = "1.0.0")] #[rustc_const_unstable(feature = "const_roasted", issue = "none")] pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } - //~^ ERROR attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` + //~^ ERROR require the function or method to be `const` } #[stable(feature = "bar", since = "1.0.0")] #[rustc_const_stable(feature = "const_bar", since = "1.0.0")] pub extern "C" fn bar_c() {} -//~^ ERROR attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +//~^ ERROR require the function or method to be `const` #[stable(feature = "foo", since = "1.0.0")] #[rustc_const_unstable(feature = "const_foo", issue = "none")] pub extern "C" fn foo_c() {} -//~^ ERROR attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +//~^ ERROR require the function or method to be `const` #[stable(feature = "foobar", since = "1.0.0")] @@ -45,3 +45,20 @@ pub const fn foobar() {} #[stable(feature = "barfoo", since = "1.0.0")] #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] pub const fn barfoo() {} + +// `rustc_const_stable` also requires the function to be stable. + +#[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] +const fn barfoo_unmarked() {} +//~^ ERROR can only be applied to functions that are declared `#[stable]` + +#[unstable(feature = "unstable", issue = "none")] +#[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] +pub const fn barfoo_unstable() {} +//~^ ERROR can only be applied to functions that are declared `#[stable]` + +// `#[rustc_const_stable_indirect]` also requires a const fn +#[rustc_const_stable_indirect] +#[unstable(feature = "unstable", issue = "none")] +pub fn not_a_const_fn() {} +//~^ ERROR require the function or method to be `const` diff --git a/tests/ui/consts/rustc-const-stability-require-const.stderr b/tests/ui/consts/rustc-const-stability-require-const.stderr index 1027b9311b7a..d9a7d37cbcd2 100644 --- a/tests/ui/consts/rustc-const-stability-require-const.stderr +++ b/tests/ui/consts/rustc-const-stability-require-const.stderr @@ -1,8 +1,6 @@ -error: attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:7:1 | -LL | #[rustc_const_unstable(feature = "const_foo", issue = "none")] - | -------------------------------------------------------------- attribute specified here LL | pub fn foo() {} | ^^^^^^^^^^^^ | @@ -12,11 +10,9 @@ help: make the function or method const LL | pub fn foo() {} | ^^^^^^^^^^^^ -error: attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:12:1 | -LL | #[rustc_const_stable(feature = "const_bar", since = "1.0.0")] - | ------------------------------------------------------------- attribute specified here LL | pub fn bar() {} | ^^^^^^^^^^^^ | @@ -26,11 +22,9 @@ help: make the function or method const LL | pub fn bar() {} | ^^^^^^^^^^^^ -error: attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:21:5 | -LL | #[rustc_const_unstable(feature = "const_salad", issue = "none")] - | ---------------------------------------------------------------- attribute specified here LL | pub fn salad(&self) -> &'static str { "mmmmmm" } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | @@ -40,11 +34,9 @@ help: make the function or method const LL | pub fn salad(&self) -> &'static str { "mmmmmm" } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:26:5 | -LL | #[rustc_const_unstable(feature = "const_roasted", issue = "none")] - | ------------------------------------------------------------------ attribute specified here LL | pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | @@ -54,11 +46,9 @@ help: make the function or method const LL | pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:32:1 | -LL | #[rustc_const_stable(feature = "const_bar", since = "1.0.0")] - | ------------------------------------------------------------- attribute specified here LL | pub extern "C" fn bar_c() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ | @@ -68,11 +58,9 @@ help: make the function or method const LL | pub extern "C" fn bar_c() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ -error: attributes `#[rustc_const_unstable]` and `#[rustc_const_stable]` require the function or method to be `const` +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:37:1 | -LL | #[rustc_const_unstable(feature = "const_foo", issue = "none")] - | -------------------------------------------------------------- attribute specified here LL | pub extern "C" fn foo_c() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ | @@ -82,5 +70,33 @@ help: make the function or method const LL | pub extern "C" fn foo_c() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 6 previous errors +error: attribute `#[rustc_const_stable]` can only be applied to functions that are declared `#[stable]` + --> $DIR/rustc-const-stability-require-const.rs:52:1 + | +LL | #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] + | ---------------------------------------------------------------- attribute specified here +LL | const fn barfoo_unmarked() {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: attribute `#[rustc_const_stable]` can only be applied to functions that are declared `#[stable]` + --> $DIR/rustc-const-stability-require-const.rs:57:1 + | +LL | #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] + | ---------------------------------------------------------------- attribute specified here +LL | pub const fn barfoo_unstable() {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` + --> $DIR/rustc-const-stability-require-const.rs:63:1 + | +LL | pub fn not_a_const_fn() {} + | ^^^^^^^^^^^^^^^^^^^^^^^ + | +help: make the function or method const + --> $DIR/rustc-const-stability-require-const.rs:63:1 + | +LL | pub fn not_a_const_fn() {} + | ^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 9 previous errors diff --git a/tests/ui/consts/unstable-const-stable.rs b/tests/ui/consts/unstable-const-stable.rs deleted file mode 100644 index f69e8d0efe59..000000000000 --- a/tests/ui/consts/unstable-const-stable.rs +++ /dev/null @@ -1,14 +0,0 @@ -//@ aux-build:unstable_but_const_stable.rs - -extern crate unstable_but_const_stable; -use unstable_but_const_stable::*; - -fn main() { - some_unstable_fn(); //~ERROR use of unstable library feature - unsafe { write_bytes(4 as *mut u8, 0, 0) }; //~ERROR use of unstable library feature -} - -const fn const_main() { - some_unstable_fn(); //~ERROR use of unstable library feature - unsafe { write_bytes(4 as *mut u8, 0, 0) }; //~ERROR use of unstable library feature -} diff --git a/tests/ui/consts/unstable-const-stable.stderr b/tests/ui/consts/unstable-const-stable.stderr deleted file mode 100644 index c4ffbbb60db3..000000000000 --- a/tests/ui/consts/unstable-const-stable.stderr +++ /dev/null @@ -1,43 +0,0 @@ -error[E0658]: use of unstable library feature 'unstable' - --> $DIR/unstable-const-stable.rs:7:5 - | -LL | some_unstable_fn(); - | ^^^^^^^^^^^^^^^^ - | - = note: see issue #42 for more information - = help: add `#![feature(unstable)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: use of unstable library feature 'unstable' - --> $DIR/unstable-const-stable.rs:8:14 - | -LL | unsafe { write_bytes(4 as *mut u8, 0, 0) }; - | ^^^^^^^^^^^ - | - = note: see issue #42 for more information - = help: add `#![feature(unstable)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: use of unstable library feature 'unstable' - --> $DIR/unstable-const-stable.rs:12:5 - | -LL | some_unstable_fn(); - | ^^^^^^^^^^^^^^^^ - | - = note: see issue #42 for more information - = help: add `#![feature(unstable)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: use of unstable library feature 'unstable' - --> $DIR/unstable-const-stable.rs:13:14 - | -LL | unsafe { write_bytes(4 as *mut u8, 0, 0) }; - | ^^^^^^^^^^^ - | - = note: see issue #42 for more information - = help: add `#![feature(unstable)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr b/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr index 319056a9c889..d599523c7274 100644 --- a/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr +++ b/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr @@ -1,3 +1,17 @@ +error: can't mark as unstable using an already stable feature + --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 + | +LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this feature is already stable +LL | const fn my_fun() {} + | -------------------- the stability attribute annotates this item + | +help: consider removing the attribute + --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 + | +LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + error: can't mark as unstable using an already stable feature --> $DIR/unstable-attribute-rejects-already-stable-features.rs:6:1 | @@ -13,19 +27,5 @@ help: consider removing the attribute LL | #[unstable(feature = "arbitrary_enum_discriminant", issue = "42")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: can't mark as unstable using an already stable feature - --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 - | -LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this feature is already stable -LL | const fn my_fun() {} - | -------------------- the stability attribute annotates this item - | -help: consider removing the attribute - --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 - | -LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - error: aborting due to 2 previous errors diff --git a/tests/ui/intrinsics/const-eval-select-stability.rs b/tests/ui/intrinsics/const-eval-select-stability.rs index 575bc0cadda1..25cbadaa22dd 100644 --- a/tests/ui/intrinsics/const-eval-select-stability.rs +++ b/tests/ui/intrinsics/const-eval-select-stability.rs @@ -15,7 +15,7 @@ const fn nothing(){} #[rustc_const_stable(since = "1.0", feature = "const_hey")] pub const fn hey() { const_eval_select((), nothing, log); - //~^ ERROR `const_eval_select` is not yet stable as a const fn + //~^ ERROR cannot use `#[feature(const_eval_select)]` } fn main() {} diff --git a/tests/ui/intrinsics/const-eval-select-stability.stderr b/tests/ui/intrinsics/const-eval-select-stability.stderr index 335b9877aa00..5f443b1d4ff7 100644 --- a/tests/ui/intrinsics/const-eval-select-stability.stderr +++ b/tests/ui/intrinsics/const-eval-select-stability.stderr @@ -1,10 +1,19 @@ -error: `const_eval_select` is not yet stable as a const fn +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(const_eval_select)]` --> $DIR/const-eval-select-stability.rs:17:5 | LL | const_eval_select((), nothing, log); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions +help: if the function is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | pub const fn hey() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(const_eval_select)] +LL | pub const fn hey() { + | error: aborting due to 1 previous error diff --git a/tests/ui/stability-attribute/const-stability-attribute-implies-missing.rs b/tests/ui/stability-attribute/const-stability-attribute-implies-missing.rs index 4089ec728852..6d6d793c62b7 100644 --- a/tests/ui/stability-attribute/const-stability-attribute-implies-missing.rs +++ b/tests/ui/stability-attribute/const-stability-attribute-implies-missing.rs @@ -14,4 +14,3 @@ pub const fn foobar() -> u32 { } const VAR: u32 = foobar(); -//~^ ERROR: `foobar` is not yet stable as a const fn diff --git a/tests/ui/stability-attribute/const-stability-attribute-implies-missing.stderr b/tests/ui/stability-attribute/const-stability-attribute-implies-missing.stderr index 918d6ebf9922..232de41c769e 100644 --- a/tests/ui/stability-attribute/const-stability-attribute-implies-missing.stderr +++ b/tests/ui/stability-attribute/const-stability-attribute-implies-missing.stderr @@ -4,13 +4,5 @@ error: feature `const_bar` implying `const_foobar` does not exist LL | #[rustc_const_unstable(feature = "const_foobar", issue = "1", implied_by = "const_bar")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: `foobar` is not yet stable as a const fn - --> $DIR/const-stability-attribute-implies-missing.rs:16:18 - | -LL | const VAR: u32 = foobar(); - | ^^^^^^^^ - | - = help: add `#![feature(const_foobar)]` to the crate attributes to enable - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/stability-attribute/missing-const-stability.rs b/tests/ui/stability-attribute/missing-const-stability.rs index 82da18cc9ac2..f11396525500 100644 --- a/tests/ui/stability-attribute/missing-const-stability.rs +++ b/tests/ui/stability-attribute/missing-const-stability.rs @@ -1,6 +1,6 @@ //@ compile-flags: -Znext-solver #![feature(staged_api)] -#![feature(const_trait_impl, effects)] //~ WARN the feature `effects` is incomplete +#![feature(const_trait_impl, effects, rustc_attrs, intrinsics)] //~ WARN the feature `effects` is incomplete #![stable(feature = "stable", since = "1.0.0")] #[stable(feature = "stable", since = "1.0.0")] @@ -31,4 +31,15 @@ impl const Bar for Foo { fn fun() {} } +#[stable(feature = "stable", since = "1.0.0")] +#[rustc_intrinsic] +pub const unsafe fn size_of_val(x: *const T) -> usize { 42 } +//~^ ERROR function has missing const stability attribute + +extern "rust-intrinsic" { + #[stable(feature = "stable", since = "1.0.0")] + #[rustc_const_stable_indirect] + pub fn min_align_of_val(x: *const T) -> usize; +} + fn main() {} diff --git a/tests/ui/stability-attribute/missing-const-stability.stderr b/tests/ui/stability-attribute/missing-const-stability.stderr index adf60c386114..e62a8b882616 100644 --- a/tests/ui/stability-attribute/missing-const-stability.stderr +++ b/tests/ui/stability-attribute/missing-const-stability.stderr @@ -1,7 +1,7 @@ warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/missing-const-stability.rs:3:30 | -LL | #![feature(const_trait_impl, effects)] +LL | #![feature(const_trait_impl, effects, rustc_attrs, intrinsics)] | ^^^^^^^ | = note: see issue #102090 for more information @@ -22,11 +22,17 @@ LL | | fn fun() {} LL | | } | |_^ +error: function has missing const stability attribute + --> $DIR/missing-const-stability.rs:36:1 + | +LL | pub const unsafe fn size_of_val(x: *const T) -> usize { 42 } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + error: associated function has missing const stability attribute --> $DIR/missing-const-stability.rs:16:5 | LL | pub const fn foo() {} | ^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/ui/target-feature/feature-hierarchy.rs b/tests/ui/target-feature/feature-hierarchy.rs index 4cf9112810cc..7f14d700ecba 100644 --- a/tests/ui/target-feature/feature-hierarchy.rs +++ b/tests/ui/target-feature/feature-hierarchy.rs @@ -19,6 +19,7 @@ trait Copy {} impl Copy for bool {} extern "rust-intrinsic" { + #[stable(feature = "test", since = "1.0.0")] #[rustc_const_stable(feature = "test", since = "1.0.0")] fn unreachable() -> !; } diff --git a/tests/ui/target-feature/no-llvm-leaks.rs b/tests/ui/target-feature/no-llvm-leaks.rs index 9f5dec4447fb..f0c887bc1e0f 100644 --- a/tests/ui/target-feature/no-llvm-leaks.rs +++ b/tests/ui/target-feature/no-llvm-leaks.rs @@ -17,6 +17,7 @@ trait Copy {} impl Copy for bool {} extern "rust-intrinsic" { + #[stable(feature = "test", since = "1.0.0")] #[rustc_const_stable(feature = "test", since = "1.0.0")] fn unreachable() -> !; } diff --git a/tests/ui/traits/const-traits/auxiliary/staged-api.rs b/tests/ui/traits/const-traits/auxiliary/staged-api.rs index 986165ef91e6..bb591321b84f 100644 --- a/tests/ui/traits/const-traits/auxiliary/staged-api.rs +++ b/tests/ui/traits/const-traits/auxiliary/staged-api.rs @@ -19,3 +19,12 @@ pub struct Unstable; impl const MyTrait for Unstable { fn func() {} } + +#[stable(feature = "rust1", since = "1.0.0")] +pub struct Unstable2; + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "unstable2", issue = "none")] +impl const MyTrait for Unstable2 { + fn func() {} +} diff --git a/tests/ui/traits/const-traits/effects/minicore.rs b/tests/ui/traits/const-traits/effects/minicore.rs index a756f4d9f6c5..1f0d22eeb38b 100644 --- a/tests/ui/traits/const-traits/effects/minicore.rs +++ b/tests/ui/traits/const-traits/effects/minicore.rs @@ -515,7 +515,7 @@ trait StructuralPartialEq {} const fn drop(_: T) {} -#[rustc_const_stable(feature = "const_eval_select", since = "1.0.0")] +#[rustc_const_stable_indirect] #[rustc_intrinsic_must_be_overridden] #[rustc_intrinsic] const fn const_eval_select( diff --git a/tests/ui/traits/const-traits/issue-79450.rs b/tests/ui/traits/const-traits/issue-79450.rs index b8b9e07b3bd6..cdefebc87d67 100644 --- a/tests/ui/traits/const-traits/issue-79450.rs +++ b/tests/ui/traits/const-traits/issue-79450.rs @@ -1,6 +1,5 @@ //@ compile-flags: -Znext-solver #![allow(incomplete_features)] -#![feature(const_fmt_arguments_new)] #![feature(const_trait_impl, effects)] #[const_trait] diff --git a/tests/ui/traits/const-traits/issue-79450.stderr b/tests/ui/traits/const-traits/issue-79450.stderr index 9e6348d37ed5..49f380c1a2b5 100644 --- a/tests/ui/traits/const-traits/issue-79450.stderr +++ b/tests/ui/traits/const-traits/issue-79450.stderr @@ -1,5 +1,5 @@ error[E0015]: cannot call non-const fn `_print` in constant functions - --> $DIR/issue-79450.rs:11:9 + --> $DIR/issue-79450.rs:10:9 | LL | println!("lul"); | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/traits/const-traits/staged-api.rs b/tests/ui/traits/const-traits/staged-api.rs index f87e723472ad..59fe6d52d5d7 100644 --- a/tests/ui/traits/const-traits/staged-api.rs +++ b/tests/ui/traits/const-traits/staged-api.rs @@ -2,6 +2,7 @@ //@ compile-flags: -Znext-solver #![cfg_attr(unstable, feature(unstable))] // The feature from the ./auxiliary/staged-api.rs file. +#![cfg_attr(unstable, feature(local_feature))] #![feature(const_trait_impl, effects)] #![allow(incomplete_features)] #![feature(staged_api)] @@ -16,8 +17,8 @@ use staged_api::*; pub struct Foo; #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(unstable, rustc_const_unstable(feature = "foo", issue = "none"))] -#[cfg_attr(stable, rustc_const_stable(feature = "foo", since = "1.0.0"))] +#[cfg_attr(unstable, rustc_const_unstable(feature = "local_feature", issue = "none"))] +#[cfg_attr(stable, rustc_const_stable(feature = "local_feature", since = "1.0.0"))] impl const MyTrait for Foo { //[stable]~^ ERROR trait implementations cannot be const stable yet fn func() {} @@ -32,32 +33,43 @@ fn non_const_context() { #[unstable(feature = "none", issue = "none")] const fn const_context() { Unstable::func(); - //[stable]~^ ERROR not yet stable as a const fn + //[unstable]~^ ERROR cannot use `#[feature(unstable)]` + //[stable]~^^ ERROR not yet stable as a const fn Foo::func(); - //[unstable]~^ ERROR not yet stable as a const fn - // ^ fails, because the `foo` feature is not active + //[unstable]~^ ERROR cannot use `#[feature(local_feature)]` + //[stable]~^^ cannot be (indirectly) exposed to stable + // We get the error on `stable` since this is a trait function. + Unstable2::func(); + //~^ ERROR not yet stable as a const fn + // ^ fails, because the `unstable2` feature is not active } #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(unstable, rustc_const_unstable(feature = "foo", issue = "none"))] +#[cfg_attr(unstable, rustc_const_unstable(feature = "local_feature", issue = "none"))] pub const fn const_context_not_const_stable() { //[stable]~^ ERROR function has missing const stability attribute Unstable::func(); //[stable]~^ ERROR not yet stable as a const fn Foo::func(); - //[unstable]~^ ERROR not yet stable as a const fn - // ^ fails, because the `foo` feature is not active + //[stable]~^ cannot be (indirectly) exposed to stable + // We get the error on `stable` since this is a trait function. + Unstable2::func(); + //~^ ERROR not yet stable as a const fn + // ^ fails, because the `unstable2` feature is not active } #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "cheese", since = "1.0.0")] const fn stable_const_context() { Unstable::func(); - //~^ ERROR not yet stable as a const fn + //[unstable]~^ ERROR cannot use `#[feature(unstable)]` + //[stable]~^^ ERROR not yet stable as a const fn Foo::func(); - //[unstable]~^ ERROR not yet stable as a const fn + //[unstable]~^ ERROR cannot use `#[feature(local_feature)]` + //[stable]~^^ cannot be (indirectly) exposed to stable + // We get the error on `stable` since this is a trait function. const_context_not_const_stable() - //[unstable]~^ ERROR not yet stable as a const fn + //[unstable]~^ ERROR cannot use `#[feature(local_feature)]` } fn main() {} diff --git a/tests/ui/traits/const-traits/staged-api.stable.stderr b/tests/ui/traits/const-traits/staged-api.stable.stderr index 6c07a253f5b0..40045081f93c 100644 --- a/tests/ui/traits/const-traits/staged-api.stable.stderr +++ b/tests/ui/traits/const-traits/staged-api.stable.stderr @@ -1,5 +1,5 @@ error: trait implementations cannot be const stable yet - --> $DIR/staged-api.rs:21:1 + --> $DIR/staged-api.rs:22:1 | LL | / impl const MyTrait for Foo { LL | | @@ -10,40 +10,80 @@ LL | | } = note: see issue #67792 for more information error: function has missing const stability attribute - --> $DIR/staged-api.rs:43:1 + --> $DIR/staged-api.rs:49:1 | LL | / pub const fn const_context_not_const_stable() { LL | | LL | | Unstable::func(); LL | | ... | -LL | | // ^ fails, because the `foo` feature is not active +LL | | // ^ fails, because the `unstable2` feature is not active LL | | } | |_^ error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:34:5 + --> $DIR/staged-api.rs:35:5 | LL | Unstable::func(); | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(unstable)]` to the crate attributes to enable +error: `::func` cannot be (indirectly) exposed to stable + --> $DIR/staged-api.rs:38:5 + | +LL | Foo::func(); + | ^^^^^^^^^^^ + | + = help: either mark the callee as `#[rustc_const_stable_indirect]`, or the caller as `#[rustc_const_unstable]` + +error: `::func` is not yet stable as a const fn + --> $DIR/staged-api.rs:42:5 + | +LL | Unstable2::func(); + | ^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable2)]` to the crate attributes to enable + error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:45:5 + --> $DIR/staged-api.rs:51:5 | LL | Unstable::func(); | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(unstable)]` to the crate attributes to enable +error: `::func` cannot be (indirectly) exposed to stable + --> $DIR/staged-api.rs:53:5 + | +LL | Foo::func(); + | ^^^^^^^^^^^ + | + = help: either mark the callee as `#[rustc_const_stable_indirect]`, or the caller as `#[rustc_const_unstable]` + +error: `::func` is not yet stable as a const fn + --> $DIR/staged-api.rs:56:5 + | +LL | Unstable2::func(); + | ^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable2)]` to the crate attributes to enable + error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:55:5 + --> $DIR/staged-api.rs:64:5 | LL | Unstable::func(); | ^^^^^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: add `#![feature(unstable)]` to the crate attributes to enable -error: aborting due to 5 previous errors +error: `::func` cannot be (indirectly) exposed to stable + --> $DIR/staged-api.rs:67:5 + | +LL | Foo::func(); + | ^^^^^^^^^^^ + | + = help: either mark the callee as `#[rustc_const_stable_indirect]`, or the caller as `#[rustc_const_unstable]` + +error: aborting due to 10 previous errors diff --git a/tests/ui/traits/const-traits/staged-api.unstable.stderr b/tests/ui/traits/const-traits/staged-api.unstable.stderr index 1c772f13dd51..64b3a8ab19f1 100644 --- a/tests/ui/traits/const-traits/staged-api.unstable.stderr +++ b/tests/ui/traits/const-traits/staged-api.unstable.stderr @@ -1,42 +1,108 @@ -error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:36:5 - | -LL | Foo::func(); - | ^^^^^^^^^^^ - | - = help: add `#![feature(foo)]` to the crate attributes to enable - -error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:47:5 - | -LL | Foo::func(); - | ^^^^^^^^^^^ - | - = help: add `#![feature(foo)]` to the crate attributes to enable - -error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:55:5 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(unstable)]` + --> $DIR/staged-api.rs:35:5 | LL | Unstable::func(); | ^^^^^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_context() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(unstable)] +LL | const fn const_context() { + | -error: `::func` is not yet stable as a const fn - --> $DIR/staged-api.rs:57:5 +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local_feature)]` + --> $DIR/staged-api.rs:38:5 | LL | Foo::func(); | ^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_context() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(local_feature)] +LL | const fn const_context() { + | -error: `const_context_not_const_stable` is not yet stable as a const fn - --> $DIR/staged-api.rs:59:5 +error: `::func` is not yet stable as a const fn + --> $DIR/staged-api.rs:42:5 + | +LL | Unstable2::func(); + | ^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable2)]` to the crate attributes to enable + +error: `::func` is not yet stable as a const fn + --> $DIR/staged-api.rs:56:5 + | +LL | Unstable2::func(); + | ^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable2)]` to the crate attributes to enable + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(unstable)]` + --> $DIR/staged-api.rs:64:5 + | +LL | Unstable::func(); + | ^^^^^^^^^^^^^^^^ + | + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn stable_const_context() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(unstable)] +LL | const fn stable_const_context() { + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local_feature)]` + --> $DIR/staged-api.rs:67:5 + | +LL | Foo::func(); + | ^^^^^^^^^^^ + | + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn stable_const_context() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(local_feature)] +LL | const fn stable_const_context() { + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local_feature)]` + --> $DIR/staged-api.rs:71:5 | LL | const_context_not_const_stable() | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: const-stable functions can only call other const-stable functions + = help: mark the callee as `#[rustc_const_stable_indirect]` if it does not itself require any unsafe features +help: if the caller is not (yet) meant to be exposed to stable, add `#[rustc_const_unstable]` (this is what you probably want to do) + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn stable_const_context() { + | +help: otherwise, as a last resort `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks (this requires team approval) + | +LL + #[rustc_allow_const_fn_unstable(local_feature)] +LL | const fn stable_const_context() { + | -error: aborting due to 5 previous errors +error: aborting due to 7 previous errors From 3854e16fa2b2ee004ff2cbc71b28f9de28306942 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 7 Oct 2024 17:27:37 +0200 Subject: [PATCH 253/366] proc_macro_harness: adjust the span we use for const fn calls --- .../src/proc_macro_harness.rs | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index d6603af101af..707c36d5046a 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -313,14 +313,23 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { match m { ProcMacro::Derive(cd) => { cx.resolver.declare_proc_macro(cd.id); - cx.expr_call(span, proc_macro_ty_method_path(cx, custom_derive), thin_vec![ - cx.expr_str(span, cd.trait_name), - cx.expr_array_ref( - span, - cd.attrs.iter().map(|&s| cx.expr_str(span, s)).collect::>(), - ), - local_path(cx, cd.function_name), - ]) + // The call needs to use `harness_span` so that the const stability checker + // accepts it. + cx.expr_call( + harness_span, + proc_macro_ty_method_path(cx, custom_derive), + thin_vec![ + cx.expr_str(span, cd.trait_name), + cx.expr_array_ref( + span, + cd.attrs + .iter() + .map(|&s| cx.expr_str(span, s)) + .collect::>(), + ), + local_path(cx, cd.function_name), + ], + ) } ProcMacro::Attr(ca) | ProcMacro::Bang(ca) => { cx.resolver.declare_proc_macro(ca.id); @@ -330,7 +339,9 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { ProcMacro::Derive(_) => unreachable!(), }; - cx.expr_call(span, proc_macro_ty_method_path(cx, ident), thin_vec![ + // The call needs to use `harness_span` so that the const stability checker + // accepts it. + cx.expr_call(harness_span, proc_macro_ty_method_path(cx, ident), thin_vec![ cx.expr_str(span, ca.function_name.name), local_path(cx, ca.function_name), ]) From 16b9bb744da42ef89e46f6feaf3497639b9b55e0 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 8 Oct 2024 14:11:44 +0200 Subject: [PATCH 254/366] get rid of the internal unlikely macro --- library/core/src/intrinsics.rs | 10 ++++++++-- library/core/src/num/int_macros.rs | 30 ++++++++++++++--------------- library/core/src/num/mod.rs | 7 ------- library/core/src/num/uint_macros.rs | 16 +++++++-------- library/core/tests/lib.rs | 1 - 5 files changed, 31 insertions(+), 33 deletions(-) diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index ff053916d96d..15f2a13eea2d 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -986,7 +986,10 @@ pub const unsafe fn assume(b: bool) { /// any safety invariants. /// /// This intrinsic does not have a stable counterpart. -#[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_likely", issue = "none"))] +#[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_likely", since = "CURRENT_RUSTC_VERSION") +)] #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] @@ -1007,7 +1010,10 @@ pub const fn likely(b: bool) -> bool { /// any safety invariants. /// /// This intrinsic does not have a stable counterpart. -#[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_likely", issue = "none"))] +#[cfg_attr( + bootstrap, + rustc_const_stable(feature = "const_likely", since = "CURRENT_RUSTC_VERSION") +)] #[cfg_attr(not(bootstrap), rustc_const_stable_indirect)] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 7241b3ff6a3b..1d640ea74c4a 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -449,7 +449,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_add(self, rhs: Self) -> Option { let (a, b) = self.overflowing_add(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict integer addition. Computes `self + rhs`, panicking @@ -545,7 +545,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_add_unsigned(self, rhs: $UnsignedT) -> Option { let (a, b) = self.overflowing_add_unsigned(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict addition with an unsigned integer. Computes `self + rhs`, @@ -601,7 +601,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_sub(self, rhs: Self) -> Option { let (a, b) = self.overflowing_sub(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict integer subtraction. Computes `self - rhs`, panicking if @@ -697,7 +697,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_sub_unsigned(self, rhs: $UnsignedT) -> Option { let (a, b) = self.overflowing_sub_unsigned(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict subtraction with an unsigned integer. Computes `self - rhs`, @@ -753,7 +753,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_mul(self, rhs: Self) -> Option { let (a, b) = self.overflowing_mul(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict integer multiplication. Computes `self * rhs`, panicking if @@ -849,7 +849,7 @@ macro_rules! int_impl { without modifying the original"] #[inline] pub const fn checked_div(self, rhs: Self) -> Option { - if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) { + if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) { None } else { // SAFETY: div by zero and by INT_MIN have been checked above @@ -924,7 +924,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_div_euclid(self, rhs: Self) -> Option { // Using `&` helps LLVM see that it is the same check made in division. - if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) { + if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) { None } else { Some(self.div_euclid(rhs)) @@ -997,7 +997,7 @@ macro_rules! int_impl { without modifying the original"] #[inline] pub const fn checked_rem(self, rhs: Self) -> Option { - if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) { + if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) { None } else { // SAFETY: div by zero and by INT_MIN have been checked above @@ -1071,7 +1071,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_rem_euclid(self, rhs: Self) -> Option { // Using `&` helps LLVM see that it is the same check made in division. - if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) { + if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) { None } else { Some(self.rem_euclid(rhs)) @@ -1142,7 +1142,7 @@ macro_rules! int_impl { #[inline] pub const fn checked_neg(self) -> Option { let (a, b) = self.overflowing_neg(); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Unchecked negation. Computes `-self`, assuming overflow cannot occur. @@ -2564,7 +2564,7 @@ macro_rules! int_impl { without modifying the original"] pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) { // Using `&` helps LLVM see that it is the same check made in division. - if unlikely!((self == Self::MIN) & (rhs == -1)) { + if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) { (self, true) } else { (self / rhs, false) @@ -2595,7 +2595,7 @@ macro_rules! int_impl { without modifying the original"] pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) { // Using `&` helps LLVM see that it is the same check made in division. - if unlikely!((self == Self::MIN) & (rhs == -1)) { + if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) { (self, true) } else { (self.div_euclid(rhs), false) @@ -2625,7 +2625,7 @@ macro_rules! int_impl { #[must_use = "this returns the result of the operation, \ without modifying the original"] pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) { - if unlikely!(rhs == -1) { + if intrinsics::unlikely(rhs == -1) { (0, self == Self::MIN) } else { (self % rhs, false) @@ -2657,7 +2657,7 @@ macro_rules! int_impl { #[inline] #[track_caller] pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) { - if unlikely!(rhs == -1) { + if intrinsics::unlikely(rhs == -1) { (0, self == Self::MIN) } else { (self.rem_euclid(rhs), false) @@ -2686,7 +2686,7 @@ macro_rules! int_impl { without modifying the original"] #[allow(unused_attributes)] pub const fn overflowing_neg(self) -> (Self, bool) { - if unlikely!(self == Self::MIN) { + if intrinsics::unlikely(self == Self::MIN) { (Self::MIN, true) } else { (-self, false) diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 05ecfe431d02..f95cfd33ae5d 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -16,13 +16,6 @@ macro_rules! try_opt { }; } -#[cfg_attr(bootstrap, allow_internal_unstable(const_likely))] -macro_rules! unlikely { - ($e: expr) => { - intrinsics::unlikely($e) - }; -} - // Use this when the generated code should differ between signed and unsigned types. macro_rules! sign_dependent_expr { (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => { diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 8e62fd85912d..562eab166305 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -491,7 +491,7 @@ macro_rules! uint_impl { // Per , // LLVM is happy to re-form the intrinsic later if useful. - if unlikely!(intrinsics::add_with_overflow(self, rhs).1) { + if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) { None } else { // SAFETY: Just checked it doesn't overflow @@ -593,7 +593,7 @@ macro_rules! uint_impl { #[inline] pub const fn checked_add_signed(self, rhs: $SignedT) -> Option { let (a, b) = self.overflowing_add_signed(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict addition with a signed integer. Computes `self + rhs`, @@ -845,7 +845,7 @@ macro_rules! uint_impl { #[inline] pub const fn checked_mul(self, rhs: Self) -> Option { let (a, b) = self.overflowing_mul(rhs); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict integer multiplication. Computes `self * rhs`, panicking if @@ -940,7 +940,7 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn checked_div(self, rhs: Self) -> Option { - if unlikely!(rhs == 0) { + if intrinsics::unlikely(rhs == 0) { None } else { // SAFETY: div by zero has been checked above and unsigned types have no other @@ -1001,7 +1001,7 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn checked_div_euclid(self, rhs: Self) -> Option { - if unlikely!(rhs == 0) { + if intrinsics::unlikely(rhs == 0) { None } else { Some(self.div_euclid(rhs)) @@ -1061,7 +1061,7 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn checked_rem(self, rhs: Self) -> Option { - if unlikely!(rhs == 0) { + if intrinsics::unlikely(rhs == 0) { None } else { // SAFETY: div by zero has been checked above and unsigned types have no other @@ -1123,7 +1123,7 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn checked_rem_euclid(self, rhs: Self) -> Option { - if unlikely!(rhs == 0) { + if intrinsics::unlikely(rhs == 0) { None } else { Some(self.rem_euclid(rhs)) @@ -1362,7 +1362,7 @@ macro_rules! uint_impl { #[inline] pub const fn checked_neg(self) -> Option { let (a, b) = self.overflowing_neg(); - if unlikely!(b) { None } else { Some(a) } + if intrinsics::unlikely(b) { None } else { Some(a) } } /// Strict negation. Computes `-self`, panicking unless `self == diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 5719d29659af..8c8987188655 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -1,5 +1,4 @@ // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(const_likely))] #![cfg_attr(bootstrap, feature(strict_provenance))] #![cfg_attr(not(bootstrap), feature(strict_provenance_lints))] #![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] From 36dda4571dc3b98ac9759b8af67887e170a426d7 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 8 Oct 2024 19:03:35 +0200 Subject: [PATCH 255/366] add a HACK to allow stdarch migration --- compiler/rustc_passes/src/stability.rs | 3 +++ .../rustc-const-stability-require-const.rs | 5 +++-- ...rustc-const-stability-require-const.stderr | 22 +++---------------- 3 files changed, 9 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index a3165410854c..e24e6a486f4a 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -189,6 +189,9 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { && let Some(fn_sig) = fn_sig && const_stab.is_const_stable() && !stab.is_some_and(|(s, _)| s.is_stable()) + // FIXME: we skip this check targets until + // propagates. + && false { self.tcx .dcx() diff --git a/tests/ui/consts/rustc-const-stability-require-const.rs b/tests/ui/consts/rustc-const-stability-require-const.rs index 6cc3f0f0da12..1c66f6e2aa5e 100644 --- a/tests/ui/consts/rustc-const-stability-require-const.rs +++ b/tests/ui/consts/rustc-const-stability-require-const.rs @@ -47,15 +47,16 @@ pub const fn foobar() {} pub const fn barfoo() {} // `rustc_const_stable` also requires the function to be stable. +// FIXME: these are disabled until propagates. #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] const fn barfoo_unmarked() {} -//~^ ERROR can only be applied to functions that are declared `#[stable]` +// FIXME disabled ERROR can only be applied to functions that are declared `#[stable]` #[unstable(feature = "unstable", issue = "none")] #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] pub const fn barfoo_unstable() {} -//~^ ERROR can only be applied to functions that are declared `#[stable]` +// FIXME disabled ERROR can only be applied to functions that are declared `#[stable]` // `#[rustc_const_stable_indirect]` also requires a const fn #[rustc_const_stable_indirect] diff --git a/tests/ui/consts/rustc-const-stability-require-const.stderr b/tests/ui/consts/rustc-const-stability-require-const.stderr index d9a7d37cbcd2..09b96ce6f835 100644 --- a/tests/ui/consts/rustc-const-stability-require-const.stderr +++ b/tests/ui/consts/rustc-const-stability-require-const.stderr @@ -70,33 +70,17 @@ help: make the function or method const LL | pub extern "C" fn foo_c() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ -error: attribute `#[rustc_const_stable]` can only be applied to functions that are declared `#[stable]` - --> $DIR/rustc-const-stability-require-const.rs:52:1 - | -LL | #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] - | ---------------------------------------------------------------- attribute specified here -LL | const fn barfoo_unmarked() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: attribute `#[rustc_const_stable]` can only be applied to functions that are declared `#[stable]` - --> $DIR/rustc-const-stability-require-const.rs:57:1 - | -LL | #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] - | ---------------------------------------------------------------- attribute specified here -LL | pub const fn barfoo_unstable() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` - --> $DIR/rustc-const-stability-require-const.rs:63:1 + --> $DIR/rustc-const-stability-require-const.rs:64:1 | LL | pub fn not_a_const_fn() {} | ^^^^^^^^^^^^^^^^^^^^^^^ | help: make the function or method const - --> $DIR/rustc-const-stability-require-const.rs:63:1 + --> $DIR/rustc-const-stability-require-const.rs:64:1 | LL | pub fn not_a_const_fn() {} | ^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 9 previous errors +error: aborting due to 7 previous errors From 8849ac6042770500db91aca860ec8d86af2c74a3 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 12 Oct 2024 20:37:35 +0200 Subject: [PATCH 256/366] tcx.is_const_fn doesn't work the way it is described, remove it Then we can rename the _raw functions to drop their suffix, and instead explicitly use is_stable_const_fn for the few cases where that is really what you want. --- .../src/check_consts/check.rs | 2 +- .../rustc_const_eval/src/check_consts/mod.rs | 2 +- .../rustc_const_eval/src/check_consts/ops.rs | 4 +- .../src/const_eval/machine.rs | 4 +- compiler/rustc_hir_analysis/src/collect.rs | 2 +- compiler/rustc_hir_typeck/src/callee.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 2 +- compiler/rustc_middle/src/hir/map/mod.rs | 2 +- compiler/rustc_middle/src/mir/graphviz.rs | 2 +- compiler/rustc_middle/src/mir/pretty.rs | 2 +- compiler/rustc_middle/src/query/mod.rs | 7 ++-- compiler/rustc_middle/src/ty/context.rs | 41 ++++++------------- compiler/rustc_middle/src/ty/mod.rs | 5 ++- .../rustc_mir_transform/src/promote_consts.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 2 +- compiler/rustc_passes/src/stability.rs | 8 ++-- .../src/traits/select/candidate_assembly.rs | 4 +- src/librustdoc/clean/types.rs | 4 +- .../clippy_utils/src/qualify_min_const_fn.rs | 16 +++++--- src/tools/clippy/clippy_utils/src/visitors.rs | 4 +- 21 files changed, 55 insertions(+), 64 deletions(-) diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index ef01fe88979a..8f1a887a9614 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -731,7 +731,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { } // Trait functions are not `const fn` so we have to skip them here. - if !tcx.is_const_fn_raw(callee) && !is_trait { + if !tcx.is_const_fn(callee) && !is_trait { self.check_op(ops::FnCallNonConst { caller, callee, diff --git a/compiler/rustc_const_eval/src/check_consts/mod.rs b/compiler/rustc_const_eval/src/check_consts/mod.rs index 146b559f2d74..56da67918473 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -112,7 +112,7 @@ pub fn is_safe_to_expose_on_stable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> b } // Const-stability is only relevant for `const fn`. - assert!(tcx.is_const_fn_raw(def_id)); + assert!(tcx.is_const_fn(def_id)); match tcx.lookup_const_stability(def_id) { None => { diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index 0f151dcdb034..3ac06ae64910 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -122,7 +122,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { if let Ok(Some(ImplSource::UserDefined(data))) = implsrc { // FIXME(effects) revisit this - if !tcx.is_const_trait_impl_raw(data.impl_def_id) { + if !tcx.is_const_trait_impl(data.impl_def_id) { let span = tcx.def_span(data.impl_def_id); err.subdiagnostic(errors::NonConstImplNote { span }); } @@ -174,7 +174,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { let note = match self_ty.kind() { FnDef(def_id, ..) => { let span = tcx.def_span(*def_id); - if ccx.tcx.is_const_fn_raw(*def_id) { + if ccx.tcx.is_const_fn(*def_id) { span_bug!(span, "calling const FnDef errored when it shouldn't"); } diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 7793de9c9333..d54c5b750f09 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -431,8 +431,8 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { // sensitive check here. But we can at least rule out functions that are not const at // all. That said, we have to allow calling functions inside a trait marked with // #[const_trait]. These *are* const-checked! - // FIXME: why does `is_const_fn_raw` not classify them as const? - if (!ecx.tcx.is_const_fn_raw(def) && !ecx.tcx.is_const_default_method(def)) + // FIXME(effects): why does `is_const_fn` not classify them as const? + if (!ecx.tcx.is_const_fn(def) && !ecx.tcx.is_const_default_method(def)) || ecx.tcx.has_attr(def, sym::rustc_do_not_const_check) { // We certainly do *not* want to actually call the fn diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index f46b7a8bc9cc..3add801cf564 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1597,7 +1597,7 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option FnCtxt<'a, 'tcx> { // // This check is here because there is currently no way to express a trait bound for `FnDef` types only. if let ty::FnDef(def_id, _args) = *arg_ty.kind() { - if idx == 0 && !self.tcx.is_const_fn_raw(def_id) { + if idx == 0 && !self.tcx.is_const_fn(def_id) { self.dcx().emit_err(errors::ConstSelectMustBeConst { span }); } } else { diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index da231acbb0f6..92c2a9060558 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1751,7 +1751,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // to tell them that in the diagnostic. Does not affect typeck. let is_constable = match element.kind { hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() { - ty::FnDef(def_id, _) if tcx.is_const_fn(def_id) => traits::IsConstable::Fn, + ty::FnDef(def_id, _) if tcx.is_stable_const_fn(def_id) => traits::IsConstable::Fn, _ => traits::IsConstable::No, }, hir::ExprKind::Path(qpath) => { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index e06c86ae4c03..47f7a8b7c201 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1081,7 +1081,7 @@ fn should_encode_mir( && (generics.requires_monomorphization(tcx) || tcx.cross_crate_inlinable(def_id))); // The function has a `const` modifier or is in a `#[const_trait]`. - let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) + let is_const_fn = tcx.is_const_fn(def_id.to_def_id()) || tcx.is_const_default_method(def_id.to_def_id()); (is_const_fn, opt) } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 8fd5ff1f369d..926691013dd8 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -329,7 +329,7 @@ impl<'hir> Map<'hir> { BodyOwnerKind::Static(mutability) => ConstContext::Static(mutability), BodyOwnerKind::Fn if self.tcx.is_constructor(def_id) => return None, - BodyOwnerKind::Fn | BodyOwnerKind::Closure if self.tcx.is_const_fn_raw(def_id) => { + BodyOwnerKind::Fn | BodyOwnerKind::Closure if self.tcx.is_const_fn(def_id) => { ConstContext::ConstFn } BodyOwnerKind::Fn if self.tcx.is_const_default_method(def_id) => ConstContext::ConstFn, diff --git a/compiler/rustc_middle/src/mir/graphviz.rs b/compiler/rustc_middle/src/mir/graphviz.rs index a3fe8f9cffa6..7bb41193d5c9 100644 --- a/compiler/rustc_middle/src/mir/graphviz.rs +++ b/compiler/rustc_middle/src/mir/graphviz.rs @@ -17,7 +17,7 @@ where let mirs = def_ids .iter() .flat_map(|def_id| { - if tcx.is_const_fn_raw(*def_id) { + if tcx.is_const_fn(*def_id) { vec![tcx.optimized_mir(*def_id), tcx.mir_for_ctfe(*def_id)] } else { vec![tcx.instance_mir(ty::InstanceKind::Item(*def_id))] diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index faa022b50ef1..e690bf74b6b4 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -317,7 +317,7 @@ pub fn write_mir_pretty<'tcx>( }; // For `const fn` we want to render both the optimized MIR and the MIR for ctfe. - if tcx.is_const_fn_raw(def_id) { + if tcx.is_const_fn(def_id) { render_body(w, tcx.optimized_mir(def_id))?; writeln!(w)?; writeln!(w, "// MIR FOR CTFE")?; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index d03fc39c9ade..94bdb913528b 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -741,12 +741,11 @@ rustc_queries! { desc { |tcx| "computing drop-check constraints for `{}`", tcx.def_path_str(key) } } - /// Returns `true` if this is a const fn, use the `is_const_fn` to know whether your crate - /// actually sees it as const fn (e.g., the const-fn-ness might be unstable and you might - /// not have the feature gate active). + /// Returns `true` if this is a const fn / const impl. /// /// **Do not call this function manually.** It is only meant to cache the base data for the - /// `is_const_fn` function. Consider using `is_const_fn` or `is_const_fn_raw` instead. + /// higher-level functions. Consider using `is_const_fn` or `is_const_trait_impl` instead. + /// Also note that neither of them takes into account feature gates and stability. query constness(key: DefId) -> hir::Constness { desc { |tcx| "checking if item is const: `{}`", tcx.def_path_str(key) } separate_provide_extern diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 1c6a5e9011f4..a6a0a6dc222c 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -3120,39 +3120,24 @@ impl<'tcx> TyCtxt<'tcx> { } } - /// Whether the `def_id` counts as const fn in the current crate, considering all active - /// feature gates - pub fn is_const_fn(self, def_id: DefId) -> bool { - if self.is_const_fn_raw(def_id) { - match self.lookup_const_stability(def_id) { - Some(stability) if stability.is_const_unstable() => { - // has a `rustc_const_unstable` attribute, check whether the user enabled the - // corresponding feature gate. - stability.feature.is_some_and(|f| self.features().enabled(f)) - } - // functions without const stability are either stable user written - // const fn or the user is using feature gates and we thus don't - // care what they do - _ => true, + /// Whether `def_id` is a stable const fn (i.e., doesn't need any feature gates to be called). + /// + /// When this is `false`, the function may still be callable as a `const fn` due to features + /// being enabled! + pub fn is_stable_const_fn(self, def_id: DefId) -> bool { + self.is_const_fn(def_id) + && match self.lookup_const_stability(def_id) { + None => true, // a fn in a non-staged_api crate + Some(stability) if stability.is_const_stable() => true, + _ => false, } - } else { - false - } } // FIXME(effects): Please remove this. It's a footgun. /// Whether the trait impl is marked const. This does not consider stability or feature gates. - pub fn is_const_trait_impl_raw(self, def_id: DefId) -> bool { - let Some(local_def_id) = def_id.as_local() else { return false }; - let node = self.hir_node_by_def_id(local_def_id); - - matches!( - node, - hir::Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { constness, .. }), - .. - }) if matches!(constness, hir::Constness::Const) - ) + pub fn is_const_trait_impl(self, def_id: DefId) -> bool { + self.def_kind(def_id) == DefKind::Impl { of_trait: true } + && self.constness(def_id) == hir::Constness::Const } pub fn intrinsic(self, def_id: impl IntoQueryParam + Copy) -> Option { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 854147648178..b92fc864b49a 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1995,8 +1995,11 @@ impl<'tcx> TyCtxt<'tcx> { (ident, scope) } + /// Checks whether this is a `const fn`. Returns `false` for non-functions. + /// + /// Even if this returns `true`, constness may still be unstable! #[inline] - pub fn is_const_fn_raw(self, def_id: DefId) -> bool { + pub fn is_const_fn(self, def_id: DefId) -> bool { matches!( self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 86c4b241a2b4..fa9a6bfcf7cc 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -673,7 +673,7 @@ impl<'tcx> Validator<'_, 'tcx> { } // Make sure the callee is a `const fn`. let is_const_fn = match *fn_ty.kind() { - ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id), + ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id), _ => false, }; if !is_const_fn { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 62c502f95242..ed0d7ed8acc6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1997,7 +1997,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { ) { match target { Target::Fn | Target::Method(_) - if self.tcx.is_const_fn_raw(hir_id.expect_owner().to_def_id()) => {} + if self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) => {} // FIXME(#80564): We permit struct fields and match arms to have an // `#[allow_internal_unstable]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index e24e6a486f4a..67e7496771dc 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -179,7 +179,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { // their ABI; `fn_sig.abi` is *not* correct for foreign functions. && !is_foreign_item && const_stab.is_some() - && (!self.in_trait_impl || !self.tcx.is_const_fn_raw(def_id.to_def_id())) + && (!self.in_trait_impl || !self.tcx.is_const_fn(def_id.to_def_id())) { self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span }); } @@ -597,8 +597,8 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { return; } - let is_const = self.tcx.is_const_fn_raw(def_id.to_def_id()) - || self.tcx.is_const_trait_impl_raw(def_id.to_def_id()); + let is_const = self.tcx.is_const_fn(def_id.to_def_id()) + || self.tcx.is_const_trait_impl(def_id.to_def_id()); let is_stable = self.tcx.lookup_stability(def_id).is_some_and(|stability| stability.level.is_stable()); let missing_const_stability_attribute = @@ -820,7 +820,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable // needs to have an error emitted. if features.const_trait_impl() - && self.tcx.is_const_trait_impl_raw(item.owner_id.to_def_id()) + && self.tcx.is_const_trait_impl(item.owner_id.to_def_id()) && const_stab.is_some_and(|(stab, _)| stab.is_const_stable()) { self.tcx.dcx().emit_err(errors::TraitImplConstStable { span: item.span }); 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 47601b0c18d5..e027586563ec 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -393,7 +393,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let self_ty = obligation.self_ty().skip_binder(); match *self_ty.kind() { ty::Closure(def_id, _) => { - let is_const = self.tcx().is_const_fn_raw(def_id); + let is_const = self.tcx().is_const_fn(def_id); debug!(?kind, ?obligation, "assemble_unboxed_candidates"); match self.infcx.closure_kind(self_ty) { Some(closure_kind) => { @@ -413,7 +413,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } ty::CoroutineClosure(def_id, args) => { let args = args.as_coroutine_closure(); - let is_const = self.tcx().is_const_fn_raw(def_id); + let is_const = self.tcx().is_const_fn(def_id); if let Some(closure_kind) = self.infcx.closure_kind(self_ty) // Ambiguity if upvars haven't been constrained yet && !args.tupled_upvars_ty().is_ty_var() diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 1c060fa01505..c62144be3da2 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -640,7 +640,7 @@ impl Item { asyncness: ty::Asyncness, ) -> hir::FnHeader { let sig = tcx.fn_sig(def_id).skip_binder(); - let constness = if tcx.is_const_fn_raw(def_id) { + let constness = if tcx.is_const_fn(def_id) { hir::Constness::Const } else { hir::Constness::NotConst @@ -662,7 +662,7 @@ impl Item { safety }, abi, - constness: if tcx.is_const_fn_raw(def_id) { + constness: if tcx.is_const_fn(def_id) { hir::Constness::Const } else { hir::Constness::NotConst diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 5f12b6bf99ec..46739862de6b 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -334,7 +334,7 @@ fn check_terminator<'tcx>( | TerminatorKind::TailCall { func, args, fn_span: _ } => { let fn_ty = func.ty(body, tcx); if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() { - if !is_const_fn(tcx, fn_def_id, msrv) { + if !is_stable_const_fn(tcx, fn_def_id, msrv) { return Err(( span, format!( @@ -377,12 +377,12 @@ fn check_terminator<'tcx>( } } -fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: &Msrv) -> bool { +fn is_stable_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: &Msrv) -> bool { tcx.is_const_fn(def_id) - && tcx.lookup_const_stability(def_id).map_or(true, |const_stab| { + && tcx.lookup_const_stability(def_id).is_none_or(|const_stab| { if let rustc_attr::StabilityLevel::Stable { since, .. } = const_stab.level { // Checking MSRV is manually necessary because `rustc` has no such concept. This entire - // function could be removed if `rustc` provided a MSRV-aware version of `is_const_fn`. + // function could be removed if `rustc` provided a MSRV-aware version of `is_stable_const_fn`. // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262. let const_stab_rust_version = match since { @@ -393,8 +393,12 @@ fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: &Msrv) -> bool { msrv.meets(const_stab_rust_version) } else { - // Unstable const fn with the feature enabled. - msrv.current().is_none() + // Unstable const fn, check if the feature is enabled. We need both the regular stability + // feature and (if set) the const stability feature to const-call this function. + let stab = tcx.lookup_stability(def_id); + let is_enabled = stab.is_some_and(|s| s.is_stable() || tcx.features().enabled(s.feature)) + && const_stab.feature.is_none_or(|f| tcx.features().enabled(f)); + is_enabled && msrv.current().is_none() } }) } diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index 02931306f162..8db6502dbfb2 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -346,13 +346,13 @@ pub fn is_const_evaluatable<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> .cx .qpath_res(p, hir_id) .opt_def_id() - .map_or(false, |id| self.cx.tcx.is_const_fn_raw(id)) => {}, + .map_or(false, |id| self.cx.tcx.is_const_fn(id)) => {}, ExprKind::MethodCall(..) if self .cx .typeck_results() .type_dependent_def_id(e.hir_id) - .map_or(false, |id| self.cx.tcx.is_const_fn_raw(id)) => {}, + .map_or(false, |id| self.cx.tcx.is_const_fn(id)) => {}, ExprKind::Binary(_, lhs, rhs) if self.cx.typeck_results().expr_ty(lhs).peel_refs().is_primitive_ty() && self.cx.typeck_results().expr_ty(rhs).peel_refs().is_primitive_ty() => {}, From 9ebba2fcc4bf9030ecd2e0d08e0e2c617ff3e773 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Fri, 25 Oct 2024 15:29:02 -0400 Subject: [PATCH 257/366] Update cargo --- src/tools/cargo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/cargo b/src/tools/cargo index cf53cc54bb59..e75214ea4936 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit cf53cc54bb593b5ec3dc2be4b1702f50c36d24d5 +Subproject commit e75214ea4936d2f2c909a71a1237042cc0e14b07 From ad76564900f353d3aca8ddcce48755f9903a6896 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 25 Oct 2024 20:14:11 +0000 Subject: [PATCH 258/366] Ensure that resume arg outlives region bound for coroutines --- compiler/rustc_type_ir/src/outlives.rs | 12 +++++++ tests/ui/coroutine/resume-arg-outlives-2.rs | 34 +++++++++++++++++++ .../ui/coroutine/resume-arg-outlives-2.stderr | 17 ++++++++++ tests/ui/coroutine/resume-arg-outlives.rs | 27 +++++++++++++++ tests/ui/coroutine/resume-arg-outlives.stderr | 20 +++++++++++ 5 files changed, 110 insertions(+) create mode 100644 tests/ui/coroutine/resume-arg-outlives-2.rs create mode 100644 tests/ui/coroutine/resume-arg-outlives-2.stderr create mode 100644 tests/ui/coroutine/resume-arg-outlives.rs create mode 100644 tests/ui/coroutine/resume-arg-outlives.stderr diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index ac35215fbaa0..0e94e989b978 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -110,6 +110,18 @@ impl TypeVisitor for OutlivesCollector<'_, I> { ty::Coroutine(_, args) => { args.as_coroutine().tupled_upvars_ty().visit_with(self); + // Coroutines may not outlive a region unless the resume + // ty outlives a region. This is because the resume ty may + // store data that lives shorter than this outlives region + // across yield points, which may subsequently be accessed + // after the coroutine is resumed again. + // + // Conceptually, you may think of the resume arg as an upvar + // of `&mut Option`, since it is kinda like + // storage shared between the callee of the coroutine and the + // coroutine body. + args.as_coroutine().resume_ty().visit_with(self); + // We ignore regions in the coroutine interior as we don't // want these to affect region inference } diff --git a/tests/ui/coroutine/resume-arg-outlives-2.rs b/tests/ui/coroutine/resume-arg-outlives-2.rs new file mode 100644 index 000000000000..387b143ea279 --- /dev/null +++ b/tests/ui/coroutine/resume-arg-outlives-2.rs @@ -0,0 +1,34 @@ +// Regression test for 132104 + +#![feature(coroutine_trait, coroutines)] + +use std::ops::Coroutine; +use std::{thread, time}; + +fn demo<'not_static>(s: &'not_static str) -> thread::JoinHandle<()> { + let mut generator = Box::pin({ + #[coroutine] + move |_ctx| { + let ctx: &'not_static str = yield; + yield; + dbg!(ctx); + } + }); + + // exploit: + generator.as_mut().resume(""); + generator.as_mut().resume(s); // <- generator hoards it as `let ctx`. + //~^ ERROR borrowed data escapes outside of function + thread::spawn(move || { + thread::sleep(time::Duration::from_millis(200)); + generator.as_mut().resume(""); // <- resumes from the last `yield`, running `dbg!(ctx)`. + }) +} + +fn main() { + let local = String::from("..."); + let thread = demo(&local); + drop(local); + let _unrelated = String::from("UAF"); + thread.join().unwrap(); +} diff --git a/tests/ui/coroutine/resume-arg-outlives-2.stderr b/tests/ui/coroutine/resume-arg-outlives-2.stderr new file mode 100644 index 000000000000..3d630d7e7e48 --- /dev/null +++ b/tests/ui/coroutine/resume-arg-outlives-2.stderr @@ -0,0 +1,17 @@ +error[E0521]: borrowed data escapes outside of function + --> $DIR/resume-arg-outlives-2.rs:20:5 + | +LL | fn demo<'not_static>(s: &'not_static str) -> thread::JoinHandle<()> { + | ----------- - `s` is a reference that is only valid in the function body + | | + | lifetime `'not_static` defined here +... +LL | generator.as_mut().resume(s); // <- generator hoards it as `let ctx`. + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `s` escapes the function body here + | argument requires that `'not_static` must outlive `'static` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0521`. diff --git a/tests/ui/coroutine/resume-arg-outlives.rs b/tests/ui/coroutine/resume-arg-outlives.rs new file mode 100644 index 000000000000..258be28e0631 --- /dev/null +++ b/tests/ui/coroutine/resume-arg-outlives.rs @@ -0,0 +1,27 @@ +// Regression test for 132104 + +#![feature(coroutine_trait, coroutines)] + +use std::ops::Coroutine; +use std::pin::Pin; + +fn demo<'not_static>(s: &'not_static str) -> Pin + 'static>> { + let mut generator = Box::pin({ + #[coroutine] + move |ctx: &'not_static str| { + yield; + dbg!(ctx); + } + }); + generator.as_mut().resume(s); + generator + //~^ ERROR lifetime may not live long enough +} + +fn main() { + let local = String::from("..."); + let mut coro = demo(&local); + drop(local); + let _unrelated = String::from("UAF"); + coro.as_mut().resume(""); +} diff --git a/tests/ui/coroutine/resume-arg-outlives.stderr b/tests/ui/coroutine/resume-arg-outlives.stderr new file mode 100644 index 000000000000..2a6337b49451 --- /dev/null +++ b/tests/ui/coroutine/resume-arg-outlives.stderr @@ -0,0 +1,20 @@ +error: lifetime may not live long enough + --> $DIR/resume-arg-outlives.rs:17:5 + | +LL | fn demo<'not_static>(s: &'not_static str) -> Pin + 'static>> { + | ----------- lifetime `'not_static` defined here +... +LL | generator + | ^^^^^^^^^ returning this value requires that `'not_static` must outlive `'static` + | +help: consider changing `impl Coroutine<&'not_static str> + 'static`'s explicit `'static` bound to the lifetime of argument `s` + | +LL | fn demo<'not_static>(s: &'not_static str) -> Pin + 'not_static>> { + | ~~~~~~~~~~~ +help: alternatively, add an explicit `'static` bound to this reference + | +LL | fn demo<'not_static>(s: &'static str) -> Pin + 'static>> { + | ~~~~~~~~~~~~ + +error: aborting due to 1 previous error + From bd8477b56248f07d9778e33045dc2b345ea9ab0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Rakic?= Date: Fri, 25 Oct 2024 20:42:09 +0000 Subject: [PATCH 259/366] Revert "Emit error when calling/declaring functions with unavailable vectors." This reverts commit 5af56cac38fa48e4228e5e123d060e85eb1acbf7. --- compiler/rustc_lint_defs/src/builtin.rs | 67 ----------- compiler/rustc_monomorphize/messages.ftl | 9 -- compiler/rustc_monomorphize/src/collector.rs | 5 - .../src/collector/abi_check.rs | 111 ------------------ compiler/rustc_monomorphize/src/errors.rs | 18 --- compiler/rustc_target/src/target_features.rs | 17 --- tests/crashes/131342-2.rs | 40 +++++++ tests/crashes/131342.rs | 1 + tests/ui/layout/post-mono-layout-cycle-2.rs | 1 + .../ui/layout/post-mono-layout-cycle-2.stderr | 10 +- tests/ui/layout/post-mono-layout-cycle.rs | 1 + tests/ui/layout/post-mono-layout-cycle.stderr | 10 +- tests/ui/simd-abi-checks.rs | 81 ------------- tests/ui/simd-abi-checks.stderr | 93 --------------- tests/ui/sse-abi-checks.rs | 24 ---- tests/ui/sse-abi-checks.stderr | 13 -- 16 files changed, 53 insertions(+), 448 deletions(-) delete mode 100644 compiler/rustc_monomorphize/src/collector/abi_check.rs create mode 100644 tests/crashes/131342-2.rs delete mode 100644 tests/ui/simd-abi-checks.rs delete mode 100644 tests/ui/simd-abi-checks.stderr delete mode 100644 tests/ui/sse-abi-checks.rs delete mode 100644 tests/ui/sse-abi-checks.stderr diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index f196d58c22d9..a4c49a159053 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -16,7 +16,6 @@ declare_lint_pass! { /// that are used by other parts of the compiler. HardwiredLints => [ // tidy-alphabetical-start - ABI_UNSUPPORTED_VECTOR_TYPES, ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_ASSOCIATED_ITEMS, AMBIGUOUS_GLOB_IMPORTS, @@ -5029,69 +5028,3 @@ declare_lint! { }; crate_level_only } - -declare_lint! { - /// The `abi_unsupported_vector_types` lint detects function definitions and calls - /// whose ABI depends on enabling certain target features, but those features are not enabled. - /// - /// ### Example - /// - /// ```rust,ignore (fails on non-x86_64) - /// extern "C" fn missing_target_feature(_: std::arch::x86_64::__m256) { - /// todo!() - /// } - /// - /// #[target_feature(enable = "avx")] - /// unsafe extern "C" fn with_target_feature(_: std::arch::x86_64::__m256) { - /// todo!() - /// } - /// - /// fn main() { - /// let v = unsafe { std::mem::zeroed() }; - /// unsafe { with_target_feature(v); } - /// } - /// ``` - /// - /// ```text - /// warning: ABI error: this function call uses a avx vector type, which is not enabled in the caller - /// --> lint_example.rs:18:12 - /// | - /// | unsafe { with_target_feature(v); } - /// | ^^^^^^^^^^^^^^^^^^^^^^ function called here - /// | - /// = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - /// = note: for more information, see issue #116558 - /// = help: consider enabling it globally (-C target-feature=+avx) or locally (#[target_feature(enable="avx")]) - /// = note: `#[warn(abi_unsupported_vector_types)]` on by default - /// - /// - /// warning: ABI error: this function definition uses a avx vector type, which is not enabled - /// --> lint_example.rs:3:1 - /// | - /// | pub extern "C" fn with_target_feature(_: std::arch::x86_64::__m256) { - /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here - /// | - /// = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - /// = note: for more information, see issue #116558 - /// = help: consider enabling it globally (-C target-feature=+avx) or locally (#[target_feature(enable="avx")]) - /// ``` - /// - /// - /// - /// ### Explanation - /// - /// The C ABI for `__m256` requires the value to be passed in an AVX register, - /// which is only possible when the `avx` target feature is enabled. - /// Therefore, `missing_target_feature` cannot be compiled without that target feature. - /// A similar (but complementary) message is triggered when `with_target_feature` is called - /// by a function that does not enable the `avx` target feature. - /// - /// Note that this lint is very similar to the `-Wpsabi` warning in `gcc`/`clang`. - pub ABI_UNSUPPORTED_VECTOR_TYPES, - Warn, - "this function call or definition uses a vector type which is not enabled", - @future_incompatible = FutureIncompatibleInfo { - reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps, - reference: "issue #116558 ", - }; -} diff --git a/compiler/rustc_monomorphize/messages.ftl b/compiler/rustc_monomorphize/messages.ftl index 6da387bbebcc..7210701d4828 100644 --- a/compiler/rustc_monomorphize/messages.ftl +++ b/compiler/rustc_monomorphize/messages.ftl @@ -1,12 +1,3 @@ -monomorphize_abi_error_disabled_vector_type_call = - ABI error: this function call uses a vector type that requires the `{$required_feature}` target feature, which is not enabled in the caller - .label = function called here - .help = consider enabling it globally (`-C target-feature=+{$required_feature}`) or locally (`#[target_feature(enable="{$required_feature}")]`) -monomorphize_abi_error_disabled_vector_type_def = - ABI error: this function definition uses a vector type that requires the `{$required_feature}` target feature, which is not enabled - .label = function defined here - .help = consider enabling it globally (`-C target-feature=+{$required_feature}`) or locally (`#[target_feature(enable="{$required_feature}")]`) - monomorphize_couldnt_dump_mono_stats = unexpected error occurred while dumping monomorphization stats: {$error} diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 3f9a0df03015..e5c59d608221 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -205,7 +205,6 @@ //! this is not implemented however: a mono item will be produced //! regardless of whether it is actually needed or not. -mod abi_check; mod move_check; use std::path::PathBuf; @@ -767,7 +766,6 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty)); let callee_ty = self.monomorphize(callee_ty); self.check_fn_args_move_size(callee_ty, args, *fn_span, location); - abi_check::check_call_site_abi(tcx, callee_ty, *fn_span, self.body.source.instance); visit_fn_use(self.tcx, callee_ty, true, source, &mut self.used_items) } mir::TerminatorKind::Drop { ref place, .. } => { @@ -1209,9 +1207,6 @@ fn collect_items_of_instance<'tcx>( mentioned_items: &mut MonoItems<'tcx>, mode: CollectionMode, ) { - // Check the instance for feature-dependent ABI. - abi_check::check_instance_abi(tcx, instance); - let body = tcx.instance_mir(instance.def); // Naively, in "used" collection mode, all functions get added to *both* `used_items` and // `mentioned_items`. Mentioned items processing will then notice that they have already been diff --git a/compiler/rustc_monomorphize/src/collector/abi_check.rs b/compiler/rustc_monomorphize/src/collector/abi_check.rs deleted file mode 100644 index 6b825019f202..000000000000 --- a/compiler/rustc_monomorphize/src/collector/abi_check.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! This module ensures that if a function's ABI requires a particular target feature, -//! that target feature is enabled both on the callee and all callers. -use rustc_hir::CRATE_HIR_ID; -use rustc_middle::ty::{self, Instance, InstanceKind, ParamEnv, Ty, TyCtxt}; -use rustc_session::lint::builtin::ABI_UNSUPPORTED_VECTOR_TYPES; -use rustc_span::def_id::DefId; -use rustc_span::{Span, Symbol}; -use rustc_target::abi::call::{FnAbi, PassMode}; -use rustc_target::abi::{Abi, RegKind}; - -use crate::errors::{AbiErrorDisabledVectorTypeCall, AbiErrorDisabledVectorTypeDef}; - -fn uses_vector_registers(mode: &PassMode, abi: &Abi) -> bool { - match mode { - PassMode::Ignore | PassMode::Indirect { .. } => false, - PassMode::Cast { pad_i32: _, cast } => { - cast.prefix.iter().any(|r| r.is_some_and(|x| x.kind == RegKind::Vector)) - || cast.rest.unit.kind == RegKind::Vector - } - PassMode::Direct(..) | PassMode::Pair(..) => matches!(abi, Abi::Vector { .. }), - } -} - -fn do_check_abi<'tcx>( - tcx: TyCtxt<'tcx>, - abi: &FnAbi<'tcx, Ty<'tcx>>, - target_feature_def: DefId, - emit_err: impl Fn(&'static str), -) { - let Some(feature_def) = tcx.sess.target.features_for_correct_vector_abi() else { - return; - }; - let codegen_attrs = tcx.codegen_fn_attrs(target_feature_def); - for arg_abi in abi.args.iter().chain(std::iter::once(&abi.ret)) { - let size = arg_abi.layout.size; - if uses_vector_registers(&arg_abi.mode, &arg_abi.layout.abi) { - // Find the first feature that provides at least this vector size. - let feature = match feature_def.iter().find(|(bits, _)| size.bits() <= *bits) { - Some((_, feature)) => feature, - None => { - emit_err(""); - continue; - } - }; - let feature_sym = Symbol::intern(feature); - if !tcx.sess.unstable_target_features.contains(&feature_sym) - && !codegen_attrs.target_features.iter().any(|x| x.name == feature_sym) - { - emit_err(feature); - } - } - } -} - -/// Checks that the ABI of a given instance of a function does not contain vector-passed arguments -/// or return values for which the corresponding target feature is not enabled. -pub(super) fn check_instance_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) { - let param_env = ParamEnv::reveal_all(); - let Ok(abi) = tcx.fn_abi_of_instance(param_env.and((instance, ty::List::empty()))) else { - // An error will be reported during codegen if we cannot determine the ABI of this - // function. - return; - }; - do_check_abi(tcx, abi, instance.def_id(), |required_feature| { - let span = tcx.def_span(instance.def_id()); - tcx.emit_node_span_lint( - ABI_UNSUPPORTED_VECTOR_TYPES, - CRATE_HIR_ID, - span, - AbiErrorDisabledVectorTypeDef { span, required_feature }, - ); - }) -} - -/// Checks that a call expression does not try to pass a vector-passed argument which requires a -/// target feature that the caller does not have, as doing so causes UB because of ABI mismatch. -pub(super) fn check_call_site_abi<'tcx>( - tcx: TyCtxt<'tcx>, - ty: Ty<'tcx>, - span: Span, - caller: InstanceKind<'tcx>, -) { - let param_env = ParamEnv::reveal_all(); - let callee_abi = match *ty.kind() { - ty::FnPtr(..) => tcx.fn_abi_of_fn_ptr(param_env.and((ty.fn_sig(tcx), ty::List::empty()))), - ty::FnDef(def_id, args) => { - // Intrinsics are handled separately by the compiler. - if tcx.intrinsic(def_id).is_some() { - return; - } - let instance = ty::Instance::expect_resolve(tcx, param_env, def_id, args, span); - tcx.fn_abi_of_instance(param_env.and((instance, ty::List::empty()))) - } - _ => { - panic!("Invalid function call"); - } - }; - - let Ok(callee_abi) = callee_abi else { - // ABI failed to compute; this will not get through codegen. - return; - }; - do_check_abi(tcx, callee_abi, caller.def_id(), |required_feature| { - tcx.emit_node_span_lint( - ABI_UNSUPPORTED_VECTOR_TYPES, - CRATE_HIR_ID, - span, - AbiErrorDisabledVectorTypeCall { span, required_feature }, - ); - }) -} diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index 5048a8d5d993..d5fae6e23cb4 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -92,21 +92,3 @@ pub(crate) struct StartNotFound; pub(crate) struct UnknownCguCollectionMode<'a> { pub mode: &'a str, } - -#[derive(LintDiagnostic)] -#[diag(monomorphize_abi_error_disabled_vector_type_def)] -#[help] -pub(crate) struct AbiErrorDisabledVectorTypeDef<'a> { - #[label] - pub span: Span, - pub required_feature: &'a str, -} - -#[derive(LintDiagnostic)] -#[diag(monomorphize_abi_error_disabled_vector_type_call)] -#[help] -pub(crate) struct AbiErrorDisabledVectorTypeCall<'a> { - #[label] - pub span: Span, - pub required_feature: &'a str, -} diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 0d16c9a96aa6..e92366d5c5c3 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -522,13 +522,6 @@ pub fn all_known_features() -> impl Iterator { .map(|(f, s, _)| (f, s)) } -// These arrays represent the least-constraining feature that is required for vector types up to a -// certain size to have their "proper" ABI on each architecture. -// Note that they must be kept sorted by vector size. -const X86_FEATURES_FOR_CORRECT_VECTOR_ABI: &'static [(u64, &'static str)] = - &[(128, "sse"), (256, "avx"), (512, "avx512f")]; -const AARCH64_FEATURES_FOR_CORRECT_VECTOR_ABI: &'static [(u64, &'static str)] = &[(128, "neon")]; - impl super::spec::Target { pub fn supported_target_features( &self, @@ -550,16 +543,6 @@ impl super::spec::Target { } } - // Returns None if we do not support ABI checks on the given target yet. - pub fn features_for_correct_vector_abi(&self) -> Option<&'static [(u64, &'static str)]> { - match &*self.arch { - "x86" | "x86_64" => Some(X86_FEATURES_FOR_CORRECT_VECTOR_ABI), - "aarch64" => Some(AARCH64_FEATURES_FOR_CORRECT_VECTOR_ABI), - // FIXME: add support for non-tier1 architectures - _ => None, - } - } - pub fn tied_target_features(&self) -> &'static [&'static [&'static str]] { match &*self.arch { "aarch64" | "arm64ec" => AARCH64_TIED_FEATURES, diff --git a/tests/crashes/131342-2.rs b/tests/crashes/131342-2.rs new file mode 100644 index 000000000000..79b6a837a49f --- /dev/null +++ b/tests/crashes/131342-2.rs @@ -0,0 +1,40 @@ +//@ known-bug: #131342 +// see also: 131342.rs + +fn main() { + problem_thingy(Once); +} + +struct Once; + +impl Iterator for Once { + type Item = (); +} + +fn problem_thingy(items: impl Iterator) { + let peeker = items.peekable(); + problem_thingy(&peeker); +} + +trait Iterator { + type Item; + + fn peekable(self) -> Peekable + where + Self: Sized, + { + loop {} + } +} + +struct Peekable { + _peeked: I::Item, +} + +impl Iterator for Peekable { + type Item = I::Item; +} + +impl Iterator for &I { + type Item = I::Item; +} diff --git a/tests/crashes/131342.rs b/tests/crashes/131342.rs index 266aa0da97d1..7f7ee9c9ac11 100644 --- a/tests/crashes/131342.rs +++ b/tests/crashes/131342.rs @@ -1,4 +1,5 @@ //@ known-bug: #131342 +// see also: 131342-2.rs fn main() { let mut items = vec![1, 2, 3, 4, 5].into_iter(); diff --git a/tests/ui/layout/post-mono-layout-cycle-2.rs b/tests/ui/layout/post-mono-layout-cycle-2.rs index e9a5292fbbdf..356f1e777c7d 100644 --- a/tests/ui/layout/post-mono-layout-cycle-2.rs +++ b/tests/ui/layout/post-mono-layout-cycle-2.rs @@ -45,6 +45,7 @@ where T: Blah, { async fn ice(&mut self) { + //~^ ERROR a cycle occurred during layout computation let arr: [(); 0] = []; self.t.iter(arr.into_iter()).await; } diff --git a/tests/ui/layout/post-mono-layout-cycle-2.stderr b/tests/ui/layout/post-mono-layout-cycle-2.stderr index ea69b39706f4..ad01c2694faf 100644 --- a/tests/ui/layout/post-mono-layout-cycle-2.stderr +++ b/tests/ui/layout/post-mono-layout-cycle-2.stderr @@ -12,12 +12,12 @@ LL | Blah::iter(self, iterator).await | = note: a recursive `async fn` call must introduce indirection such as `Box::pin` to avoid an infinitely sized future -note: the above error was encountered while instantiating `fn main::{closure#0}` - --> $DIR/post-mono-layout-cycle-2.rs:16:15 +error: a cycle occurred during layout computation + --> $DIR/post-mono-layout-cycle-2.rs:47:5 | -LL | match fut.as_mut().poll(ctx) { - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | async fn ice(&mut self) { + | ^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 1 previous error +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0733`. diff --git a/tests/ui/layout/post-mono-layout-cycle.rs b/tests/ui/layout/post-mono-layout-cycle.rs index 6753c01267ec..8d136190c005 100644 --- a/tests/ui/layout/post-mono-layout-cycle.rs +++ b/tests/ui/layout/post-mono-layout-cycle.rs @@ -14,6 +14,7 @@ struct Wrapper { } fn abi(_: Option>) {} +//~^ ERROR a cycle occurred during layout computation fn indirect() { abi::(None); diff --git a/tests/ui/layout/post-mono-layout-cycle.stderr b/tests/ui/layout/post-mono-layout-cycle.stderr index e2f6ac595d00..47f7f30b1cb4 100644 --- a/tests/ui/layout/post-mono-layout-cycle.stderr +++ b/tests/ui/layout/post-mono-layout-cycle.stderr @@ -5,12 +5,12 @@ error[E0391]: cycle detected when computing layout of `Wrapper<()>` = note: cycle used when computing layout of `core::option::Option>` = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information -note: the above error was encountered while instantiating `fn indirect::<()>` - --> $DIR/post-mono-layout-cycle.rs:23:5 +error: a cycle occurred during layout computation + --> $DIR/post-mono-layout-cycle.rs:16:1 | -LL | indirect::<()>(); - | ^^^^^^^^^^^^^^^^ +LL | fn abi(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 1 previous error +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0391`. diff --git a/tests/ui/simd-abi-checks.rs b/tests/ui/simd-abi-checks.rs deleted file mode 100644 index 094c89930b75..000000000000 --- a/tests/ui/simd-abi-checks.rs +++ /dev/null @@ -1,81 +0,0 @@ -//@ only-x86_64 -//@ build-pass -//@ ignore-pass (test emits codegen-time warnings) - -#![feature(avx512_target_feature)] -#![feature(portable_simd)] -#![allow(improper_ctypes_definitions)] - -use std::arch::x86_64::*; - -#[repr(transparent)] -struct Wrapper(__m256); - -unsafe extern "C" fn w(_: Wrapper) { - //~^ ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled - //~| WARNING this was previously accepted by the compiler - todo!() -} - -unsafe extern "C" fn f(_: __m256) { - //~^ ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled - //~| WARNING this was previously accepted by the compiler - todo!() -} - -unsafe extern "C" fn g() -> __m256 { - //~^ ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled - //~| WARNING this was previously accepted by the compiler - todo!() -} - -#[target_feature(enable = "avx")] -unsafe extern "C" fn favx() -> __m256 { - todo!() -} - -// avx2 implies avx, so no error here. -#[target_feature(enable = "avx2")] -unsafe extern "C" fn gavx(_: __m256) { - todo!() -} - -// No error because of "Rust" ABI. -fn as_f64x8(d: __m512d) -> std::simd::f64x8 { - unsafe { std::mem::transmute(d) } -} - -unsafe fn test() { - let arg = std::mem::transmute([0.0f64; 8]); - as_f64x8(arg); -} - -fn main() { - unsafe { - f(g()); - //~^ WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - //~| WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - //~| WARNING this was previously accepted by the compiler - //~| WARNING this was previously accepted by the compiler - } - - unsafe { - gavx(favx()); - //~^ WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - //~| WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - //~| WARNING this was previously accepted by the compiler - //~| WARNING this was previously accepted by the compiler - } - - unsafe { - test(); - } - - unsafe { - w(Wrapper(g())); - //~^ WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - //~| WARNING ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - //~| WARNING this was previously accepted by the compiler - //~| WARNING this was previously accepted by the compiler - } -} diff --git a/tests/ui/simd-abi-checks.stderr b/tests/ui/simd-abi-checks.stderr deleted file mode 100644 index aa7e94001698..000000000000 --- a/tests/ui/simd-abi-checks.stderr +++ /dev/null @@ -1,93 +0,0 @@ -warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - --> $DIR/simd-abi-checks.rs:55:11 - | -LL | f(g()); - | ^^^ function called here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - = note: `#[warn(abi_unsupported_vector_types)]` on by default - -warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - --> $DIR/simd-abi-checks.rs:55:9 - | -LL | f(g()); - | ^^^^^^ function called here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - --> $DIR/simd-abi-checks.rs:63:14 - | -LL | gavx(favx()); - | ^^^^^^ function called here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - --> $DIR/simd-abi-checks.rs:63:9 - | -LL | gavx(favx()); - | ^^^^^^^^^^^^ function called here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - --> $DIR/simd-abi-checks.rs:75:19 - | -LL | w(Wrapper(g())); - | ^^^ function called here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function call uses a vector type that requires the `avx` target feature, which is not enabled in the caller - --> $DIR/simd-abi-checks.rs:75:9 - | -LL | w(Wrapper(g())); - | ^^^^^^^^^^^^^^^ function called here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled - --> $DIR/simd-abi-checks.rs:26:1 - | -LL | unsafe extern "C" fn g() -> __m256 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled - --> $DIR/simd-abi-checks.rs:20:1 - | -LL | unsafe extern "C" fn f(_: __m256) { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: ABI error: this function definition uses a vector type that requires the `avx` target feature, which is not enabled - --> $DIR/simd-abi-checks.rs:14:1 - | -LL | unsafe extern "C" fn w(_: Wrapper) { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+avx`) or locally (`#[target_feature(enable="avx")]`) - -warning: 9 warnings emitted - diff --git a/tests/ui/sse-abi-checks.rs b/tests/ui/sse-abi-checks.rs deleted file mode 100644 index d2afd38fcc85..000000000000 --- a/tests/ui/sse-abi-checks.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Ensure we trigger abi_unsupported_vector_types for target features that are usually enabled -//! on a target, but disabled in this file via a `-C` flag. -//@ compile-flags: --crate-type=rlib --target=i686-unknown-linux-gnu -C target-feature=-sse,-sse2 -//@ build-pass -//@ ignore-pass (test emits codegen-time warnings) -//@ needs-llvm-components: x86 -#![feature(no_core, lang_items, repr_simd)] -#![no_core] -#![allow(improper_ctypes_definitions)] - -#[lang = "sized"] -trait Sized {} - -#[lang = "copy"] -trait Copy {} - -#[repr(simd)] -pub struct SseVector([i64; 2]); - -#[no_mangle] -pub unsafe extern "C" fn f(_: SseVector) { - //~^ ABI error: this function definition uses a vector type that requires the `sse` target feature, which is not enabled - //~| WARNING this was previously accepted by the compiler -} diff --git a/tests/ui/sse-abi-checks.stderr b/tests/ui/sse-abi-checks.stderr deleted file mode 100644 index 77c4e1fc07ab..000000000000 --- a/tests/ui/sse-abi-checks.stderr +++ /dev/null @@ -1,13 +0,0 @@ -warning: ABI error: this function definition uses a vector type that requires the `sse` target feature, which is not enabled - --> $DIR/sse-abi-checks.rs:21:1 - | -LL | pub unsafe extern "C" fn f(_: SseVector) { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #116558 - = help: consider enabling it globally (`-C target-feature=+sse`) or locally (`#[target_feature(enable="sse")]`) - = note: `#[warn(abi_unsupported_vector_types)]` on by default - -warning: 1 warning emitted - From e2d3f5aaec941850479e16e89ebfb70824e65a45 Mon Sep 17 00:00:00 2001 From: Manuel Drehwald Date: Sat, 12 Oct 2024 00:16:39 +0200 Subject: [PATCH 260/366] Allow building rustc's LLVM with Offload support --- config.example.toml | 3 +++ src/bootstrap/configure.py | 1 + src/bootstrap/src/core/build_steps/llvm.rs | 15 +++++++++++++++ src/bootstrap/src/core/config/config.rs | 9 +++++++++ src/bootstrap/src/utils/change_tracker.rs | 5 +++++ 5 files changed, 33 insertions(+) diff --git a/config.example.toml b/config.example.toml index a52968e9a414..d5b904ebf3d5 100644 --- a/config.example.toml +++ b/config.example.toml @@ -84,6 +84,9 @@ # Wheter to build Enzyme as AutoDiff backend. #enzyme = false +# Whether to build LLVM with support for it's gpu offload runtime. +#offload = false + # Indicates whether ccache is used when building LLVM. Set to `true` to use the first `ccache` in # PATH, or set an absolute path to use a specific version. #ccache = false diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index 15137fbb2b5c..2e173c9e6df4 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -72,6 +72,7 @@ v("llvm-libunwind", "rust.llvm-libunwind", "use LLVM libunwind") o("optimize-llvm", "llvm.optimize", "build optimized LLVM") o("llvm-assertions", "llvm.assertions", "build LLVM with assertions") o("llvm-enzyme", "llvm.enzyme", "build LLVM with enzyme") +o("llvm-offload", "llvm.offload", "build LLVM with gpu offload support") o("llvm-plugins", "llvm.plugins", "build LLVM with plugin interface") o("debug-assertions", "rust.debug-assertions", "build with debugging assertions") o("debug-assertions-std", "rust.debug-assertions-std", "build the standard library with debugging assertions") diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index a2d40f6fbd89..ffb7d9a9e0e7 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -472,6 +472,21 @@ impl Step for Llvm { cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";")); } + let mut enabled_llvm_runtimes = Vec::new(); + + if builder.config.llvm_offload { + enabled_llvm_runtimes.push("offload"); + //FIXME(ZuseZ4): LLVM intends to drop the offload dependency on openmp. + //Remove this line once they achieved it. + enabled_llvm_runtimes.push("openmp"); + } + + if !enabled_llvm_runtimes.is_empty() { + enabled_llvm_runtimes.sort(); + enabled_llvm_runtimes.dedup(); + cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";")); + } + if let Some(num_linkers) = builder.config.llvm_link_jobs { if num_linkers > 0 { cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string()); diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 444c97a2048e..087dde0d9c6b 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -224,6 +224,7 @@ pub struct Config { pub llvm_assertions: bool, pub llvm_tests: bool, pub llvm_enzyme: bool, + pub llvm_offload: bool, pub llvm_plugins: bool, pub llvm_optimize: bool, pub llvm_thin_lto: bool, @@ -938,6 +939,7 @@ define_config! { use_libcxx: Option = "use-libcxx", use_linker: Option = "use-linker", allow_old_toolchain: Option = "allow-old-toolchain", + offload: Option = "offload", polly: Option = "polly", clang: Option = "clang", enable_warnings: Option = "enable-warnings", @@ -1647,6 +1649,7 @@ impl Config { // we'll infer default values for them later let mut llvm_tests = None; let mut llvm_enzyme = None; + let mut llvm_offload = None; let mut llvm_plugins = None; let mut debug = None; let mut debug_assertions = None; @@ -1884,6 +1887,7 @@ impl Config { use_libcxx, use_linker, allow_old_toolchain, + offload, polly, clang, enable_warnings, @@ -1900,6 +1904,7 @@ impl Config { set(&mut config.ninja_in_file, ninja); llvm_tests = tests; llvm_enzyme = enzyme; + llvm_offload = offload; llvm_plugins = plugins; set(&mut config.llvm_optimize, optimize_toml); set(&mut config.llvm_thin_lto, thin_lto); @@ -1921,6 +1926,7 @@ impl Config { set(&mut config.llvm_use_libcxx, use_libcxx); config.llvm_use_linker.clone_from(&use_linker); config.llvm_allow_old_toolchain = allow_old_toolchain.unwrap_or(false); + config.llvm_offload = offload.unwrap_or(false); config.llvm_polly = polly.unwrap_or(false); config.llvm_clang = clang.unwrap_or(false); config.llvm_enable_warnings = enable_warnings.unwrap_or(false); @@ -2097,6 +2103,7 @@ impl Config { config.llvm_tests = llvm_tests.unwrap_or(false); config.llvm_enzyme = llvm_enzyme.unwrap_or(false); + config.llvm_offload = llvm_offload.unwrap_or(false); config.llvm_plugins = llvm_plugins.unwrap_or(false); config.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true)); @@ -2963,6 +2970,7 @@ pub(crate) fn check_incompatible_options_for_ci_llvm( use_libcxx, use_linker, allow_old_toolchain, + offload, polly, clang, enable_warnings, @@ -2985,6 +2993,7 @@ pub(crate) fn check_incompatible_options_for_ci_llvm( err!(current_llvm_config.use_libcxx, use_libcxx); err!(current_llvm_config.use_linker, use_linker); err!(current_llvm_config.allow_old_toolchain, allow_old_toolchain); + err!(current_llvm_config.offload, offload); err!(current_llvm_config.polly, polly); err!(current_llvm_config.clang, clang); err!(current_llvm_config.build_config, build_config); diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index fac24572a878..b9cf8f053169 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -285,4 +285,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "New option `build.compiletest-diff-tool` that adds support for a custom differ for compiletest", }, + ChangeInfo { + change_id: 131513, + severity: ChangeSeverity::Info, + summary: "New option `llvm.offload` to control whether the llvm offload runtime for GPU support is built. Implicitly enables the openmp runtime as dependency.", + }, ]; From 19b2142d18805f4b30a585f2c12a181d9b8c72d0 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 23 Oct 2024 21:02:18 +1100 Subject: [PATCH 261/366] coverage: Don't rely on the custom traversal to find enclosing loops --- .../src/coverage/counters.rs | 31 ++--- .../rustc_mir_transform/src/coverage/graph.rs | 117 +++++++++++------- 2 files changed, 85 insertions(+), 63 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs index 9a533ea024d7..cf9f6981c5a2 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters.rs @@ -280,13 +280,12 @@ impl<'a> CountersBuilder<'a> { // // The traversal tries to ensure that, when a loop is encountered, all // nodes within the loop are visited before visiting any nodes outside - // the loop. It also keeps track of which loop(s) the traversal is - // currently inside. + // the loop. let mut traversal = TraverseCoverageGraphWithLoops::new(self.graph); while let Some(bcb) = traversal.next() { let _span = debug_span!("traversal", ?bcb).entered(); if self.bcb_needs_counter.contains(bcb) { - self.make_node_counter_and_out_edge_counters(&traversal, bcb); + self.make_node_counter_and_out_edge_counters(bcb); } } @@ -299,12 +298,8 @@ impl<'a> CountersBuilder<'a> { /// Make sure the given node has a node counter, and then make sure each of /// its out-edges has an edge counter (if appropriate). - #[instrument(level = "debug", skip(self, traversal))] - fn make_node_counter_and_out_edge_counters( - &mut self, - traversal: &TraverseCoverageGraphWithLoops<'_>, - from_bcb: BasicCoverageBlock, - ) { + #[instrument(level = "debug", skip(self))] + fn make_node_counter_and_out_edge_counters(&mut self, from_bcb: BasicCoverageBlock) { // First, ensure that this node has a counter of some kind. // We might also use that counter to compute one of the out-edge counters. let node_counter = self.get_or_make_node_counter(from_bcb); @@ -337,8 +332,7 @@ impl<'a> CountersBuilder<'a> { // If there are out-edges without counters, choose one to be given an expression // (computed from this node and the other out-edges) instead of a physical counter. - let Some(target_bcb) = - self.choose_out_edge_for_expression(traversal, &candidate_successors) + let Some(target_bcb) = self.choose_out_edge_for_expression(from_bcb, &candidate_successors) else { return; }; @@ -462,12 +456,12 @@ impl<'a> CountersBuilder<'a> { /// choose one to be given a counter expression instead of a physical counter. fn choose_out_edge_for_expression( &self, - traversal: &TraverseCoverageGraphWithLoops<'_>, + from_bcb: BasicCoverageBlock, candidate_successors: &[BasicCoverageBlock], ) -> Option { // Try to find a candidate that leads back to the top of a loop, // because reloop edges tend to be executed more times than loop-exit edges. - if let Some(reloop_target) = self.find_good_reloop_edge(traversal, &candidate_successors) { + if let Some(reloop_target) = self.find_good_reloop_edge(from_bcb, &candidate_successors) { debug!("Selecting reloop target {reloop_target:?} to get an expression"); return Some(reloop_target); } @@ -486,7 +480,7 @@ impl<'a> CountersBuilder<'a> { /// for them to be able to avoid a physical counter increment. fn find_good_reloop_edge( &self, - traversal: &TraverseCoverageGraphWithLoops<'_>, + from_bcb: BasicCoverageBlock, candidate_successors: &[BasicCoverageBlock], ) -> Option { // If there are no candidates, avoid iterating over the loop stack. @@ -495,14 +489,15 @@ impl<'a> CountersBuilder<'a> { } // Consider each loop on the current traversal context stack, top-down. - for reloop_bcbs in traversal.reloop_bcbs_per_loop() { + for loop_header_node in self.graph.loop_headers_containing(from_bcb) { // Try to find a candidate edge that doesn't exit this loop. for &target_bcb in candidate_successors { // An edge is a reloop edge if its target dominates any BCB that has // an edge back to the loop header. (Otherwise it's an exit edge.) - let is_reloop_edge = reloop_bcbs - .iter() - .any(|&reloop_bcb| self.graph.dominates(target_bcb, reloop_bcb)); + let is_reloop_edge = self + .graph + .reloop_predecessors(loop_header_node) + .any(|reloop_bcb| self.graph.dominates(target_bcb, reloop_bcb)); if is_reloop_edge { // We found a good out-edge to be given an expression. return Some(target_bcb); diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 930fa129ef2a..168262bf01cd 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -1,10 +1,11 @@ use std::cmp::Ordering; use std::collections::VecDeque; +use std::iter; use std::ops::{Index, IndexMut}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::graph::dominators::{self, Dominators}; +use rustc_data_structures::graph::dominators::Dominators; use rustc_data_structures::graph::{self, DirectedGraph, StartNode}; use rustc_index::IndexVec; use rustc_index::bit_set::BitSet; @@ -20,11 +21,17 @@ pub(crate) struct CoverageGraph { bb_to_bcb: IndexVec>, pub(crate) successors: IndexVec>, pub(crate) predecessors: IndexVec>, + dominators: Option>, /// Allows nodes to be compared in some total order such that _if_ /// `a` dominates `b`, then `a < b`. If neither node dominates the other, /// their relative order is consistent but arbitrary. dominator_order_rank: IndexVec, + /// A loop header is a node that dominates one or more of its predecessors. + is_loop_header: BitSet, + /// For each node, the loop header node of its nearest enclosing loop. + /// This forms a linked list that can be traversed to find all enclosing loops. + enclosing_loop_header: IndexVec>, } impl CoverageGraph { @@ -66,17 +73,38 @@ impl CoverageGraph { predecessors, dominators: None, dominator_order_rank: IndexVec::from_elem_n(0, num_nodes), + is_loop_header: BitSet::new_empty(num_nodes), + enclosing_loop_header: IndexVec::from_elem_n(None, num_nodes), }; assert_eq!(num_nodes, this.num_nodes()); - this.dominators = Some(dominators::dominators(&this)); + // Set the dominators first, because later init steps rely on them. + this.dominators = Some(graph::dominators::dominators(&this)); - // The dominator rank of each node is just its index in a reverse-postorder traversal. - let reverse_post_order = graph::iterate::reverse_post_order(&this, this.start_node()); + // Iterate over all nodes, such that dominating nodes are visited before + // the nodes they dominate. Either preorder or reverse postorder is fine. + let dominator_order = graph::iterate::reverse_post_order(&this, this.start_node()); // The coverage graph is created by traversal, so all nodes are reachable. - assert_eq!(reverse_post_order.len(), this.num_nodes()); - for (rank, bcb) in (0u32..).zip(reverse_post_order) { + assert_eq!(dominator_order.len(), this.num_nodes()); + for (rank, bcb) in (0u32..).zip(dominator_order) { + // The dominator rank of each node is its index in a dominator-order traversal. this.dominator_order_rank[bcb] = rank; + + // A node is a loop header if it dominates any of its predecessors. + if this.reloop_predecessors(bcb).next().is_some() { + this.is_loop_header.insert(bcb); + } + + // If the immediate dominator is a loop header, that's our enclosing loop. + // Otherwise, inherit the immediate dominator's enclosing loop. + // (Dominator order ensures that we already processed the dominator.) + if let Some(dom) = this.dominators().immediate_dominator(bcb) { + this.enclosing_loop_header[bcb] = this + .is_loop_header + .contains(dom) + .then_some(dom) + .or_else(|| this.enclosing_loop_header[dom]); + } } // The coverage graph's entry-point node (bcb0) always starts with bb0, @@ -172,9 +200,14 @@ impl CoverageGraph { if bb.index() < self.bb_to_bcb.len() { self.bb_to_bcb[bb] } else { None } } + #[inline(always)] + fn dominators(&self) -> &Dominators { + self.dominators.as_ref().unwrap() + } + #[inline(always)] pub(crate) fn dominates(&self, dom: BasicCoverageBlock, node: BasicCoverageBlock) -> bool { - self.dominators.as_ref().unwrap().dominates(dom, node) + self.dominators().dominates(dom, node) } #[inline(always)] @@ -214,6 +247,36 @@ impl CoverageGraph { None } } + + /// For each loop that contains the given node, yields the "loop header" + /// node representing that loop, from innermost to outermost. If the given + /// node is itself a loop header, it is yielded first. + pub(crate) fn loop_headers_containing( + &self, + bcb: BasicCoverageBlock, + ) -> impl Iterator + Captures<'_> { + let self_if_loop_header = self.is_loop_header.contains(bcb).then_some(bcb).into_iter(); + + let mut curr = Some(bcb); + let strictly_enclosing = iter::from_fn(move || { + let enclosing = self.enclosing_loop_header[curr?]; + curr = enclosing; + enclosing + }); + + self_if_loop_header.chain(strictly_enclosing) + } + + /// For the given node, yields the subset of its predecessor nodes that + /// it dominates. If that subset is non-empty, the node is a "loop header", + /// and each of those predecessors represents an in-edge that jumps back to + /// the top of its loop. + pub(crate) fn reloop_predecessors( + &self, + to_bcb: BasicCoverageBlock, + ) -> impl Iterator + Captures<'_> { + self.predecessors[to_bcb].iter().copied().filter(move |&pred| self.dominates(to_bcb, pred)) + } } impl Index for CoverageGraph { @@ -439,15 +502,12 @@ struct TraversalContext { pub(crate) struct TraverseCoverageGraphWithLoops<'a> { basic_coverage_blocks: &'a CoverageGraph, - backedges: IndexVec>, context_stack: Vec, visited: BitSet, } impl<'a> TraverseCoverageGraphWithLoops<'a> { pub(crate) fn new(basic_coverage_blocks: &'a CoverageGraph) -> Self { - let backedges = find_loop_backedges(basic_coverage_blocks); - let worklist = VecDeque::from([basic_coverage_blocks.start_node()]); let context_stack = vec![TraversalContext { loop_header: None, worklist }]; @@ -456,17 +516,7 @@ impl<'a> TraverseCoverageGraphWithLoops<'a> { // of the stack as loops are entered, and popped off of the stack when a loop's worklist is // exhausted. let visited = BitSet::new_empty(basic_coverage_blocks.num_nodes()); - Self { basic_coverage_blocks, backedges, context_stack, visited } - } - - /// For each loop on the loop context stack (top-down), yields a list of BCBs - /// within that loop that have an outgoing edge back to the loop header. - pub(crate) fn reloop_bcbs_per_loop(&self) -> impl Iterator { - self.context_stack - .iter() - .rev() - .filter_map(|context| context.loop_header) - .map(|header_bcb| self.backedges[header_bcb].as_slice()) + Self { basic_coverage_blocks, context_stack, visited } } pub(crate) fn next(&mut self) -> Option { @@ -488,7 +538,7 @@ impl<'a> TraverseCoverageGraphWithLoops<'a> { } debug!("Visiting {bcb:?}"); - if self.backedges[bcb].len() > 0 { + if self.basic_coverage_blocks.is_loop_header.contains(bcb) { debug!("{bcb:?} is a loop header! Start a new TraversalContext..."); self.context_stack .push(TraversalContext { loop_header: Some(bcb), worklist: VecDeque::new() }); @@ -566,29 +616,6 @@ impl<'a> TraverseCoverageGraphWithLoops<'a> { } } -fn find_loop_backedges( - basic_coverage_blocks: &CoverageGraph, -) -> IndexVec> { - let num_bcbs = basic_coverage_blocks.num_nodes(); - let mut backedges = IndexVec::from_elem_n(Vec::::new(), num_bcbs); - - // Identify loops by their backedges. - for (bcb, _) in basic_coverage_blocks.iter_enumerated() { - for &successor in &basic_coverage_blocks.successors[bcb] { - if basic_coverage_blocks.dominates(successor, bcb) { - let loop_header = successor; - let backedge_from_bcb = bcb; - debug!( - "Found BCB backedge: {:?} -> loop_header: {:?}", - backedge_from_bcb, loop_header - ); - backedges[loop_header].push(backedge_from_bcb); - } - } - } - backedges -} - fn short_circuit_preorder<'a, 'tcx, F, Iter>( body: &'a mir::Body<'tcx>, filtered_successors: F, From d94a76a73f0ba7a819d98174895704261a13a0e0 Mon Sep 17 00:00:00 2001 From: Clayton Wilkinson Date: Fri, 25 Oct 2024 23:07:36 +0000 Subject: [PATCH 262/366] Update Fuchsia CI script for package serving This updates the "start" and "stop" methods of the test runner to use the standalone package server. --- src/ci/docker/scripts/fuchsia-test-runner.py | 52 +++++++++----------- 1 file changed, 22 insertions(+), 30 deletions(-) diff --git a/src/ci/docker/scripts/fuchsia-test-runner.py b/src/ci/docker/scripts/fuchsia-test-runner.py index 1aa9a4a1794f..5c319411774c 100755 --- a/src/ci/docker/scripts/fuchsia-test-runner.py +++ b/src/ci/docker/scripts/fuchsia-test-runner.py @@ -287,7 +287,7 @@ class TestEnvironment: @property def package_server_log_path(self) -> Path: - return self.tmp_dir().joinpath("package_server_log") + return self.tmp_dir().joinpath(f"repo_{self.TEST_REPO_NAME}.log") @property def emulator_log_path(self) -> Path: @@ -401,6 +401,7 @@ class TestEnvironment: # Set configs configs = { "log.enabled": "true", + "log.dir": self.tmp_dir(), "test.is_isolated": "true", "test.experimental_structured_output": "true", } @@ -575,43 +576,19 @@ class TestEnvironment: stderr_handler=self.subprocess_logger.debug, ) - # Add repository - check_call_with_logging( - [ - ffx_path, - "repository", - "add-from-pm", - "--repository", - self.TEST_REPO_NAME, - self.repo_dir(), - ], - env=ffx_env, - stdout_handler=self.subprocess_logger.debug, - stderr_handler=self.subprocess_logger.debug, - ) - - # Start repository server - # Note that we must first enable the repository server daemon. - check_call_with_logging( - [ - ffx_path, - "config", - "set", - "repository.server.enabled", - "true", - ], - env=ffx_env, - stdout_handler=self.subprocess_logger.debug, - stderr_handler=self.subprocess_logger.debug, - ) check_call_with_logging( [ ffx_path, "repository", "server", "start", + "--background", "--address", "[::]:0", + "--repo-path", + self.repo_dir(), + "--repository", + self.TEST_REPO_NAME ], env=ffx_env, stdout_handler=self.subprocess_logger.debug, @@ -1009,6 +986,21 @@ class TestEnvironment: stderr_handler=self.subprocess_logger.debug, ) + # Stop the package server + self.env_logger.info("Stopping package server...") + check_call_with_logging( + [ + self.tool_path("ffx"), + "repository", + "server", + "stop", + self.TEST_REPO_NAME + ], + env=self.ffx_cmd_env(), + stdout_handler=self.subprocess_logger.debug, + stderr_handler=self.subprocess_logger.debug, + ) + # Stop ffx isolation self.env_logger.info("Stopping ffx isolation...") self.stop_ffx_isolation() From ce4fc999a77cacc67adf27d81264d498c05a5314 Mon Sep 17 00:00:00 2001 From: Tyler Mandry Date: Fri, 25 Oct 2024 19:38:16 -0400 Subject: [PATCH 263/366] Fix indentation --- src/ci/docker/scripts/fuchsia-test-runner.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ci/docker/scripts/fuchsia-test-runner.py b/src/ci/docker/scripts/fuchsia-test-runner.py index 5c319411774c..77e2741f9ead 100755 --- a/src/ci/docker/scripts/fuchsia-test-runner.py +++ b/src/ci/docker/scripts/fuchsia-test-runner.py @@ -287,7 +287,7 @@ class TestEnvironment: @property def package_server_log_path(self) -> Path: - return self.tmp_dir().joinpath(f"repo_{self.TEST_REPO_NAME}.log") + return self.tmp_dir().joinpath(f"repo_{self.TEST_REPO_NAME}.log") @property def emulator_log_path(self) -> Path: @@ -401,7 +401,7 @@ class TestEnvironment: # Set configs configs = { "log.enabled": "true", - "log.dir": self.tmp_dir(), + "log.dir": self.tmp_dir(), "test.is_isolated": "true", "test.experimental_structured_output": "true", } From f6fea8334271e05f1e00e95cdcc4ca7b3558d130 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 26 Oct 2024 10:18:42 +0800 Subject: [PATCH 264/366] Effects cleanup - removed extra bits from predicates queries that are no longer needed in the new system - removed the need for `non_erasable_generics` to take in tcx and DefId, removed unused arguments in callers --- .../src/debuginfo/mod.rs | 1 - compiler/rustc_codegen_gcc/src/callee.rs | 3 +- compiler/rustc_codegen_llvm/src/callee.rs | 3 +- .../rustc_codegen_llvm/src/debuginfo/mod.rs | 1 - .../src/back/symbol_export.rs | 16 ++++------ .../src/debuginfo/type_names.rs | 29 +++++-------------- compiler/rustc_hir_analysis/src/bounds.rs | 12 +------- .../src/collect/item_bounds.rs | 4 +-- .../src/collect/predicates_of.rs | 20 ++++--------- compiler/rustc_hir_analysis/src/delegation.rs | 2 -- .../src/hir_ty_lowering/dyn_compatibility.rs | 2 +- compiler/rustc_middle/src/mir/mono.rs | 6 ++-- compiler/rustc_middle/src/ty/diagnostics.rs | 2 +- compiler/rustc_middle/src/ty/generic_args.rs | 3 -- compiler/rustc_middle/src/ty/generics.rs | 1 - compiler/rustc_middle/src/ty/instance.rs | 2 +- compiler/rustc_mir_transform/src/inline.rs | 7 +---- compiler/rustc_monomorphize/src/collector.rs | 2 +- .../rustc_monomorphize/src/partitioning.rs | 4 +-- compiler/rustc_smir/src/rustc_smir/context.rs | 6 ++-- compiler/rustc_symbol_mangling/src/lib.rs | 8 ++--- src/librustdoc/clean/mod.rs | 1 - src/tools/clippy/clippy_lints/src/derive.rs | 2 +- 23 files changed, 40 insertions(+), 97 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs index f0b78e5d7c67..79d76925df9f 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs @@ -210,7 +210,6 @@ impl DebugContext { type_names::push_generic_params( tcx, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args), - enclosing_fn_def_id, &mut name, ); diff --git a/compiler/rustc_codegen_gcc/src/callee.rs b/compiler/rustc_codegen_gcc/src/callee.rs index 9ad2e90122f5..65972a03e835 100644 --- a/compiler/rustc_codegen_gcc/src/callee.rs +++ b/compiler/rustc_codegen_gcc/src/callee.rs @@ -98,8 +98,7 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). - let is_generic = - instance.args.non_erasable_generics(tcx, instance.def_id()).next().is_some(); + let is_generic = instance.args.non_erasable_generics().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 206a70697920..a51ef8d7b85f 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -98,8 +98,7 @@ pub(crate) fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'t unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); - let is_generic = - instance.args.non_erasable_generics(tcx, instance.def_id()).next().is_some(); + let is_generic = instance.args.non_erasable_generics().next().is_some(); let is_hidden = if is_generic { // This is a monomorphization of a generic function. diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 1a8153a54e83..3de4ca77e7d4 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -350,7 +350,6 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { type_names::push_generic_params( tcx, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args), - enclosing_fn_def_id, &mut name, ); diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 77c35a1fe79e..d9669453f5ad 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -312,7 +312,7 @@ fn exported_symbols_provider_local( match *mono_item { MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => { - if args.non_erasable_generics(tcx, def).next().is_some() { + if args.non_erasable_generics().next().is_some() { let symbol = ExportedSymbol::Generic(def, args); symbols.push((symbol, SymbolExportInfo { level: SymbolExportLevel::Rust, @@ -321,12 +321,9 @@ fn exported_symbols_provider_local( })); } } - MonoItem::Fn(Instance { def: InstanceKind::DropGlue(def_id, Some(ty)), args }) => { + MonoItem::Fn(Instance { def: InstanceKind::DropGlue(_, Some(ty)), args }) => { // A little sanity-check - assert_eq!( - args.non_erasable_generics(tcx, def_id).next(), - Some(GenericArgKind::Type(ty)) - ); + assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty))); symbols.push((ExportedSymbol::DropGlue(ty), SymbolExportInfo { level: SymbolExportLevel::Rust, kind: SymbolExportKind::Text, @@ -334,14 +331,11 @@ fn exported_symbols_provider_local( })); } MonoItem::Fn(Instance { - def: InstanceKind::AsyncDropGlueCtorShim(def_id, Some(ty)), + def: InstanceKind::AsyncDropGlueCtorShim(_, Some(ty)), args, }) => { // A little sanity-check - assert_eq!( - args.non_erasable_generics(tcx, def_id).next(), - Some(GenericArgKind::Type(ty)) - ); + assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty))); symbols.push((ExportedSymbol::AsyncDropGlueCtorShim(ty), SymbolExportInfo { level: SymbolExportLevel::Rust, kind: SymbolExportKind::Text, diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 526d2b86d488..1e5b4f3433d6 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -110,14 +110,14 @@ fn push_debuginfo_type_name<'tcx>( ty_and_layout, &|output, visited| { push_item_name(tcx, def.did(), true, output); - push_generic_params_internal(tcx, args, def.did(), output, visited); + push_generic_params_internal(tcx, args, output, visited); }, output, visited, ); } else { push_item_name(tcx, def.did(), qualified, output); - push_generic_params_internal(tcx, args, def.did(), output, visited); + push_generic_params_internal(tcx, args, output, visited); } } ty::Tuple(component_types) => { @@ -251,13 +251,8 @@ fn push_debuginfo_type_name<'tcx>( let principal = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), principal); push_item_name(tcx, principal.def_id, qualified, output); - let principal_has_generic_params = push_generic_params_internal( - tcx, - principal.args, - principal.def_id, - output, - visited, - ); + let principal_has_generic_params = + push_generic_params_internal(tcx, principal.args, output, visited); let projection_bounds: SmallVec<[_; 4]> = trait_data .projection_bounds() @@ -538,13 +533,7 @@ pub fn compute_debuginfo_vtable_name<'tcx>( tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), trait_ref); push_item_name(tcx, trait_ref.def_id, true, &mut vtable_name); visited.clear(); - push_generic_params_internal( - tcx, - trait_ref.args, - trait_ref.def_id, - &mut vtable_name, - &mut visited, - ); + push_generic_params_internal(tcx, trait_ref.args, &mut vtable_name, &mut visited); } else { vtable_name.push('_'); } @@ -647,12 +636,11 @@ fn push_unqualified_item_name( fn push_generic_params_internal<'tcx>( tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>, - def_id: DefId, output: &mut String, visited: &mut FxHashSet>, ) -> bool { assert_eq!(args, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args)); - let mut args = args.non_erasable_generics(tcx, def_id).peekable(); + let mut args = args.non_erasable_generics().peekable(); if args.peek().is_none() { return false; } @@ -736,12 +724,11 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S pub fn push_generic_params<'tcx>( tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>, - def_id: DefId, output: &mut String, ) { let _prof = tcx.prof.generic_activity("compute_debuginfo_type_name"); let mut visited = FxHashSet::default(); - push_generic_params_internal(tcx, args, def_id, output, &mut visited); + push_generic_params_internal(tcx, args, output, &mut visited); } fn push_closure_or_coroutine_name<'tcx>( @@ -786,7 +773,7 @@ fn push_closure_or_coroutine_name<'tcx>( // FIXME(async_closures): This is probably not going to be correct w.r.t. // multiple coroutine flavors. Maybe truncate to (parent + 1)? let args = args.truncate_to(tcx, generics); - push_generic_params_internal(tcx, args, enclosing_fn_def_id, output, visited); + push_generic_params_internal(tcx, args, output, visited); } fn push_close_angle_bracket(cpp_like_debuginfo: bool, output: &mut String) { diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index 1121ca532401..09ddc6ca9de1 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -1,7 +1,6 @@ //! Bounds are restrictions applied to some types after they've been lowered from the HIR to the //! [`rustc_middle::ty`] form. -use rustc_data_structures::fx::FxIndexMap; use rustc_hir::LangItem; use rustc_middle::ty::{self, Ty, TyCtxt, Upcast}; use rustc_span::Span; @@ -25,7 +24,6 @@ use rustc_span::Span; #[derive(Default, PartialEq, Eq, Clone, Debug)] pub(crate) struct Bounds<'tcx> { clauses: Vec<(ty::Clause<'tcx>, Span)>, - effects_min_tys: FxIndexMap, Span>, } impl<'tcx> Bounds<'tcx> { @@ -96,15 +94,7 @@ impl<'tcx> Bounds<'tcx> { } } - pub(crate) fn clauses( - &self, - // FIXME(effects): remove tcx - _tcx: TyCtxt<'tcx>, - ) -> impl Iterator, Span)> + '_ { + pub(crate) fn clauses(&self) -> impl Iterator, Span)> + '_ { self.clauses.iter().cloned() } - - pub(crate) fn effects_min_tys(&self) -> impl Iterator> + '_ { - self.effects_min_tys.keys().copied() - } } diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 075faea3d2aa..b2ad42be6c7f 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -67,7 +67,7 @@ fn associated_type_bounds<'tcx>( ) }); - let all_bounds = tcx.arena.alloc_from_iter(bounds.clauses(tcx).chain(bounds_from_parent)); + let all_bounds = tcx.arena.alloc_from_iter(bounds.clauses().chain(bounds_from_parent)); debug!( "associated_type_bounds({}) = {:?}", tcx.def_path_str(assoc_item_def_id.to_def_id()), @@ -339,7 +339,7 @@ fn opaque_type_bounds<'tcx>( } debug!(?bounds); - tcx.arena.alloc_from_iter(bounds.clauses(tcx)) + tcx.arena.alloc_from_iter(bounds.clauses()) }) } diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 61dc4b1677c6..644ff0c667c6 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -106,7 +106,6 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen return ty::GenericPredicates { parent: Some(tcx.parent(def_id.to_def_id())), predicates: tcx.arena.alloc_from_iter(predicates), - effects_min_tys: ty::List::empty(), }; } @@ -128,7 +127,6 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen return ty::GenericPredicates { parent: Some(impl_def_id), predicates: tcx.arena.alloc_from_iter(impl_predicates), - effects_min_tys: ty::List::empty(), }; } @@ -154,7 +152,6 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // We use an `IndexSet` to preserve order of insertion. // Preserving the order of insertion is important here so as not to break UI tests. let mut predicates: FxIndexSet<(ty::Clause<'_>, Span)> = FxIndexSet::default(); - let mut effects_min_tys = Vec::new(); let hir_generics = node.generics().unwrap_or(NO_GENERICS); if let Node::Item(item) = node { @@ -189,8 +186,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen ty::List::empty(), PredicateFilter::All, ); - predicates.extend(bounds.clauses(tcx)); - effects_min_tys.extend(bounds.effects_min_tys()); + predicates.extend(bounds.clauses()); } // In default impls, we can assume that the self type implements @@ -223,7 +219,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen param.span, ); trace!(?bounds); - predicates.extend(bounds.clauses(tcx)); + predicates.extend(bounds.clauses()); trace!(?predicates); } hir::GenericParamKind::Const { .. } => { @@ -275,8 +271,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen bound_vars, PredicateFilter::All, ); - predicates.extend(bounds.clauses(tcx)); - effects_min_tys.extend(bounds.effects_min_tys()); + predicates.extend(bounds.clauses()); } hir::WherePredicate::RegionPredicate(region_pred) => { @@ -348,7 +343,6 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen ty::GenericPredicates { parent: generics.parent, predicates: tcx.arena.alloc_from_iter(predicates), - effects_min_tys: tcx.mk_type_list(&effects_min_tys), } } @@ -499,7 +493,6 @@ pub(super) fn explicit_predicates_of<'tcx>( ty::GenericPredicates { parent: predicates_and_bounds.parent, predicates: tcx.arena.alloc_slice(&predicates), - effects_min_tys: predicates_and_bounds.effects_min_tys, } } } else { @@ -551,7 +544,6 @@ pub(super) fn explicit_predicates_of<'tcx>( return GenericPredicates { parent: parent_preds.parent, predicates: { tcx.arena.alloc_from_iter(filtered_predicates) }, - effects_min_tys: parent_preds.effects_min_tys, }; } gather_explicit_predicates_of(tcx, def_id) @@ -630,7 +622,7 @@ pub(super) fn implied_predicates_with_filter<'tcx>( // Combine the two lists to form the complete set of superbounds: let implied_bounds = - &*tcx.arena.alloc_from_iter(bounds.clauses(tcx).chain(where_bounds_that_match)); + &*tcx.arena.alloc_from_iter(bounds.clauses().chain(where_bounds_that_match)); debug!(?implied_bounds); // Now require that immediate supertraits are lowered, which will, in @@ -874,7 +866,7 @@ impl<'tcx> ItemCtxt<'tcx> { ); } - bounds.clauses(self.tcx).collect() + bounds.clauses().collect() } } @@ -966,7 +958,7 @@ pub(super) fn const_conditions<'tcx>( ty::ConstConditions { parent: has_parent.then(|| tcx.local_parent(def_id).to_def_id()), - predicates: tcx.arena.alloc_from_iter(bounds.clauses(tcx).map(|(clause, span)| { + predicates: tcx.arena.alloc_from_iter(bounds.clauses().map(|(clause, span)| { ( clause.kind().map_bound(|clause| match clause { ty::ClauseKind::HostEffect(ty::HostEffectPredicate { diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index 4d3595965c91..e65420ea8bf4 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -278,8 +278,6 @@ impl<'tcx> PredicatesBuilder<'tcx> { ty::GenericPredicates { parent: self.parent, predicates: self.tcx.arena.alloc_from_iter(preds), - // FIXME(fn_delegation): Support effects. - effects_min_tys: ty::List::empty(), } } } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index 3449270564a7..890e8fa99e65 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -62,7 +62,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut trait_bounds = vec![]; let mut projection_bounds = vec![]; - for (pred, span) in bounds.clauses(tcx) { + for (pred, span) in bounds.clauses() { let bound_pred = pred.kind(); match bound_pred.skip_binder() { ty::ClauseKind::Trait(trait_pred) => { diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 56ca9167d4da..d8d99deeb2c9 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -86,11 +86,9 @@ impl<'tcx> MonoItem<'tcx> { } } - pub fn is_generic_fn(&self, tcx: TyCtxt<'tcx>) -> bool { + pub fn is_generic_fn(&self) -> bool { match self { - MonoItem::Fn(instance) => { - instance.args.non_erasable_generics(tcx, instance.def_id()).next().is_some() - } + MonoItem::Fn(instance) => instance.args.non_erasable_generics().next().is_some(), MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false, } } diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 64405d18c7d2..84f52bfe48f2 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -70,7 +70,7 @@ impl<'tcx> Ty<'tcx> { /// ADTs with no type arguments. pub fn is_simple_text(self, tcx: TyCtxt<'tcx>) -> bool { match self.kind() { - Adt(def, args) => args.non_erasable_generics(tcx, def.did()).next().is_none(), + Adt(_, args) => args.non_erasable_generics().next().is_none(), Ref(_, ty, _) => ty.is_simple_text(tcx), _ => self.is_simple_ty(), } diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 56111ee063eb..737f1362b34c 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -501,9 +501,6 @@ impl<'tcx> GenericArgs<'tcx> { #[inline] pub fn non_erasable_generics( &'tcx self, - // FIXME(effects): Remove these - _tcx: TyCtxt<'tcx>, - _def_id: DefId, ) -> impl DoubleEndedIterator> + 'tcx { self.iter().filter_map(|k| match k.unpack() { ty::GenericArgKind::Lifetime(_) => None, diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index ab1b8fa6a732..19779740227b 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -360,7 +360,6 @@ impl<'tcx> Generics { pub struct GenericPredicates<'tcx> { pub parent: Option, pub predicates: &'tcx [(Clause<'tcx>, Span)], - pub effects_min_tys: &'tcx ty::List>, } impl<'tcx> GenericPredicates<'tcx> { diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 61cb43225015..e237d382900f 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -204,7 +204,7 @@ impl<'tcx> Instance<'tcx> { } // If this a non-generic instance, it cannot be a shared monomorphization. - self.args.non_erasable_generics(tcx, self.def_id()).next()?; + self.args.non_erasable_generics().next()?; // compiler_builtins cannot use upstream monomorphizations. if tcx.is_compiler_builtins(LOCAL_CRATE) { diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index c9f24764cc2a..42d6bdf6cee7 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -439,12 +439,7 @@ impl<'tcx> Inliner<'tcx> { // Reachability pass defines which functions are eligible for inlining. Generally inlining // other functions is incorrect because they could reference symbols that aren't exported. - let is_generic = callsite - .callee - .args - .non_erasable_generics(self.tcx, callsite.callee.def_id()) - .next() - .is_some(); + let is_generic = callsite.callee.args.non_erasable_generics().next().is_some(); if !is_generic && !cross_crate_inlinable { return Err("not exported"); } diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 3f9a0df03015..e4fe719c2183 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -505,7 +505,7 @@ fn collect_items_rec<'tcx>( // Check for PMEs and emit a diagnostic if one happened. To try to show relevant edges of the // mono item graph. if tcx.dcx().err_count() > error_count - && starting_item.node.is_generic_fn(tcx) + && starting_item.node.is_generic_fn() && starting_item.node.is_user_defined() { let formatted_item = with_no_trimmed_paths!(starting_item.node.to_string()); diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 9bf7e67417ef..e2a6d392ca09 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -229,7 +229,7 @@ where } let characteristic_def_id = characteristic_def_id_of_mono_item(cx.tcx, mono_item); - let is_volatile = is_incremental_build && mono_item.is_generic_fn(cx.tcx); + let is_volatile = is_incremental_build && mono_item.is_generic_fn(); let cgu_name = match characteristic_def_id { Some(def_id) => compute_codegen_unit_name( @@ -822,7 +822,7 @@ fn mono_item_visibility<'tcx>( return Visibility::Hidden; } - let is_generic = instance.args.non_erasable_generics(tcx, def_id).next().is_some(); + let is_generic = instance.args.non_erasable_generics().next().is_some(); // Upstream `DefId` instances get different handling than local ones. let Some(def_id) = def_id.as_local() else { diff --git a/compiler/rustc_smir/src/rustc_smir/context.rs b/compiler/rustc_smir/src/rustc_smir/context.rs index 8fa8f2ac4021..9514ec883ae5 100644 --- a/compiler/rustc_smir/src/rustc_smir/context.rs +++ b/compiler/rustc_smir/src/rustc_smir/context.rs @@ -161,8 +161,7 @@ impl<'tcx> Context for TablesWrapper<'tcx> { fn predicates_of(&self, def_id: stable_mir::DefId) -> stable_mir::ty::GenericPredicates { let mut tables = self.0.borrow_mut(); let def_id = tables[def_id]; - let GenericPredicates { parent, predicates, effects_min_tys: _ } = - tables.tcx.predicates_of(def_id); + let GenericPredicates { parent, predicates } = tables.tcx.predicates_of(def_id); stable_mir::ty::GenericPredicates { parent: parent.map(|did| tables.trait_def(did)), predicates: predicates @@ -183,8 +182,7 @@ impl<'tcx> Context for TablesWrapper<'tcx> { ) -> stable_mir::ty::GenericPredicates { let mut tables = self.0.borrow_mut(); let def_id = tables[def_id]; - let GenericPredicates { parent, predicates, effects_min_tys: _ } = - tables.tcx.explicit_predicates_of(def_id); + let GenericPredicates { parent, predicates } = tables.tcx.explicit_predicates_of(def_id); stable_mir::ty::GenericPredicates { parent: parent.map(|did| tables.trait_def(did)), predicates: predicates diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs index 78e6b9ec6e85..5c5ab435dbd7 100644 --- a/compiler/rustc_symbol_mangling/src/lib.rs +++ b/compiler/rustc_symbol_mangling/src/lib.rs @@ -135,7 +135,7 @@ fn symbol_name_provider<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty // This closure determines the instantiating crate for instances that // need an instantiating-crate-suffix for their symbol name, in order // to differentiate between local copies. - if is_generic(instance, tcx) { + if is_generic(instance) { // For generics we might find re-usable upstream instances. If there // is one, we rely on the symbol being instantiated locally. instance.upstream_monomorphization(tcx).unwrap_or(LOCAL_CRATE) @@ -241,7 +241,7 @@ fn compute_symbol_name<'tcx>( // the ID of the instantiating crate. This avoids symbol conflicts // in case the same instances is emitted in two crates of the same // project. - let avoid_cross_crate_conflicts = is_generic(instance, tcx) || is_globally_shared_function; + let avoid_cross_crate_conflicts = is_generic(instance) || is_globally_shared_function; let instantiating_crate = avoid_cross_crate_conflicts.then(compute_instantiating_crate); @@ -276,6 +276,6 @@ fn compute_symbol_name<'tcx>( symbol } -fn is_generic<'tcx>(instance: Instance<'tcx>, tcx: TyCtxt<'tcx>) -> bool { - instance.args.non_erasable_generics(tcx, instance.def_id()).next().is_some() +fn is_generic<'tcx>(instance: Instance<'tcx>) -> bool { + instance.args.non_erasable_generics().next().is_some() } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 81264b49dfd0..ea349f878e0e 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1400,7 +1400,6 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo clean_ty_generics(cx, tcx.generics_of(assoc_item.def_id), ty::GenericPredicates { parent: None, predicates, - effects_min_tys: ty::List::empty(), }); simplify::move_bounds_to_generic_parameters(&mut generics); diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index 82a66cc92029..e8e21edd4943 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -324,7 +324,7 @@ fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &h // If the current self type doesn't implement Copy (due to generic constraints), search to see if // there's a Copy impl for any instance of the adt. if !is_copy(cx, ty) { - if ty_subs.non_erasable_generics(cx.tcx, ty_adt.did()).next().is_some() { + if ty_subs.non_erasable_generics().next().is_some() { let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(©_id).map_or(false, |impls| { impls.iter().any(|&id| { matches!(cx.tcx.type_of(id).instantiate_identity().kind(), ty::Adt(adt, _) From f2f67232a53b79b44c5b87fe5757ef1f18f4b590 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 26 Oct 2024 11:35:16 +0800 Subject: [PATCH 265/366] Deny calls to non-`#[const_trait]` methods in MIR constck --- .../src/check_consts/check.rs | 29 +++++--- .../unify-op-with-fn-call.stderr | 30 ++++++--- tests/ui/const-generics/issue-93647.stderr | 4 -- .../const-generics/issues/issue-90318.stderr | 8 --- tests/ui/consts/closure-in-foreign-crate.rs | 6 +- tests/ui/consts/const-fn-error.stderr | 8 --- tests/ui/consts/const-for-feature-gate.stderr | 8 --- tests/ui/consts/const-for.stderr | 8 --- tests/ui/consts/const-try-feature-gate.stderr | 8 --- tests/ui/consts/const-try.rs | 2 + tests/ui/consts/const-try.stderr | 19 +++++- tests/ui/consts/const_cmp_type_id.rs | 7 +- tests/ui/consts/const_cmp_type_id.stderr | 34 ++++++++++ tests/ui/consts/control-flow/loop.stderr | 16 ----- tests/ui/consts/control-flow/try.stderr | 8 --- tests/ui/consts/fn_trait_refs.stderr | 20 ------ .../invalid-inline-const-in-match-arm.stderr | 4 -- tests/ui/consts/issue-28113.stderr | 4 -- tests/ui/consts/issue-56164.stderr | 4 -- .../issue-68542-closure-in-array-len.stderr | 4 -- .../ui/consts/issue-73976-monomorphic.stderr | 4 -- tests/ui/consts/issue-90870.rs | 3 - tests/ui/consts/issue-90870.stderr | 18 +---- tests/ui/consts/issue-94675.stderr | 4 -- tests/ui/consts/try-operator.stderr | 16 ----- .../unstable-const-fn-in-libcore.stderr | 4 -- .../impl-trait/normalize-tait-in-const.stderr | 4 -- tests/ui/issues/issue-25901.stderr | 4 -- tests/ui/never_type/issue-52443.stderr | 8 --- .../issue-35813-postfix-after-cast.stderr | 4 -- tests/ui/resolve/issue-39559-2.stderr | 8 --- ...bitrary-self-from-method-substs-ice.stderr | 4 -- .../statics/check-values-constraints.stderr | 4 -- .../call-const-trait-method-pass.stderr | 8 --- .../const-traits/call-generic-in-impl.stderr | 4 -- .../call-generic-method-chain.stderr | 23 ++++++- .../call-generic-method-dup-bound.stderr | 35 +++++++++- .../const-traits/call-generic-method-fail.rs | 4 +- .../call-generic-method-fail.stderr | 15 +++++ .../call-generic-method-pass.stderr | 23 ++++++- tests/ui/traits/const-traits/call.rs | 3 +- tests/ui/traits/const-traits/call.stderr | 12 ++++ .../const-closure-trait-method-fail.stderr | 4 -- .../const-closure-trait-method.stderr | 4 -- .../traits/const-traits/const-closures.stderr | 12 ---- .../derive-const-non-const-type.stderr | 14 +++- .../const_derives/derive-const-use.stderr | 66 +++++++++++++++---- .../derive-const-with-params.stderr | 22 ++++++- ...nst_closure-const_trait_impl-ice-113381.rs | 5 +- ...closure-const_trait_impl-ice-113381.stderr | 11 ++++ .../ice-112822-expected-type-for-param.rs | 1 + .../ice-112822-expected-type-for-param.stderr | 11 +++- .../traits/const-traits/generic-bound.stderr | 4 -- .../ui/traits/const-traits/hir-const-check.rs | 2 + .../const-traits/hir-const-check.stderr | 25 ++++++- .../ice-126148-failed-to-normalize.rs | 2 + .../ice-126148-failed-to-normalize.stderr | 21 +++++- .../inline-incorrect-early-bound-in-ctfe.rs | 1 + ...nline-incorrect-early-bound-in-ctfe.stderr | 13 +++- .../traits/const-traits/issue-102985.stderr | 4 -- .../ui/traits/const-traits/issue-88155.stderr | 4 -- .../match-non-const-eq.gated.stderr | 4 -- .../match-non-const-eq.stock.stderr | 4 -- ...st-op-const-closure-non-const-outer.stderr | 4 -- .../non-const-op-in-closure-in-const.stderr | 4 -- .../const-traits/std-impl-gate.gated.stderr | 4 -- .../const-traits/std-impl-gate.stock.stderr | 4 -- .../super-traits-fail-2.nn.stderr | 11 +++- .../super-traits-fail-2.ny.stderr | 11 +++- .../const-traits/super-traits-fail-2.rs | 1 + .../super-traits-fail-3.nn.stderr | 11 +++- .../super-traits-fail-3.ny.stderr | 11 +++- .../const-traits/super-traits-fail-3.rs | 1 + .../trait-default-body-stability.stderr | 19 +++++- .../typeck_type_placeholder_item.stderr | 8 --- 75 files changed, 440 insertions(+), 326 deletions(-) create mode 100644 tests/ui/consts/const_cmp_type_id.stderr create mode 100644 tests/ui/traits/const-traits/call-generic-method-fail.stderr create mode 100644 tests/ui/traits/const-traits/call.stderr create mode 100644 tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.stderr diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 8f1a887a9614..004fb12419f1 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -616,14 +616,16 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { let mut is_trait = false; // Attempting to call a trait method? - if tcx.trait_of_item(callee).is_some() { + if let Some(trait_did) = tcx.trait_of_item(callee) { trace!("attempting to call a trait method"); + + let trait_is_const = tcx.is_const_trait(trait_did); // trait method calls are only permitted when `effects` is enabled. - // we don't error, since that is handled by typeck. We try to resolve - // the trait into the concrete method, and uses that for const stability - // checks. + // typeck ensures the conditions for calling a const trait method are met, + // so we only error if the trait isn't const. We try to resolve the trait + // into the concrete method, and uses that for const stability checks. // FIXME(effects) we might consider moving const stability checks to typeck as well. - if tcx.features().effects() { + if tcx.features().effects() && trait_is_const { // This skips the check below that ensures we only call `const fn`. is_trait = true; @@ -638,17 +640,24 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { callee = def; } } else { + // if the trait is const but the user has not enabled the feature(s), + // suggest them. + let feature = if trait_is_const { + Some(if tcx.features().const_trait_impl() { + sym::effects + } else { + sym::const_trait_impl + }) + } else { + None + }; self.check_op(ops::FnCallNonConst { caller, callee, args: fn_args, span: *fn_span, call_source, - feature: Some(if tcx.features().const_trait_impl() { - sym::effects - } else { - sym::const_trait_impl - }), + feature, }); // If we allowed this, we're in miri-unleashed mode, so we might // as well skip the remaining checks. diff --git a/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr b/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr index bae8249845c0..b8d7c94bddc8 100644 --- a/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr +++ b/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr @@ -27,11 +27,13 @@ LL + #[derive(ConstParamTy)] LL | struct Foo(u8); | -error[E0284]: type annotations needed: cannot normalize `foo::{constant#0}` - --> $DIR/unify-op-with-fn-call.rs:20:25 +error[E0015]: cannot call non-const operator in constants + --> $DIR/unify-op-with-fn-call.rs:20:39 | LL | fn foo(a: Evaluatable<{ N + N }>) { - | ^^^^^^^^^^^^^^^^^^^^^^ cannot normalize `foo::{constant#0}` + | ^^^^^ + | + = note: calls in constants are limited to constant functions, tuple structs and tuple variants error[E0741]: `Foo` must implement `ConstParamTy` to be used as the type of a const generic parameter --> $DIR/unify-op-with-fn-call.rs:20:17 @@ -63,11 +65,21 @@ error[E0284]: type annotations needed: cannot normalize `foo2::{constant#0}` LL | fn foo2(a: Evaluatable2<{ N + N }>) { | ^^^^^^^^^^^^^^^^^^^^^^^ cannot normalize `foo2::{constant#0}` -error[E0284]: type annotations needed: cannot normalize `foo::{constant#0}` - --> $DIR/unify-op-with-fn-call.rs:21:11 +error[E0015]: cannot call non-const fn `::add` in constants + --> $DIR/unify-op-with-fn-call.rs:21:13 | LL | bar::<{ std::ops::Add::add(N, N) }>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot normalize `foo::{constant#0}` + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + +error[E0015]: cannot call non-const fn `::add` in constants + --> $DIR/unify-op-with-fn-call.rs:30:14 + | +LL | bar2::<{ std::ops::Add::add(N, N) }>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: calls in constants are limited to constant functions, tuple structs and tuple variants error[E0284]: type annotations needed: cannot normalize `foo2::{constant#0}` --> $DIR/unify-op-with-fn-call.rs:30:12 @@ -75,7 +87,7 @@ error[E0284]: type annotations needed: cannot normalize `foo2::{constant#0}` LL | bar2::<{ std::ops::Add::add(N, N) }>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot normalize `foo2::{constant#0}` -error: aborting due to 9 previous errors +error: aborting due to 10 previous errors -Some errors have detailed explanations: E0284, E0741. -For more information about an error, try `rustc --explain E0284`. +Some errors have detailed explanations: E0015, E0284, E0741. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/const-generics/issue-93647.stderr b/tests/ui/const-generics/issue-93647.stderr index 81f50a1b5172..38fb3d79459f 100644 --- a/tests/ui/const-generics/issue-93647.stderr +++ b/tests/ui/const-generics/issue-93647.stderr @@ -6,10 +6,6 @@ LL | (||1usize)() | = note: closures need an RFC before allowed to be called in constants = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 1 previous error diff --git a/tests/ui/const-generics/issues/issue-90318.stderr b/tests/ui/const-generics/issues/issue-90318.stderr index a534e8f8d44f..9c7cb5ceb58c 100644 --- a/tests/ui/const-generics/issues/issue-90318.stderr +++ b/tests/ui/const-generics/issues/issue-90318.stderr @@ -29,10 +29,6 @@ LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/any.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const operator in constants --> $DIR/issue-90318.rs:22:10 @@ -43,10 +39,6 @@ LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/any.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 4 previous errors diff --git a/tests/ui/consts/closure-in-foreign-crate.rs b/tests/ui/consts/closure-in-foreign-crate.rs index 701cf0910450..94e40fcf1e41 100644 --- a/tests/ui/consts/closure-in-foreign-crate.rs +++ b/tests/ui/consts/closure-in-foreign-crate.rs @@ -1,8 +1,8 @@ -//@ aux-build:closure-in-foreign-crate.rs +// FIXME(effects) aux-build:closure-in-foreign-crate.rs //@ build-pass -extern crate closure_in_foreign_crate; +// FIXME(effects) extern crate closure_in_foreign_crate; -const _: () = closure_in_foreign_crate::test(); +// FIXME(effects) const _: () = closure_in_foreign_crate::test(); fn main() {} diff --git a/tests/ui/consts/const-fn-error.stderr b/tests/ui/consts/const-fn-error.stderr index e886a0b4fe44..42a6f2704c9e 100644 --- a/tests/ui/consts/const-fn-error.stderr +++ b/tests/ui/consts/const-fn-error.stderr @@ -22,10 +22,6 @@ LL | for i in 0..x { note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn ` as Iterator>::next` in constant functions --> $DIR/const-fn-error.rs:5:14 @@ -34,10 +30,6 @@ LL | for i in 0..x { | ^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/const-for-feature-gate.stderr b/tests/ui/consts/const-for-feature-gate.stderr index 3344611a60ca..6e099a3159d9 100644 --- a/tests/ui/consts/const-for-feature-gate.stderr +++ b/tests/ui/consts/const-for-feature-gate.stderr @@ -17,10 +17,6 @@ LL | for _ in 0..5 {} note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/const-for-feature-gate.rs:4:14 @@ -29,10 +25,6 @@ LL | for _ in 0..5 {} | ^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/const-for.stderr b/tests/ui/consts/const-for.stderr index 2b817c2d20c8..78336dc93e85 100644 --- a/tests/ui/consts/const-for.stderr +++ b/tests/ui/consts/const-for.stderr @@ -7,10 +7,6 @@ LL | for _ in 0..5 {} note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/const-for.rs:4:14 @@ -19,10 +15,6 @@ LL | for _ in 0..5 {} | ^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 2 previous errors diff --git a/tests/ui/consts/const-try-feature-gate.stderr b/tests/ui/consts/const-try-feature-gate.stderr index 0c4c16fc56ac..dc1dabc2f4f6 100644 --- a/tests/ui/consts/const-try-feature-gate.stderr +++ b/tests/ui/consts/const-try-feature-gate.stderr @@ -17,10 +17,6 @@ LL | Some(())?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/option.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: `?` cannot convert from residual of `Option<()>` in constant functions --> $DIR/const-try-feature-gate.rs:4:5 @@ -31,10 +27,6 @@ LL | Some(())?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/option.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/const-try.rs b/tests/ui/consts/const-try.rs index 2862b6ffb17b..758c4dd1e8c4 100644 --- a/tests/ui/consts/const-try.rs +++ b/tests/ui/consts/const-try.rs @@ -34,6 +34,8 @@ impl const Try for TryMe { const fn t() -> TryMe { TryMe?; + //~^ ERROR `?` cannot determine the branch of `TryMe` in constant functions + //~| ERROR `?` cannot convert from residual of `TryMe` in constant functions TryMe } diff --git a/tests/ui/consts/const-try.stderr b/tests/ui/consts/const-try.stderr index ba9da2421073..abb1a921cfa4 100644 --- a/tests/ui/consts/const-try.stderr +++ b/tests/ui/consts/const-try.stderr @@ -16,5 +16,22 @@ LL | impl const Try for TryMe { = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error: aborting due to 2 previous errors +error[E0015]: `?` cannot determine the branch of `TryMe` in constant functions + --> $DIR/const-try.rs:36:5 + | +LL | TryMe?; + | ^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +error[E0015]: `?` cannot convert from residual of `TryMe` in constant functions + --> $DIR/const-try.rs:36:5 + | +LL | TryMe?; + | ^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/const_cmp_type_id.rs b/tests/ui/consts/const_cmp_type_id.rs index 77482007be48..3a54764f422f 100644 --- a/tests/ui/consts/const_cmp_type_id.rs +++ b/tests/ui/consts/const_cmp_type_id.rs @@ -1,4 +1,3 @@ -//@ check-pass //@ compile-flags: -Znext-solver #![feature(const_type_id, const_trait_impl, effects)] #![allow(incomplete_features)] @@ -7,11 +6,13 @@ use std::any::TypeId; fn main() { const { - // FIXME(effects) this isn't supposed to pass (right now) but it did. - // revisit binops typeck please. assert!(TypeId::of::() == TypeId::of::()); + //~^ ERROR cannot call non-const operator in constants assert!(TypeId::of::<()>() != TypeId::of::()); + //~^ ERROR cannot call non-const operator in constants let _a = TypeId::of::() < TypeId::of::(); + //~^ ERROR cannot call non-const operator in constants // can't assert `_a` because it is not deterministic + // FIXME(effects) make it pass } } diff --git a/tests/ui/consts/const_cmp_type_id.stderr b/tests/ui/consts/const_cmp_type_id.stderr new file mode 100644 index 000000000000..12f35361b808 --- /dev/null +++ b/tests/ui/consts/const_cmp_type_id.stderr @@ -0,0 +1,34 @@ +error[E0015]: cannot call non-const operator in constants + --> $DIR/const_cmp_type_id.rs:9:17 + | +LL | assert!(TypeId::of::() == TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + +error[E0015]: cannot call non-const operator in constants + --> $DIR/const_cmp_type_id.rs:11:17 + | +LL | assert!(TypeId::of::<()>() != TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + +error[E0015]: cannot call non-const operator in constants + --> $DIR/const_cmp_type_id.rs:13:18 + | +LL | let _a = TypeId::of::() < TypeId::of::(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/control-flow/loop.stderr b/tests/ui/consts/control-flow/loop.stderr index 13d5d3e0b55c..5e43c70e9dfb 100644 --- a/tests/ui/consts/control-flow/loop.stderr +++ b/tests/ui/consts/control-flow/loop.stderr @@ -35,10 +35,6 @@ LL | for i in 0..4 { note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/loop.rs:53:14 @@ -47,10 +43,6 @@ LL | for i in 0..4 { | ^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot convert `std::ops::Range` into an iterator in constants --> $DIR/loop.rs:59:14 @@ -61,10 +53,6 @@ LL | for i in 0..4 { note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/loop.rs:59:14 @@ -73,10 +61,6 @@ LL | for i in 0..4 { | ^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 6 previous errors diff --git a/tests/ui/consts/control-flow/try.stderr b/tests/ui/consts/control-flow/try.stderr index e08f52369faa..5e2c77318e78 100644 --- a/tests/ui/consts/control-flow/try.stderr +++ b/tests/ui/consts/control-flow/try.stderr @@ -17,10 +17,6 @@ LL | x?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/option.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: `?` cannot convert from residual of `Option` in constant functions --> $DIR/try.rs:6:5 @@ -31,10 +27,6 @@ LL | x?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/option.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/fn_trait_refs.stderr b/tests/ui/consts/fn_trait_refs.stderr index 2b012432afd4..82b2b87c4a5a 100644 --- a/tests/ui/consts/fn_trait_refs.stderr +++ b/tests/ui/consts/fn_trait_refs.stderr @@ -183,10 +183,6 @@ LL | assert!(test_one == (1, 1, 1)); | ^^^^^^^^^^^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: cannot call non-const operator in constants --> $DIR/fn_trait_refs.rs:73:17 @@ -195,10 +191,6 @@ LL | assert!(test_two == (2, 2)); | ^^^^^^^^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: cannot call non-const closure in constant functions --> $DIR/fn_trait_refs.rs:15:5 @@ -211,10 +203,6 @@ help: consider further restricting this bound | LL | T: ~const Fn<()> + ~const Destruct + ~const Fn(), | +++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/fn_trait_refs.rs:11:23 @@ -236,10 +224,6 @@ help: consider further restricting this bound | LL | T: ~const FnMut<()> + ~const Destruct + ~const FnMut(), | ++++++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/fn_trait_refs.rs:18:27 @@ -261,10 +245,6 @@ help: consider further restricting this bound | LL | T: ~const FnOnce<()> + ~const FnOnce(), | +++++++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0493]: destructor of `T` cannot be evaluated at compile-time --> $DIR/fn_trait_refs.rs:32:21 diff --git a/tests/ui/consts/invalid-inline-const-in-match-arm.stderr b/tests/ui/consts/invalid-inline-const-in-match-arm.stderr index 0e41053a29df..2e48837bdcdc 100644 --- a/tests/ui/consts/invalid-inline-const-in-match-arm.stderr +++ b/tests/ui/consts/invalid-inline-const-in-match-arm.stderr @@ -6,10 +6,6 @@ LL | const { (|| {})() } => {} | = note: closures need an RFC before allowed to be called in constants = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: could not evaluate constant pattern --> $DIR/invalid-inline-const-in-match-arm.rs:5:9 diff --git a/tests/ui/consts/issue-28113.stderr b/tests/ui/consts/issue-28113.stderr index c2f53870173a..401536c1353e 100644 --- a/tests/ui/consts/issue-28113.stderr +++ b/tests/ui/consts/issue-28113.stderr @@ -6,10 +6,6 @@ LL | || -> u8 { 5 }() | = note: closures need an RFC before allowed to be called in constants = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 1 previous error diff --git a/tests/ui/consts/issue-56164.stderr b/tests/ui/consts/issue-56164.stderr index 6ec4ce0fbd70..de5a53c9ad26 100644 --- a/tests/ui/consts/issue-56164.stderr +++ b/tests/ui/consts/issue-56164.stderr @@ -6,10 +6,6 @@ LL | const fn foo() { (||{})() } | = note: closures need an RFC before allowed to be called in constant functions = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: function pointer calls are not allowed in constant functions --> $DIR/issue-56164.rs:5:5 diff --git a/tests/ui/consts/issue-68542-closure-in-array-len.stderr b/tests/ui/consts/issue-68542-closure-in-array-len.stderr index b414a6e0dba0..9f323b2259f8 100644 --- a/tests/ui/consts/issue-68542-closure-in-array-len.stderr +++ b/tests/ui/consts/issue-68542-closure-in-array-len.stderr @@ -6,10 +6,6 @@ LL | a: [(); (|| { 0 })()] | = note: closures need an RFC before allowed to be called in constants = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 1 previous error diff --git a/tests/ui/consts/issue-73976-monomorphic.stderr b/tests/ui/consts/issue-73976-monomorphic.stderr index 79dbed4bea82..ef754b23ff06 100644 --- a/tests/ui/consts/issue-73976-monomorphic.stderr +++ b/tests/ui/consts/issue-73976-monomorphic.stderr @@ -7,10 +7,6 @@ LL | GetTypeId::::VALUE == GetTypeId::::VALUE note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/any.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 1 previous error diff --git a/tests/ui/consts/issue-90870.rs b/tests/ui/consts/issue-90870.rs index e1929c68c70a..b62769a33f8e 100644 --- a/tests/ui/consts/issue-90870.rs +++ b/tests/ui/consts/issue-90870.rs @@ -3,9 +3,6 @@ #![allow(dead_code)] const fn f(a: &u8, b: &u8) -> bool { -//~^ HELP: add `#![feature(const_trait_impl)]` -//~| HELP: add `#![feature(const_trait_impl)]` -//~| HELP: add `#![feature(const_trait_impl)]` a == b //~^ ERROR: cannot call non-const operator in constant functions [E0015] //~| HELP: consider dereferencing here diff --git a/tests/ui/consts/issue-90870.stderr b/tests/ui/consts/issue-90870.stderr index df88a0c95cc5..ea987920d7d3 100644 --- a/tests/ui/consts/issue-90870.stderr +++ b/tests/ui/consts/issue-90870.stderr @@ -1,5 +1,5 @@ error[E0015]: cannot call non-const operator in constant functions - --> $DIR/issue-90870.rs:9:5 + --> $DIR/issue-90870.rs:6:5 | LL | a == b | ^^^^^^ @@ -9,13 +9,9 @@ help: consider dereferencing here | LL | *a == *b | + + -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const operator in constant functions - --> $DIR/issue-90870.rs:15:5 + --> $DIR/issue-90870.rs:12:5 | LL | a == b | ^^^^^^ @@ -25,13 +21,9 @@ help: consider dereferencing here | LL | ****a == ****b | ++++ ++++ -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const operator in constant functions - --> $DIR/issue-90870.rs:22:12 + --> $DIR/issue-90870.rs:19:12 | LL | if l == r { | ^^^^^^ @@ -41,10 +33,6 @@ help: consider dereferencing here | LL | if *l == *r { | + + -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/consts/issue-94675.stderr b/tests/ui/consts/issue-94675.stderr index a85c5e10374f..8cad13724f20 100644 --- a/tests/ui/consts/issue-94675.stderr +++ b/tests/ui/consts/issue-94675.stderr @@ -7,10 +7,6 @@ LL | self.bar[0] = baz.len(); note: impl defined here, but it is not `const` --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 1 previous error diff --git a/tests/ui/consts/try-operator.stderr b/tests/ui/consts/try-operator.stderr index 2c8b4c7fcd9c..40d96ed3a100 100644 --- a/tests/ui/consts/try-operator.stderr +++ b/tests/ui/consts/try-operator.stderr @@ -13,10 +13,6 @@ LL | Err(())?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/result.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: `?` cannot convert from residual of `Result` in constant functions --> $DIR/try-operator.rs:10:9 @@ -27,10 +23,6 @@ LL | Err(())?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/result.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: `?` cannot determine the branch of `Option<()>` in constant functions --> $DIR/try-operator.rs:18:9 @@ -41,10 +33,6 @@ LL | None?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/option.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: `?` cannot convert from residual of `Option<()>` in constant functions --> $DIR/try-operator.rs:18:9 @@ -55,10 +43,6 @@ LL | None?; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/option.rs:LL:COL = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 5 previous errors diff --git a/tests/ui/consts/unstable-const-fn-in-libcore.stderr b/tests/ui/consts/unstable-const-fn-in-libcore.stderr index 59476f986032..e546694070dd 100644 --- a/tests/ui/consts/unstable-const-fn-in-libcore.stderr +++ b/tests/ui/consts/unstable-const-fn-in-libcore.stderr @@ -23,10 +23,6 @@ help: consider further restricting this bound | LL | const fn unwrap_or_else T + ~const FnOnce()>(self, f: F) -> T { | +++++++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0493]: destructor of `F` cannot be evaluated at compile-time --> $DIR/unstable-const-fn-in-libcore.rs:19:60 diff --git a/tests/ui/impl-trait/normalize-tait-in-const.stderr b/tests/ui/impl-trait/normalize-tait-in-const.stderr index f1e6207ed817..b370a5d7eb11 100644 --- a/tests/ui/impl-trait/normalize-tait-in-const.stderr +++ b/tests/ui/impl-trait/normalize-tait-in-const.stderr @@ -37,10 +37,6 @@ help: consider further restricting this bound | LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct + ~const Fn(&foo::Alias<'_>)>(fun: F) { | ++++++++++++++++++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0493]: destructor of `F` cannot be evaluated at compile-time --> $DIR/normalize-tait-in-const.rs:26:79 diff --git a/tests/ui/issues/issue-25901.stderr b/tests/ui/issues/issue-25901.stderr index 3fedfd964170..bcbc805908ff 100644 --- a/tests/ui/issues/issue-25901.stderr +++ b/tests/ui/issues/issue-25901.stderr @@ -17,10 +17,6 @@ LL | impl Deref for A { | ^^^^^^^^^^^^^^^^ = note: calls in statics are limited to constant functions, tuple structs and tuple variants = note: consider wrapping this expression in `std::sync::LazyLock::new(|| ...)` -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 1 previous error diff --git a/tests/ui/never_type/issue-52443.stderr b/tests/ui/never_type/issue-52443.stderr index adcff6637b0d..2207ceb50336 100644 --- a/tests/ui/never_type/issue-52443.stderr +++ b/tests/ui/never_type/issue-52443.stderr @@ -50,10 +50,6 @@ LL | [(); { for _ in 0usize.. {}; 0}]; note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/issue-52443.rs:9:21 @@ -62,10 +58,6 @@ LL | [(); { for _ in 0usize.. {}; 0}]; | ^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 5 previous errors; 1 warning emitted diff --git a/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr b/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr index 66b57c772d54..e34371be3d26 100644 --- a/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr +++ b/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr @@ -353,10 +353,6 @@ LL | static bar: &[i32] = &(&[1,2,3] as &[i32][0..1]); | = note: calls in statics are limited to constant functions, tuple structs and tuple variants = note: consider wrapping this expression in `std::sync::LazyLock::new(|| ...)` -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 40 previous errors diff --git a/tests/ui/resolve/issue-39559-2.stderr b/tests/ui/resolve/issue-39559-2.stderr index 7f51357a56f4..ea27e7bd2508 100644 --- a/tests/ui/resolve/issue-39559-2.stderr +++ b/tests/ui/resolve/issue-39559-2.stderr @@ -5,10 +5,6 @@ LL | let array: [usize; Dim3::dim()] | ^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn `::dim` in constants --> $DIR/issue-39559-2.rs:16:15 @@ -17,10 +13,6 @@ LL | = [0; Dim3::dim()]; | ^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 2 previous errors diff --git a/tests/ui/self/arbitrary-self-from-method-substs-ice.stderr b/tests/ui/self/arbitrary-self-from-method-substs-ice.stderr index 505b0a173fad..6ae60e7af47d 100644 --- a/tests/ui/self/arbitrary-self-from-method-substs-ice.stderr +++ b/tests/ui/self/arbitrary-self-from-method-substs-ice.stderr @@ -5,10 +5,6 @@ LL | self.0 | ^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0493]: destructor of `R` cannot be evaluated at compile-time --> $DIR/arbitrary-self-from-method-substs-ice.rs:10:43 diff --git a/tests/ui/statics/check-values-constraints.stderr b/tests/ui/statics/check-values-constraints.stderr index 24763c175fc8..b4ee34530d3b 100644 --- a/tests/ui/statics/check-values-constraints.stderr +++ b/tests/ui/statics/check-values-constraints.stderr @@ -37,10 +37,6 @@ LL | field2: SafeEnum::Variant4("str".to_string()), | = note: calls in statics are limited to constant functions, tuple structs and tuple variants = note: consider wrapping this expression in `std::sync::LazyLock::new(|| ...)` -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0010]: allocations are not allowed in statics --> $DIR/check-values-constraints.rs:96:5 diff --git a/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr b/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr index c1cead542163..32f53137a00e 100644 --- a/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr +++ b/tests/ui/traits/const-traits/call-const-trait-method-pass.stderr @@ -23,10 +23,6 @@ LL | const ADD_INT: Int = Int(1i32) + Int(2i32); | ^^^^^^^^^^^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: cannot call non-const fn `::plus` in constant functions --> $DIR/call-const-trait-method-pass.rs:11:20 @@ -47,10 +43,6 @@ LL | !self.eq(other) | ^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: cannot call non-const fn `::plus` in constant functions --> $DIR/call-const-trait-method-pass.rs:36:7 diff --git a/tests/ui/traits/const-traits/call-generic-in-impl.stderr b/tests/ui/traits/const-traits/call-generic-in-impl.stderr index 368c22675e7f..971e77e372b8 100644 --- a/tests/ui/traits/const-traits/call-generic-in-impl.stderr +++ b/tests/ui/traits/const-traits/call-generic-in-impl.stderr @@ -19,10 +19,6 @@ LL | PartialEq::eq(self, other) | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/traits/const-traits/call-generic-method-chain.stderr b/tests/ui/traits/const-traits/call-generic-method-chain.stderr index 62eed0f14f9c..aa90305c6482 100644 --- a/tests/ui/traits/const-traits/call-generic-method-chain.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-chain.stderr @@ -44,5 +44,26 @@ LL | const fn equals_self_wrapper(t: &T) -> bool { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 5 previous errors; 1 warning emitted +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/call-generic-method-chain.rs:21:5 + | +LL | *t == *t + | ^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +help: consider further restricting this bound + | +LL | const fn equals_self(t: &T) -> bool { + | ++++++++++++++++++++++++++++ +error[E0015]: cannot call non-const fn `::eq` in constant functions + --> $DIR/call-generic-method-chain.rs:16:15 + | +LL | !self.eq(other) + | ^^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 7 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr index 3f9dce919d05..029915b7646d 100644 --- a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr @@ -44,5 +44,38 @@ LL | const fn equals_self2(t: &T) -> bool { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 5 previous errors; 1 warning emitted +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/call-generic-method-dup-bound.rs:21:5 + | +LL | *t == *t + | ^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +help: consider further restricting this bound + | +LL | const fn equals_self(t: &T) -> bool { + | ++++++++++++++++++++++++++++ +error[E0015]: cannot call non-const fn `::eq` in constant functions + --> $DIR/call-generic-method-dup-bound.rs:14:15 + | +LL | !self.eq(other) + | ^^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/call-generic-method-dup-bound.rs:28:5 + | +LL | *t == *t + | ^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +help: consider further restricting this bound + | +LL | const fn equals_self2(t: &T) -> bool { + | ++++++++++++++++++++++++++++ + +error: aborting due to 8 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/call-generic-method-fail.rs b/tests/ui/traits/const-traits/call-generic-method-fail.rs index 86e0eae61c9c..6bfbbef6f762 100644 --- a/tests/ui/traits/const-traits/call-generic-method-fail.rs +++ b/tests/ui/traits/const-traits/call-generic-method-fail.rs @@ -1,12 +1,10 @@ -//@ check-pass //@ compile-flags: -Znext-solver #![allow(incomplete_features)] #![feature(const_trait_impl, effects)] pub const fn equals_self(t: &T) -> bool { *t == *t - // FIXME(effects) ~^ ERROR mismatched types - // FIXME(effects): diagnostic + //~^ ERROR cannot call non-const operator in constant functions } fn main() {} diff --git a/tests/ui/traits/const-traits/call-generic-method-fail.stderr b/tests/ui/traits/const-traits/call-generic-method-fail.stderr new file mode 100644 index 000000000000..5cd4216dce11 --- /dev/null +++ b/tests/ui/traits/const-traits/call-generic-method-fail.stderr @@ -0,0 +1,15 @@ +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/call-generic-method-fail.rs:6:5 + | +LL | *t == *t + | ^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +help: consider further restricting this bound + | +LL | pub const fn equals_self(t: &T) -> bool { + | ++++++++++++++++++++++++++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/call-generic-method-pass.stderr b/tests/ui/traits/const-traits/call-generic-method-pass.stderr index e35de48ed606..97ce7fe1c2a8 100644 --- a/tests/ui/traits/const-traits/call-generic-method-pass.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-pass.stderr @@ -30,5 +30,26 @@ LL | const fn equals_self(t: &T) -> bool { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 3 previous errors; 1 warning emitted +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/call-generic-method-pass.rs:21:5 + | +LL | *t == *t + | ^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +help: consider further restricting this bound + | +LL | const fn equals_self(t: &T) -> bool { + | ++++++++++++++++++++++++++++ +error[E0015]: cannot call non-const fn `::eq` in constant functions + --> $DIR/call-generic-method-pass.rs:16:15 + | +LL | !self.eq(other) + | ^^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 5 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/call.rs b/tests/ui/traits/const-traits/call.rs index af2f7caf88c7..f96fb614ac2f 100644 --- a/tests/ui/traits/const-traits/call.rs +++ b/tests/ui/traits/const-traits/call.rs @@ -1,10 +1,11 @@ -//@ check-pass +// FIXME(effects) check-pass //@ compile-flags: -Znext-solver #![feature(const_closures, const_trait_impl, effects)] #![allow(incomplete_features)] pub const _: () = { assert!((const || true)()); + //~^ ERROR cannot call non-const closure in constants }; fn main() {} diff --git a/tests/ui/traits/const-traits/call.stderr b/tests/ui/traits/const-traits/call.stderr new file mode 100644 index 000000000000..e9bf64092f3b --- /dev/null +++ b/tests/ui/traits/const-traits/call.stderr @@ -0,0 +1,12 @@ +error[E0015]: cannot call non-const closure in constants + --> $DIR/call.rs:7:13 + | +LL | assert!((const || true)()); + | ^^^^^^^^^^^^^^^^^ + | + = note: closures need an RFC before allowed to be called in constants + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr index 4e6707bba51c..f0f033bceef4 100644 --- a/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr +++ b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr @@ -23,10 +23,6 @@ help: consider further restricting this bound | LL | const fn need_const_closure i32 + ~const FnOnce(())>(x: T) -> i32 { | +++++++++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/traits/const-traits/const-closure-trait-method.stderr b/tests/ui/traits/const-traits/const-closure-trait-method.stderr index 0f0cd73cc102..4c5a4d0cdf41 100644 --- a/tests/ui/traits/const-traits/const-closure-trait-method.stderr +++ b/tests/ui/traits/const-traits/const-closure-trait-method.stderr @@ -23,10 +23,6 @@ help: consider further restricting this bound | LL | const fn need_const_closure i32 + ~const FnOnce(())>(x: T) -> i32 { | +++++++++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/traits/const-traits/const-closures.stderr b/tests/ui/traits/const-traits/const-closures.stderr index 4d354cb281fe..a81804a50dc2 100644 --- a/tests/ui/traits/const-traits/const-closures.stderr +++ b/tests/ui/traits/const-traits/const-closures.stderr @@ -65,10 +65,6 @@ help: consider further restricting this bound | LL | const fn answer u8 + ~const Fn()>(f: &F) -> u8 { | +++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: cannot call non-const closure in constant functions --> $DIR/const-closures.rs:24:11 @@ -81,10 +77,6 @@ help: consider further restricting this bound | LL | const fn answer u8 + ~const Fn()>(f: &F) -> u8 { | +++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error[E0015]: cannot call non-const closure in constant functions --> $DIR/const-closures.rs:12:5 @@ -97,10 +89,6 @@ help: consider further restricting this bound | LL | F: ~const FnOnce() -> u8 + ~const Fn(), | +++++++++++++ -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 11 previous errors diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr index 777b3313da6b..4bcc17952e62 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr @@ -22,5 +22,17 @@ LL | #[derive_const(Default)] = note: adding a non-const method body in the future would be a breaking change = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 2 previous errors; 1 warning emitted +error[E0015]: cannot call non-const fn `::default` in constant functions + --> $DIR/derive-const-non-const-type.rs:11:14 + | +LL | #[derive_const(Default)] + | ------- in this derive macro expansion +LL | pub struct S(A); + | ^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) +error: aborting due to 3 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr index ad727fc36cd7..d471a8253ba5 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr @@ -62,29 +62,67 @@ LL | #[derive_const(Default, PartialEq)] = note: adding a non-const method body in the future would be a breaking change = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0080]: evaluation of constant value failed - --> $DIR/derive-const-use.rs:16:14 +error[E0015]: cannot call non-const fn `::default` in constants + --> $DIR/derive-const-use.rs:18:35 | -LL | #[derive_const(Default, PartialEq)] - | ------- in this derive macro expansion -LL | pub struct S((), A); - | ^^ calling non-const function `<() as Default>::default` +LL | const _: () = assert!(S((), A) == S::default()); + | ^^^^^^^^^^^^ | -note: inside `::default` + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + +error[E0015]: cannot call non-const operator in constants + --> $DIR/derive-const-use.rs:18:23 + | +LL | const _: () = assert!(S((), A) == S::default()); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + +error[E0015]: cannot call non-const fn `<() as Default>::default` in constant functions --> $DIR/derive-const-use.rs:16:14 | LL | #[derive_const(Default, PartialEq)] | ------- in this derive macro expansion LL | pub struct S((), A); | ^^ -note: inside `_` - --> $DIR/derive-const-use.rs:18:35 | -LL | const _: () = assert!(S((), A) == S::default()); - | ^^^^^^^^^^^^ + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 8 previous errors; 1 warning emitted +error[E0015]: cannot call non-const fn `::default` in constant functions + --> $DIR/derive-const-use.rs:16:18 + | +LL | #[derive_const(Default, PartialEq)] + | ------- in this derive macro expansion +LL | pub struct S((), A); + | ^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) -Some errors have detailed explanations: E0080, E0635. -For more information about an error, try `rustc --explain E0080`. +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/derive-const-use.rs:16:14 + | +LL | #[derive_const(Default, PartialEq)] + | --------- in this derive macro expansion +LL | pub struct S((), A); + | ^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/derive-const-use.rs:16:18 + | +LL | #[derive_const(Default, PartialEq)] + | --------- in this derive macro expansion +LL | pub struct S((), A); + | ^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 13 previous errors; 1 warning emitted + +Some errors have detailed explanations: E0015, E0635. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr index addce8dcd6c7..33e7e08bb235 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr @@ -30,5 +30,25 @@ LL | #[derive_const(PartialEq)] | = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 3 previous errors; 1 warning emitted +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/derive-const-with-params.rs:8:23 + | +LL | #[derive_const(PartialEq)] + | --------- in this derive macro expansion +LL | pub struct Reverse(T); + | ^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/derive-const-with-params.rs:11:5 + | +LL | a == b + | ^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 5 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.rs b/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.rs index 3debc22098af..8f8e9f065845 100644 --- a/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.rs +++ b/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.rs @@ -1,5 +1,3 @@ -//@ check-pass -// FIXME(effects) this shouldn't pass //@ compile-flags: -Znext-solver #![feature(const_closures, const_trait_impl, effects)] #![allow(incomplete_features)] @@ -14,5 +12,6 @@ impl Foo for () { fn main() { (const || { (()).foo() })(); - // FIXME(effects) ~^ ERROR: cannot call non-const fn + //~^ ERROR: cannot call non-const fn `<() as Foo>::foo` in constant functions + // FIXME(effects) this should probably say constant closures } diff --git a/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.stderr b/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.stderr new file mode 100644 index 000000000000..243e94087bbd --- /dev/null +++ b/tests/ui/traits/const-traits/effects/const_closure-const_trait_impl-ice-113381.stderr @@ -0,0 +1,11 @@ +error[E0015]: cannot call non-const fn `<() as Foo>::foo` in constant functions + --> $DIR/const_closure-const_trait_impl-ice-113381.rs:14:22 + | +LL | (const || { (()).foo() })(); + | ^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.rs b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.rs index 9a9016de3a0d..ab530b109e15 100644 --- a/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.rs +++ b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.rs @@ -10,6 +10,7 @@ const fn test() -> impl ~const Fn() { [first, remainder @ ..] => { assert_eq!(first, &b'f'); //~^ ERROR cannot call non-const fn + //~| ERROR cannot call non-const operator } [] => panic!(), } diff --git a/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr index 526746eec734..edfdf8b5f781 100644 --- a/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr +++ b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr @@ -36,6 +36,15 @@ LL | const fn test() -> impl ~const Fn() { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/ice-112822-expected-type-for-param.rs:11:17 + | +LL | assert_eq!(first, &b'f'); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) + error[E0015]: cannot call non-const fn `core::panicking::assert_failed::<&u8, &u8>` in constant functions --> $DIR/ice-112822-expected-type-for-param.rs:11:17 | @@ -45,7 +54,7 @@ LL | assert_eq!(first, &b'f'); = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 5 previous errors; 1 warning emitted +error: aborting due to 6 previous errors; 1 warning emitted Some errors have detailed explanations: E0015, E0658. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/generic-bound.stderr b/tests/ui/traits/const-traits/generic-bound.stderr index 2baac1d2a168..0444c3195773 100644 --- a/tests/ui/traits/const-traits/generic-bound.stderr +++ b/tests/ui/traits/const-traits/generic-bound.stderr @@ -14,10 +14,6 @@ LL | arg + arg | ^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/hir-const-check.rs b/tests/ui/traits/const-traits/hir-const-check.rs index b3df6495afc9..0ffd60682b0c 100644 --- a/tests/ui/traits/const-traits/hir-const-check.rs +++ b/tests/ui/traits/const-traits/hir-const-check.rs @@ -12,6 +12,8 @@ pub trait MyTrait { impl const MyTrait for () { fn method(&self) -> Option<()> { Some(())?; //~ ERROR `?` is not allowed in a `const fn` + //~^ ERROR `?` cannot determine the branch of `Option<()>` in constant functions + //~| ERROR `?` cannot convert from residual of `Option<()>` in constant functions None } } diff --git a/tests/ui/traits/const-traits/hir-const-check.stderr b/tests/ui/traits/const-traits/hir-const-check.stderr index 19ea734efb77..a22ac2c97397 100644 --- a/tests/ui/traits/const-traits/hir-const-check.stderr +++ b/tests/ui/traits/const-traits/hir-const-check.stderr @@ -17,6 +17,27 @@ LL | Some(())?; = help: add `#![feature(const_try)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: aborting due to 1 previous error; 1 warning emitted +error[E0015]: `?` cannot determine the branch of `Option<()>` in constant functions + --> $DIR/hir-const-check.rs:14:9 + | +LL | Some(())?; + | ^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/option.rs:LL:COL + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -For more information about this error, try `rustc --explain E0658`. +error[E0015]: `?` cannot convert from residual of `Option<()>` in constant functions + --> $DIR/hir-const-check.rs:14:9 + | +LL | Some(())?; + | ^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/option.rs:LL:COL + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 3 previous errors; 1 warning emitted + +Some errors have detailed explanations: E0015, E0658. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs index 717c0e7c0882..da97a0e70ed7 100644 --- a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs +++ b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs @@ -18,6 +18,8 @@ impl const Try for TryMe { const fn t() -> TryMe { TryMe?; + //~^ ERROR `?` cannot determine the branch of `TryMe` in constant functions + //~| ERROR `?` cannot convert from residual of `TryMe` in constant functions TryMe } diff --git a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr index e49436c8f0f7..0ca16a1be409 100644 --- a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr +++ b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr @@ -38,6 +38,23 @@ LL | impl const Try for TryMe { = help: implement the missing item: `fn from_output(_: ::Output) -> Self { todo!() }` = help: implement the missing item: `fn branch(self) -> ControlFlow<::Residual, ::Output> { todo!() }` -error: aborting due to 5 previous errors +error[E0015]: `?` cannot determine the branch of `TryMe` in constant functions + --> $DIR/ice-126148-failed-to-normalize.rs:20:5 + | +LL | TryMe?; + | ^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -For more information about this error, try `rustc --explain E0046`. +error[E0015]: `?` cannot convert from residual of `TryMe` in constant functions + --> $DIR/ice-126148-failed-to-normalize.rs:20:5 + | +LL | TryMe?; + | ^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 7 previous errors + +Some errors have detailed explanations: E0015, E0046. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.rs b/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.rs index e3adcce17b42..8638c4bbd7f1 100644 --- a/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.rs +++ b/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.rs @@ -25,6 +25,7 @@ impl Trait for () { const fn foo() { ().foo(); + //~^ ERROR cannot call non-const fn `<() as Trait>::foo` in constant functions } const UWU: () = foo(); diff --git a/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.stderr b/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.stderr index 2e7801c0b8ac..096b00dd3029 100644 --- a/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.stderr +++ b/tests/ui/traits/const-traits/inline-incorrect-early-bound-in-ctfe.stderr @@ -16,6 +16,15 @@ LL | fn foo(self); LL | fn foo(self) { | ^ found 1 type parameter -error: aborting due to 1 previous error; 1 warning emitted +error[E0015]: cannot call non-const fn `<() as Trait>::foo` in constant functions + --> $DIR/inline-incorrect-early-bound-in-ctfe.rs:27:8 + | +LL | ().foo(); + | ^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -For more information about this error, try `rustc --explain E0049`. +error: aborting due to 2 previous errors; 1 warning emitted + +Some errors have detailed explanations: E0015, E0049. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/issue-102985.stderr b/tests/ui/traits/const-traits/issue-102985.stderr index 8401d1bd4f6c..7c5c5acf2079 100644 --- a/tests/ui/traits/const-traits/issue-102985.stderr +++ b/tests/ui/traits/const-traits/issue-102985.stderr @@ -6,10 +6,6 @@ LL | n => n(), | = note: closures need an RFC before allowed to be called in constants = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/issue-88155.stderr b/tests/ui/traits/const-traits/issue-88155.stderr index afe1ea3b1b73..157b54214fa7 100644 --- a/tests/ui/traits/const-traits/issue-88155.stderr +++ b/tests/ui/traits/const-traits/issue-88155.stderr @@ -5,10 +5,6 @@ LL | T::assoc() | ^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/match-non-const-eq.gated.stderr b/tests/ui/traits/const-traits/match-non-const-eq.gated.stderr index c7d211516614..89e59e5db6ed 100644 --- a/tests/ui/traits/const-traits/match-non-const-eq.gated.stderr +++ b/tests/ui/traits/const-traits/match-non-const-eq.gated.stderr @@ -6,10 +6,6 @@ LL | "a" => (), //FIXME [gated]~ ERROR can't compare `str` with `str` in | = note: `str` cannot be compared in compile-time, and therefore cannot be used in `match`es = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/match-non-const-eq.stock.stderr b/tests/ui/traits/const-traits/match-non-const-eq.stock.stderr index 0f5ecac3891e..89e59e5db6ed 100644 --- a/tests/ui/traits/const-traits/match-non-const-eq.stock.stderr +++ b/tests/ui/traits/const-traits/match-non-const-eq.stock.stderr @@ -6,10 +6,6 @@ LL | "a" => (), //FIXME [gated]~ ERROR can't compare `str` with `str` in | = note: `str` cannot be compared in compile-time, and therefore cannot be used in `match`es = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.stderr b/tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.stderr index c362a1077e33..97ad83130d44 100644 --- a/tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.stderr +++ b/tests/ui/traits/const-traits/non-const-op-const-closure-non-const-outer.stderr @@ -5,10 +5,6 @@ LL | (const || { (()).foo() })(); | ^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr index 2803c37646b1..08a40fe65bfa 100644 --- a/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr +++ b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr @@ -19,10 +19,6 @@ LL | B::from(self) | ^^^^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 3 previous errors diff --git a/tests/ui/traits/const-traits/std-impl-gate.gated.stderr b/tests/ui/traits/const-traits/std-impl-gate.gated.stderr index d761fdce4bf0..f3b171307618 100644 --- a/tests/ui/traits/const-traits/std-impl-gate.gated.stderr +++ b/tests/ui/traits/const-traits/std-impl-gate.gated.stderr @@ -11,10 +11,6 @@ LL | Default::default() | ^^^^^^^^^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(effects)]` to the crate attributes to enable - | -LL + #![feature(effects)] - | error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/std-impl-gate.stock.stderr b/tests/ui/traits/const-traits/std-impl-gate.stock.stderr index b63ea695fc22..7240b5f4a94c 100644 --- a/tests/ui/traits/const-traits/std-impl-gate.stock.stderr +++ b/tests/ui/traits/const-traits/std-impl-gate.stock.stderr @@ -5,10 +5,6 @@ LL | Default::default() | ^^^^^^^^^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 1 previous error diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr index 48bb1907be2e..6277966b08e9 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr @@ -32,5 +32,14 @@ LL | trait Bar: ~const Foo {} | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 4 previous errors +error[E0015]: cannot call non-const fn `::a` in constant functions + --> $DIR/super-traits-fail-2.rs:21:7 + | +LL | x.a(); + | ^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +error: aborting due to 5 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr index a0848fe520e8..60660ecc2797 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr @@ -36,5 +36,14 @@ LL | trait Bar: ~const Foo {} | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 5 previous errors +error[E0015]: cannot call non-const fn `::a` in constant functions + --> $DIR/super-traits-fail-2.rs:21:7 + | +LL | x.a(); + | ^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.rs b/tests/ui/traits/const-traits/super-traits-fail-2.rs index 0ea61f4ae200..1e41d709d6b3 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.rs +++ b/tests/ui/traits/const-traits/super-traits-fail-2.rs @@ -20,6 +20,7 @@ trait Bar: ~const Foo {} const fn foo(x: &T) { x.a(); //[yy,yn]~^ ERROR the trait bound `T: ~const Foo` + //[nn,ny]~^^ ERROR cannot call non-const fn `::a` in constant functions } fn main() {} diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr index 294545014bf5..b39bf8d8e158 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr @@ -46,5 +46,14 @@ LL | const fn foo(x: &T) { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 6 previous errors +error[E0015]: cannot call non-const fn `::a` in constant functions + --> $DIR/super-traits-fail-3.rs:25:7 + | +LL | x.a(); + | ^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +error: aborting due to 7 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr index 54bb6c5ca441..187cd998d95a 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr @@ -36,5 +36,14 @@ LL | trait Bar: ~const Foo {} | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 5 previous errors +error[E0015]: cannot call non-const fn `::a` in constant functions + --> $DIR/super-traits-fail-3.rs:25:7 + | +LL | x.a(); + | ^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.rs b/tests/ui/traits/const-traits/super-traits-fail-3.rs index a9b08e6edcdc..414337956e21 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.rs +++ b/tests/ui/traits/const-traits/super-traits-fail-3.rs @@ -24,6 +24,7 @@ const fn foo(x: &T) { //[yn,nn]~| ERROR: `~const` can only be applied to `#[const_trait]` x.a(); //[yn]~^ ERROR: the trait bound `T: ~const Foo` is not satisfied + //[nn,ny]~^^ ERROR: cannot call non-const fn `::a` in constant functions } fn main() {} diff --git a/tests/ui/traits/const-traits/trait-default-body-stability.stderr b/tests/ui/traits/const-traits/trait-default-body-stability.stderr index 49fbef9aaa29..5806b6d6fd21 100644 --- a/tests/ui/traits/const-traits/trait-default-body-stability.stderr +++ b/tests/ui/traits/const-traits/trait-default-body-stability.stderr @@ -16,5 +16,22 @@ LL | impl const FromResidual for T { = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error: aborting due to 2 previous errors +error[E0015]: `?` cannot determine the branch of `T` in constant functions + --> $DIR/trait-default-body-stability.rs:45:9 + | +LL | T? + | ^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +error[E0015]: `?` cannot convert from residual of `T` in constant functions + --> $DIR/trait-default-body-stability.rs:45:9 + | +LL | T? + | ^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/typeck/typeck_type_placeholder_item.stderr b/tests/ui/typeck/typeck_type_placeholder_item.stderr index 8a765c21624e..5e32d5c429ef 100644 --- a/tests/ui/typeck/typeck_type_placeholder_item.stderr +++ b/tests/ui/typeck/typeck_type_placeholder_item.stderr @@ -675,10 +675,6 @@ LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); | ^^^^^^^^^^^^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error[E0015]: cannot call non-const fn `, {closure@$DIR/typeck_type_placeholder_item.rs:230:29: 230:32}> as Iterator>::map::` in constants --> $DIR/typeck_type_placeholder_item.rs:230:45 @@ -687,10 +683,6 @@ LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); | ^^^^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - | -LL + #![feature(const_trait_impl)] - | error: aborting due to 74 previous errors From fe425cd54971add38935950a10681d9e81c1ccf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Sat, 26 Oct 2024 09:06:10 +0300 Subject: [PATCH 266/366] Turn Remove dbg into a quick fix for better prioritization --- .../crates/ide-assists/src/handlers/remove_dbg.rs | 2 +- src/tools/rust-analyzer/crates/ide-assists/src/lib.rs | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/remove_dbg.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/remove_dbg.rs index 0e9c463e0245..94274f6d17c3 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/remove_dbg.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/remove_dbg.rs @@ -41,7 +41,7 @@ pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<( macro_calls.into_iter().filter_map(compute_dbg_replacement).collect::>(); acc.add( - AssistId("remove_dbg", AssistKind::Refactor), + AssistId("remove_dbg", AssistKind::QuickFix), "Remove dbg!()", replacements.iter().map(|&(range, _)| range).reduce(|acc, range| acc.cover(range))?, |builder| { diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs index 22620816d504..8aaf5d6fff23 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/lib.rs @@ -301,6 +301,7 @@ mod handlers { inline_call::inline_into_callers, inline_const_as_literal::inline_const_as_literal, inline_local_variable::inline_local_variable, + inline_macro::inline_macro, inline_type_alias::inline_type_alias, inline_type_alias::inline_type_alias_uses, into_to_qualified_from::into_to_qualified_from, @@ -326,6 +327,7 @@ mod handlers { raw_string::add_hash, raw_string::make_usual_string, raw_string::remove_hash, + remove_dbg::remove_dbg, remove_mut::remove_mut, remove_unused_imports::remove_unused_imports, remove_unused_param::remove_unused_param, @@ -381,9 +383,6 @@ mod handlers { generate_getter_or_setter::generate_setter, generate_delegate_methods::generate_delegate_methods, generate_deref::generate_deref, - // - remove_dbg::remove_dbg, - inline_macro::inline_macro, // Are you sure you want to add new assist here, and not to the // sorted list above? ] From 0d653a5866720570b96260ab69b732d241ec346e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 26 Oct 2024 17:37:04 +1100 Subject: [PATCH 267/366] coverage: Add links to LLVM docs for the coverage mapping format --- compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 5b39d078e0d7..8edd788ee36c 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -349,6 +349,7 @@ fn generate_covmap_record<'ll>( llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); llvm::set_section(llglobal, &covmap_section_name); // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. + // llvm::set_alignment(llglobal, Align::EIGHT); cx.add_used_global(llglobal); } @@ -400,6 +401,7 @@ fn generate_covfun_record( llvm::set_visibility(llglobal, llvm::Visibility::Hidden); llvm::set_section(llglobal, cx.covfun_section_name()); // LLVM's coverage mapping format specifies 8-byte alignment for items in this section. + // llvm::set_alignment(llglobal, Align::EIGHT); if cx.target_spec().supports_comdat() { llvm::set_comdat(cx.llmod, llglobal, &func_record_var_name); From 510090f77453980255db60725532ab5ec111ce0b Mon Sep 17 00:00:00 2001 From: MoskalykA <100430077+MoskalykA@users.noreply.github.com> Date: Mon, 7 Oct 2024 06:46:01 +0200 Subject: [PATCH 268/366] Start using `Option::is_none_or` --- .../rust-analyzer/crates/hir-ty/src/consteval.rs | 4 ++-- .../ide-completion/src/completions/mod_.rs | 3 +-- src/tools/rust-analyzer/crates/stdx/src/lib.rs | 16 ---------------- 3 files changed, 3 insertions(+), 20 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs index 9b0044f5c4f3..ba0952f708f9 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs @@ -11,7 +11,7 @@ use hir_def::{ ConstBlockLoc, EnumVariantId, GeneralConstId, StaticId, }; use hir_expand::Lookup; -use stdx::{never, IsNoneOr}; +use stdx::never; use triomphe::Arc; use crate::{ @@ -287,7 +287,7 @@ pub(crate) fn const_eval_discriminant_variant( } let repr = db.enum_data(loc.parent).repr; - let is_signed = IsNoneOr::is_none_or(repr.and_then(|repr| repr.int), |int| int.is_signed()); + let is_signed = Option::is_none_or(repr.and_then(|repr| repr.int), |int| int.is_signed()); let mir_body = db.monomorphized_mir_body( def, diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs index 05e2892fdc85..c0fb981749a3 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs @@ -7,7 +7,6 @@ use ide_db::{ base_db::{SourceRootDatabase, VfsPath}, FxHashSet, RootDatabase, SymbolKind, }; -use stdx::IsNoneOr; use syntax::{ast, AstNode, SyntaxKind, ToSmolStr}; use crate::{context::CompletionContext, CompletionItem, Completions}; @@ -66,7 +65,7 @@ pub(crate) fn complete_mod( .iter() .filter(|&submodule_candidate_file| submodule_candidate_file != module_definition_file) .filter(|&submodule_candidate_file| { - IsNoneOr::is_none_or(module_declaration_file, |it| it != submodule_candidate_file) + Option::is_none_or(module_declaration_file, |it| it != submodule_candidate_file) }) .filter_map(|submodule_file| { let submodule_path = source_root.path_for_file(&submodule_file)?; diff --git a/src/tools/rust-analyzer/crates/stdx/src/lib.rs b/src/tools/rust-analyzer/crates/stdx/src/lib.rs index 76dbd42ff6b2..1c42d198e558 100644 --- a/src/tools/rust-analyzer/crates/stdx/src/lib.rs +++ b/src/tools/rust-analyzer/crates/stdx/src/lib.rs @@ -304,22 +304,6 @@ pub fn slice_tails(this: &[T]) -> impl Iterator { (0..this.len()).map(|i| &this[i..]) } -pub trait IsNoneOr { - type Type; - #[allow(clippy::wrong_self_convention)] - fn is_none_or(self, s: impl FnOnce(Self::Type) -> bool) -> bool; -} -#[allow(unstable_name_collisions)] -impl IsNoneOr for Option { - type Type = T; - fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool { - match self { - Some(v) => f(v), - None => true, - } - } -} - #[cfg(test)] mod tests { use super::*; From f719ee7fc2d56deeef4794a58f5db7df345fe918 Mon Sep 17 00:00:00 2001 From: MoskalykA <100430077+MoskalykA@users.noreply.github.com> Date: Mon, 7 Oct 2024 18:44:24 +0200 Subject: [PATCH 269/366] Use method syntax --- src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs | 2 +- .../rust-analyzer/crates/ide-completion/src/completions/mod_.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs index ba0952f708f9..091cfcd4654c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs @@ -287,7 +287,7 @@ pub(crate) fn const_eval_discriminant_variant( } let repr = db.enum_data(loc.parent).repr; - let is_signed = Option::is_none_or(repr.and_then(|repr| repr.int), |int| int.is_signed()); + let is_signed = repr.and_then(|repr| repr.int).is_none_or(|int| int.is_signed()); let mir_body = db.monomorphized_mir_body( def, diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs index c0fb981749a3..f12f011a6bd3 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs @@ -65,7 +65,7 @@ pub(crate) fn complete_mod( .iter() .filter(|&submodule_candidate_file| submodule_candidate_file != module_definition_file) .filter(|&submodule_candidate_file| { - Option::is_none_or(module_declaration_file, |it| it != submodule_candidate_file) + module_declaration_file.is_none_or(|it| it != submodule_candidate_file) }) .filter_map(|submodule_file| { let submodule_path = source_root.path_for_file(&submodule_file)?; From 56b0299039b6e638d7fface6ea5252770fc77397 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Sat, 26 Oct 2024 09:39:23 +0300 Subject: [PATCH 270/366] Bump MSRV to 1.82 --- src/tools/rust-analyzer/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/Cargo.toml b/src/tools/rust-analyzer/Cargo.toml index 3c2d3a13b191..4e6861d35136 100644 --- a/src/tools/rust-analyzer/Cargo.toml +++ b/src/tools/rust-analyzer/Cargo.toml @@ -4,7 +4,7 @@ exclude = ["crates/proc-macro-srv/proc-macro-test/imp"] resolver = "2" [workspace.package] -rust-version = "1.81" +rust-version = "1.82" edition = "2021" license = "MIT OR Apache-2.0" authors = ["rust-analyzer team"] From 867640e24d9a54b5a4251e2827c83131f4574bb5 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 26 Oct 2024 09:48:39 +0200 Subject: [PATCH 271/366] x86 target features: make pclmulqdq imply sse2 --- compiler/rustc_target/src/target_features.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index e92366d5c5c3..910cafbdf3bd 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -316,7 +316,7 @@ const X86_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("lahfsahf", Unstable(sym::lahfsahf_target_feature), &[]), ("lzcnt", Stable, &[]), ("movbe", Stable, &[]), - ("pclmulqdq", Stable, &[]), + ("pclmulqdq", Stable, &["sse2"]), ("popcnt", Stable, &[]), ("prfchw", Unstable(sym::prfchw_target_feature), &[]), ("rdrand", Stable, &[]), From 144a12acdd673f333b420e946965621be76d3544 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 18:22:03 +1100 Subject: [PATCH 272/366] Add a macro that derives `TryFrom` for fieldless enums --- compiler/rustc_macros/src/lib.rs | 10 ++++ compiler/rustc_macros/src/try_from.rs | 53 ++++++++++++++++++++ tests/ui-fulldeps/try-from-u32/errors.rs | 24 +++++++++ tests/ui-fulldeps/try-from-u32/errors.stderr | 32 ++++++++++++ tests/ui-fulldeps/try-from-u32/hygiene.rs | 32 ++++++++++++ tests/ui-fulldeps/try-from-u32/values.rs | 36 +++++++++++++ 6 files changed, 187 insertions(+) create mode 100644 compiler/rustc_macros/src/try_from.rs create mode 100644 tests/ui-fulldeps/try-from-u32/errors.rs create mode 100644 tests/ui-fulldeps/try-from-u32/errors.stderr create mode 100644 tests/ui-fulldeps/try-from-u32/hygiene.rs create mode 100644 tests/ui-fulldeps/try-from-u32/values.rs diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index f46c795b9565..0df674eb4c90 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -20,6 +20,7 @@ mod lift; mod query; mod serialize; mod symbols; +mod try_from; mod type_foldable; mod type_visitable; @@ -165,3 +166,12 @@ decl_derive!( suggestion_part, applicability)] => diagnostics::subdiagnostic_derive ); + +decl_derive! { + [TryFromU32] => + /// Derives `TryFrom` for the annotated `enum`, which must have no fields. + /// Each variant maps to the value it would produce under an `as u32` cast. + /// + /// The error type is `u32`. + try_from::try_from_u32 +} diff --git a/compiler/rustc_macros/src/try_from.rs b/compiler/rustc_macros/src/try_from.rs new file mode 100644 index 000000000000..fde7c8f62040 --- /dev/null +++ b/compiler/rustc_macros/src/try_from.rs @@ -0,0 +1,53 @@ +use proc_macro2::TokenStream; +use quote::{quote, quote_spanned}; +use syn::Data; +use syn::spanned::Spanned; +use synstructure::Structure; + +pub(crate) fn try_from_u32(s: Structure<'_>) -> TokenStream { + let span_error = |span, message: &str| { + quote_spanned! { span => const _: () = ::core::compile_error!(#message); } + }; + + // Must be applied to an enum type. + if let Some(span) = match &s.ast().data { + Data::Enum(_) => None, + Data::Struct(s) => Some(s.struct_token.span()), + Data::Union(u) => Some(u.union_token.span()), + } { + return span_error(span, "type is not an enum (TryFromU32)"); + } + + // The enum's variants must not have fields. + let variant_field_errors = s + .variants() + .iter() + .filter_map(|v| v.ast().fields.iter().map(|f| f.span()).next()) + .map(|span| span_error(span, "enum variant cannot have fields (TryFromU32)")) + .collect::(); + if !variant_field_errors.is_empty() { + return variant_field_errors; + } + + let ctor = s + .variants() + .iter() + .map(|v| v.construct(|_, _| -> TokenStream { unreachable!() })) + .collect::>(); + s.gen_impl(quote! { + // The surrounding code might have shadowed these identifiers. + use ::core::convert::TryFrom; + use ::core::primitive::u32; + use ::core::result::Result::{self, Ok, Err}; + + gen impl TryFrom for @Self { + type Error = u32; + + #[allow(deprecated)] // Don't warn about deprecated variants. + fn try_from(value: u32) -> Result { + #( if value == const { #ctor as u32 } { return Ok(#ctor) } )* + Err(value) + } + } + }) +} diff --git a/tests/ui-fulldeps/try-from-u32/errors.rs b/tests/ui-fulldeps/try-from-u32/errors.rs new file mode 100644 index 000000000000..0470063312cb --- /dev/null +++ b/tests/ui-fulldeps/try-from-u32/errors.rs @@ -0,0 +1,24 @@ +#![feature(rustc_private)] +//@ edition: 2021 + +// Checks the error messages produced by `#[derive(TryFromU32)]`. + +extern crate rustc_macros; + +use rustc_macros::TryFromU32; + +#[derive(TryFromU32)] +struct MyStruct {} //~ type is not an enum + +#[derive(TryFromU32)] +enum NonTrivial { + A, + B(), + C {}, + D(bool), //~ enum variant cannot have fields + E(bool, bool), //~ enum variant cannot have fields + F { x: bool }, //~ enum variant cannot have fields + G { x: bool, y: bool }, //~ enum variant cannot have fields +} + +fn main() {} diff --git a/tests/ui-fulldeps/try-from-u32/errors.stderr b/tests/ui-fulldeps/try-from-u32/errors.stderr new file mode 100644 index 000000000000..d20567061d7b --- /dev/null +++ b/tests/ui-fulldeps/try-from-u32/errors.stderr @@ -0,0 +1,32 @@ +error: type is not an enum (TryFromU32) + --> $DIR/errors.rs:11:1 + | +LL | struct MyStruct {} + | ^^^^^^ + +error: enum variant cannot have fields (TryFromU32) + --> $DIR/errors.rs:18:7 + | +LL | D(bool), + | ^^^^ + +error: enum variant cannot have fields (TryFromU32) + --> $DIR/errors.rs:19:7 + | +LL | E(bool, bool), + | ^^^^ + +error: enum variant cannot have fields (TryFromU32) + --> $DIR/errors.rs:20:9 + | +LL | F { x: bool }, + | ^ + +error: enum variant cannot have fields (TryFromU32) + --> $DIR/errors.rs:21:9 + | +LL | G { x: bool, y: bool }, + | ^ + +error: aborting due to 5 previous errors + diff --git a/tests/ui-fulldeps/try-from-u32/hygiene.rs b/tests/ui-fulldeps/try-from-u32/hygiene.rs new file mode 100644 index 000000000000..e0655a64a64d --- /dev/null +++ b/tests/ui-fulldeps/try-from-u32/hygiene.rs @@ -0,0 +1,32 @@ +#![feature(rustc_private)] +//@ edition: 2021 +//@ check-pass + +// Checks that the derive macro still works even if the surrounding code has +// shadowed the relevant library types. + +extern crate rustc_macros; + +mod submod { + use rustc_macros::TryFromU32; + + struct Result; + trait TryFrom {} + #[allow(non_camel_case_types)] + struct u32; + struct Ok; + struct Err; + mod core {} + mod std {} + + #[derive(TryFromU32)] + pub(crate) enum MyEnum { + Zero, + One, + } +} + +fn main() { + use submod::MyEnum; + let _: Result = MyEnum::try_from(1u32); +} diff --git a/tests/ui-fulldeps/try-from-u32/values.rs b/tests/ui-fulldeps/try-from-u32/values.rs new file mode 100644 index 000000000000..180a8f2beb75 --- /dev/null +++ b/tests/ui-fulldeps/try-from-u32/values.rs @@ -0,0 +1,36 @@ +#![feature(assert_matches)] +#![feature(rustc_private)] +//@ edition: 2021 +//@ run-pass + +// Checks the values accepted by the `TryFrom` impl produced by `#[derive(TryFromU32)]`. + +extern crate rustc_macros; + +use core::assert_matches::assert_matches; +use rustc_macros::TryFromU32; + +#[derive(TryFromU32, Debug, PartialEq)] +#[repr(u32)] +enum Repr { + Zero, + One(), + Seven = 7, +} + +#[derive(TryFromU32, Debug)] +enum NoRepr { + Zero, + One, +} + +fn main() { + assert_eq!(Repr::try_from(0u32), Ok(Repr::Zero)); + assert_eq!(Repr::try_from(1u32), Ok(Repr::One())); + assert_eq!(Repr::try_from(2u32), Err(2)); + assert_eq!(Repr::try_from(7u32), Ok(Repr::Seven)); + + assert_matches!(NoRepr::try_from(0u32), Ok(NoRepr::Zero)); + assert_matches!(NoRepr::try_from(1u32), Ok(NoRepr::One)); + assert_matches!(NoRepr::try_from(2u32), Err(2)); +} From 983d258be3cbfc72a806c870a69743b6d14e4a33 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 21:40:38 +1100 Subject: [PATCH 273/366] Use safe wrappers `get_linkage` and `set_linkage` --- compiler/rustc_codegen_llvm/src/back/write.rs | 8 +- compiler/rustc_codegen_llvm/src/callee.rs | 4 +- compiler/rustc_codegen_llvm/src/common.rs | 2 +- compiler/rustc_codegen_llvm/src/consts.rs | 78 +++++++++---------- compiler/rustc_codegen_llvm/src/context.rs | 2 +- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 2 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 13 ++-- compiler/rustc_codegen_llvm/src/llvm/mod.rs | 4 + compiler/rustc_codegen_llvm/src/mono_item.rs | 6 +- 9 files changed, 59 insertions(+), 60 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index afdd2b581b86..bf77fc56d08c 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -1043,7 +1043,7 @@ unsafe fn embed_bitcode( let section = bitcode_section_name(cgcx); llvm::LLVMSetSection(llglobal, section.as_ptr().cast()); - llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage); + llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); llvm::LLVMSetGlobalConstant(llglobal, llvm::True); let llconst = common::bytes_in_context(llcx, cmdline.as_bytes()); @@ -1061,7 +1061,7 @@ unsafe fn embed_bitcode( c".llvmcmd" }; llvm::LLVMSetSection(llglobal, section.as_ptr()); - llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage); + llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); } else { // We need custom section flags, so emit module-level inline assembly. let section_flags = if cgcx.is_pe_coff { "n" } else { "e" }; @@ -1096,7 +1096,7 @@ fn create_msvc_imps( let ptr_ty = Type::ptr_llcx(llcx); let globals = base::iter_globals(llmod) .filter(|&val| { - llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage + llvm::get_linkage(val) == llvm::Linkage::ExternalLinkage && llvm::LLVMIsDeclaration(val) == 0 }) .filter_map(|val| { @@ -1115,7 +1115,7 @@ fn create_msvc_imps( for (imp_name, val) in globals { let imp = llvm::LLVMAddGlobal(llmod, ptr_ty, imp_name.as_ptr()); llvm::LLVMSetInitializer(imp, val); - llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage); + llvm::set_linkage(imp, llvm::Linkage::ExternalLinkage); } } diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index a51ef8d7b85f..0e85c7c7d003 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -95,9 +95,9 @@ pub(crate) fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'t // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). - unsafe { - llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); + llvm::set_linkage(llfn, llvm::Linkage::ExternalLinkage); + unsafe { let is_generic = instance.args.non_erasable_generics().next().is_some(); let is_hidden = if is_generic { diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 0ced37b53a84..ff47eb944dd4 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -219,8 +219,8 @@ impl<'ll, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { llvm::LLVMSetInitializer(g, sc); llvm::LLVMSetGlobalConstant(g, True); llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global); - llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage); } + llvm::set_linkage(g, llvm::Linkage::InternalLinkage); (s.to_owned(), g) }) .1; diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 33a85adeb878..0bfd433418ac 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -172,29 +172,27 @@ fn check_and_apply_linkage<'ll, 'tcx>( if let Some(linkage) = attrs.import_linkage { debug!("get_static: sym={} linkage={:?}", sym, linkage); - unsafe { - // Declare a symbol `foo` with the desired linkage. - let g1 = cx.declare_global(sym, cx.type_i8()); - llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage)); + // Declare a symbol `foo` with the desired linkage. + let g1 = cx.declare_global(sym, cx.type_i8()); + llvm::set_linkage(g1, base::linkage_to_llvm(linkage)); - // Declare an internal global `extern_with_linkage_foo` which - // is initialized with the address of `foo`. If `foo` is - // discarded during linking (for example, if `foo` has weak - // linkage and there are no definitions), then - // `extern_with_linkage_foo` will instead be initialized to - // zero. - let mut real_name = "_rust_extern_with_linkage_".to_string(); - real_name.push_str(sym); - let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| { - cx.sess().dcx().emit_fatal(SymbolAlreadyDefined { - span: cx.tcx.def_span(def_id), - symbol_name: sym, - }) - }); - llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage); - llvm::LLVMSetInitializer(g2, g1); - g2 - } + // Declare an internal global `extern_with_linkage_foo` which + // is initialized with the address of `foo`. If `foo` is + // discarded during linking (for example, if `foo` has weak + // linkage and there are no definitions), then + // `extern_with_linkage_foo` will instead be initialized to + // zero. + let mut real_name = "_rust_extern_with_linkage_".to_string(); + real_name.push_str(sym); + let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| { + cx.sess().dcx().emit_fatal(SymbolAlreadyDefined { + span: cx.tcx.def_span(def_id), + symbol_name: sym, + }) + }); + llvm::set_linkage(g2, llvm::Linkage::InternalLinkage); + unsafe { llvm::LLVMSetInitializer(g2, g1) }; + g2 } else if cx.tcx.sess.target.arch == "x86" && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym) { @@ -224,23 +222,21 @@ impl<'ll> CodegenCx<'ll, '_> { align: Align, kind: Option<&str>, ) -> &'ll Value { - unsafe { - let gv = match kind { - Some(kind) if !self.tcx.sess.fewer_names() => { - let name = self.generate_local_symbol_name(kind); - let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| { - bug!("symbol `{}` is already defined", name); - }); - llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage); - gv - } - _ => self.define_private_global(self.val_ty(cv)), - }; - llvm::LLVMSetInitializer(gv, cv); - set_global_alignment(self, gv, align); - llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global); - gv - } + let gv = match kind { + Some(kind) if !self.tcx.sess.fewer_names() => { + let name = self.generate_local_symbol_name(kind); + let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| { + bug!("symbol `{}` is already defined", name); + }); + llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage); + gv + } + _ => self.define_private_global(self.val_ty(cv)), + }; + unsafe { llvm::LLVMSetInitializer(gv, cv) }; + set_global_alignment(self, gv, align); + llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global); + gv } #[instrument(level = "debug", skip(self))] @@ -401,7 +397,7 @@ impl<'ll> CodegenCx<'ll, '_> { let name = llvm::get_value_name(g).to_vec(); llvm::set_value_name(g, b""); - let linkage = llvm::LLVMRustGetLinkage(g); + let linkage = llvm::get_linkage(g); let visibility = llvm::LLVMRustGetVisibility(g); let new_g = llvm::LLVMRustGetOrInsertGlobal( @@ -411,7 +407,7 @@ impl<'ll> CodegenCx<'ll, '_> { val_llty, ); - llvm::LLVMRustSetLinkage(new_g, linkage); + llvm::set_linkage(new_g, linkage); llvm::LLVMRustSetVisibility(new_g, visibility); // The old global has had its name removed but is returned by diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index fb845c0087b1..b5985a6aa1ea 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -605,7 +605,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { unsafe { let g = llvm::LLVMAddGlobal(self.llmod, self.val_ty(array), name.as_ptr()); llvm::LLVMSetInitializer(g, array); - llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage); + llvm::set_linkage(g, llvm::Linkage::AppendingLinkage); llvm::LLVMSetSection(g, c"llvm.metadata".as_ptr()); } } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index f93d3e40b205..7947c9c8c8ef 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -76,7 +76,7 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( llvm::LLVMSetInitializer(section_var, cx.const_bytes(section_contents)); llvm::LLVMSetGlobalConstant(section_var, llvm::True); llvm::LLVMSetUnnamedAddress(section_var, llvm::UnnamedAddr::Global); - llvm::LLVMRustSetLinkage(section_var, llvm::Linkage::LinkOnceODRLinkage); + llvm::set_linkage(section_var, llvm::Linkage::LinkOnceODRLinkage); // This should make sure that the whole section is not larger than // the string it contains. Otherwise we get a warning from GDB. llvm::LLVMSetAlignment(section_var, 1); diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index c9a17c9852db..d04b52576194 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -785,13 +785,12 @@ fn codegen_msvc_try<'ll>( let type_info = bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false); let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info)); - unsafe { - llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage); - if bx.cx.tcx.sess.target.supports_comdat() { - llvm::SetUniqueComdat(bx.llmod, tydesc); - } - llvm::LLVMSetInitializer(tydesc, type_info); + + llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage); + if bx.cx.tcx.sess.target.supports_comdat() { + llvm::SetUniqueComdat(bx.llmod, tydesc); } + unsafe { llvm::LLVMSetInitializer(tydesc, type_info) }; // The flag value of 8 indicates that we are catching the exception by // reference instead of by value. We can't use catch by value because @@ -1064,7 +1063,7 @@ fn gen_fn<'ll, 'tcx>( cx.set_frame_pointer_type(llfn); cx.apply_target_cpu_attr(llfn); // FIXME(eddyb) find a nicer way to do this. - unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) }; + llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage); let llbb = Builder::append_block(cx, llfn, "entry-block"); let bx = Builder::build(cx, llbb); codegen(bx); diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index e837022044ee..9900742d592f 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -232,6 +232,10 @@ pub fn set_global_constant(llglobal: &Value, is_constant: bool) { } } +pub fn get_linkage(llglobal: &Value) -> Linkage { + unsafe { LLVMRustGetLinkage(llglobal) } +} + pub fn set_linkage(llglobal: &Value, linkage: Linkage) { unsafe { LLVMRustSetLinkage(llglobal, linkage); diff --git a/compiler/rustc_codegen_llvm/src/mono_item.rs b/compiler/rustc_codegen_llvm/src/mono_item.rs index bf6ef219873a..cd41e6052288 100644 --- a/compiler/rustc_codegen_llvm/src/mono_item.rs +++ b/compiler/rustc_codegen_llvm/src/mono_item.rs @@ -39,8 +39,8 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name }) }); + llvm::set_linkage(g, base::linkage_to_llvm(linkage)); unsafe { - llvm::LLVMRustSetLinkage(g, base::linkage_to_llvm(linkage)); llvm::LLVMRustSetVisibility(g, base::visibility_to_llvm(visibility)); if self.should_assume_dso_local(g, false) { llvm::LLVMRustSetDSOLocal(g, true); @@ -61,7 +61,7 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty()); let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance)); - unsafe { llvm::LLVMRustSetLinkage(lldecl, base::linkage_to_llvm(linkage)) }; + llvm::set_linkage(lldecl, base::linkage_to_llvm(linkage)); let attrs = self.tcx.codegen_fn_attrs(instance.def_id()); base::set_link_section(lldecl, attrs); if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR) @@ -107,7 +107,7 @@ impl CodegenCx<'_, '_> { llval: &llvm::Value, is_declaration: bool, ) -> bool { - let linkage = unsafe { llvm::LLVMRustGetLinkage(llval) }; + let linkage = llvm::get_linkage(llval); let visibility = unsafe { llvm::LLVMRustGetVisibility(llval) }; if matches!(linkage, llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage) { From b114040afbdf2366390dea7a53b8ca6fbf3f5951 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 19 Oct 2024 12:17:33 +1100 Subject: [PATCH 274/366] Use safe wrappers `get_visibility` and `set_visibility` --- compiler/rustc_codegen_llvm/src/allocator.rs | 17 ++++------------- compiler/rustc_codegen_llvm/src/callee.rs | 2 +- compiler/rustc_codegen_llvm/src/consts.rs | 10 ++++------ compiler/rustc_codegen_llvm/src/llvm/mod.rs | 4 ++++ compiler/rustc_codegen_llvm/src/mono_item.rs | 20 +++++++------------- 5 files changed, 20 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index 89f5305840b9..55ee6dcdf878 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -77,20 +77,14 @@ pub(crate) unsafe fn codegen( // __rust_alloc_error_handler_should_panic let name = OomStrategy::SYMBOL; let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_ptr().cast(), name.len(), i8); - llvm::LLVMRustSetVisibility( - ll_g, - llvm::Visibility::from_generic(tcx.sess.default_visibility()), - ); + llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); let val = tcx.sess.opts.unstable_opts.oom.should_panic(); let llval = llvm::LLVMConstInt(i8, val as u64, False); llvm::LLVMSetInitializer(ll_g, llval); let name = NO_ALLOC_SHIM_IS_UNSTABLE; let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_ptr().cast(), name.len(), i8); - llvm::LLVMRustSetVisibility( - ll_g, - llvm::Visibility::from_generic(tcx.sess.default_visibility()), - ); + llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); let llval = llvm::LLVMConstInt(i8, 0, False); llvm::LLVMSetInitializer(ll_g, llval); } @@ -134,10 +128,7 @@ fn create_wrapper_function( None }; - llvm::LLVMRustSetVisibility( - llfn, - llvm::Visibility::from_generic(tcx.sess.default_visibility()), - ); + llvm::set_visibility(llfn, llvm::Visibility::from_generic(tcx.sess.default_visibility())); if tcx.sess.must_emit_unwind_tables() { let uwtable = @@ -151,7 +142,7 @@ fn create_wrapper_function( // -> ! DIFlagNoReturn attributes::apply_to_llfn(callee, llvm::AttributePlace::Function, &[no_return]); } - llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); + llvm::set_visibility(callee, llvm::Visibility::Hidden); let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, c"entry".as_ptr()); diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 0e85c7c7d003..25037b973750 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -135,7 +135,7 @@ pub(crate) fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'t || !cx.tcx.is_reachable_non_generic(instance_def_id)) }; if is_hidden { - llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden); + llvm::set_visibility(llfn, llvm::Visibility::Hidden); } // MinGW: For backward compatibility we rely on the linker to decide whether it diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 0bfd433418ac..1e3abcfd1af4 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -288,9 +288,7 @@ impl<'ll> CodegenCx<'ll, '_> { let g = self.declare_global(sym, llty); if !self.tcx.is_reachable_non_generic(def_id) { - unsafe { - llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden); - } + llvm::set_visibility(g, llvm::Visibility::Hidden); } g @@ -308,7 +306,7 @@ impl<'ll> CodegenCx<'ll, '_> { llvm::set_thread_local_mode(g, self.tls_model); } - let dso_local = unsafe { self.should_assume_dso_local(g, true) }; + let dso_local = self.should_assume_dso_local(g, true); if dso_local { unsafe { llvm::LLVMRustSetDSOLocal(g, true); @@ -398,7 +396,7 @@ impl<'ll> CodegenCx<'ll, '_> { llvm::set_value_name(g, b""); let linkage = llvm::get_linkage(g); - let visibility = llvm::LLVMRustGetVisibility(g); + let visibility = llvm::get_visibility(g); let new_g = llvm::LLVMRustGetOrInsertGlobal( self.llmod, @@ -408,7 +406,7 @@ impl<'ll> CodegenCx<'ll, '_> { ); llvm::set_linkage(new_g, linkage); - llvm::LLVMRustSetVisibility(new_g, visibility); + llvm::set_visibility(new_g, visibility); // The old global has had its name removed but is returned by // get_static since it is in the instance cache. Provide an diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index 9900742d592f..235b5794b8c5 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -242,6 +242,10 @@ pub fn set_linkage(llglobal: &Value, linkage: Linkage) { } } +pub fn get_visibility(llglobal: &Value) -> Visibility { + unsafe { LLVMRustGetVisibility(llglobal) } +} + pub fn set_visibility(llglobal: &Value, visibility: Visibility) { unsafe { LLVMRustSetVisibility(llglobal, visibility); diff --git a/compiler/rustc_codegen_llvm/src/mono_item.rs b/compiler/rustc_codegen_llvm/src/mono_item.rs index cd41e6052288..ea8857b4739c 100644 --- a/compiler/rustc_codegen_llvm/src/mono_item.rs +++ b/compiler/rustc_codegen_llvm/src/mono_item.rs @@ -40,8 +40,8 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { }); llvm::set_linkage(g, base::linkage_to_llvm(linkage)); + llvm::set_visibility(g, base::visibility_to_llvm(visibility)); unsafe { - llvm::LLVMRustSetVisibility(g, base::visibility_to_llvm(visibility)); if self.should_assume_dso_local(g, false) { llvm::LLVMRustSetDSOLocal(g, true); } @@ -78,21 +78,15 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { && linkage != Linkage::Private && self.tcx.is_compiler_builtins(LOCAL_CRATE) { - unsafe { - llvm::LLVMRustSetVisibility(lldecl, llvm::Visibility::Hidden); - } + llvm::set_visibility(lldecl, llvm::Visibility::Hidden); } else { - unsafe { - llvm::LLVMRustSetVisibility(lldecl, base::visibility_to_llvm(visibility)); - } + llvm::set_visibility(lldecl, base::visibility_to_llvm(visibility)); } debug!("predefine_fn: instance = {:?}", instance); - unsafe { - if self.should_assume_dso_local(lldecl, false) { - llvm::LLVMRustSetDSOLocal(lldecl, true); - } + if self.should_assume_dso_local(lldecl, false) { + unsafe { llvm::LLVMRustSetDSOLocal(lldecl, true) }; } self.instances.borrow_mut().insert(instance, lldecl); @@ -102,13 +96,13 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { impl CodegenCx<'_, '_> { /// Whether a definition or declaration can be assumed to be local to a group of /// libraries that form a single DSO or executable. - pub(crate) unsafe fn should_assume_dso_local( + pub(crate) fn should_assume_dso_local( &self, llval: &llvm::Value, is_declaration: bool, ) -> bool { let linkage = llvm::get_linkage(llval); - let visibility = unsafe { llvm::LLVMRustGetVisibility(llval) }; + let visibility = llvm::get_visibility(llval); if matches!(linkage, llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage) { return true; From ec41e6d1b069316818dc5735e7307f24752004cd Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 23:34:10 +1100 Subject: [PATCH 275/366] Add a wrapper type for raw enum values returned by LLVM --- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 10e55a4f7f65..b295331f8ec3 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1,6 +1,7 @@ #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] +use std::fmt::Debug; use std::marker::PhantomData; use libc::{c_char, c_int, c_uint, c_ulonglong, c_void, size_t}; @@ -19,6 +20,30 @@ pub type Bool = c_uint; pub const True: Bool = 1 as Bool; pub const False: Bool = 0 as Bool; +/// Wrapper for a raw enum value returned from LLVM's C APIs. +/// +/// For C enums returned by LLVM, it's risky to use a Rust enum as the return +/// type, because it would be UB if a later version of LLVM adds a new enum +/// value and returns it. Instead, return this raw wrapper, then convert to the +/// Rust-side enum explicitly. +#[repr(transparent)] +pub struct RawEnum { + value: u32, + /// We don't own or consume a `T`, but we can produce one. + _rust_side_type: PhantomData T>, +} + +impl> RawEnum { + #[track_caller] + pub(crate) fn to_rust(self) -> T + where + T::Error: Debug, + { + // If this fails, the Rust-side enum is out of sync with LLVM's enum. + T::try_from(self.value).expect("enum value returned by LLVM should be known") + } +} + #[derive(Copy, Clone, PartialEq)] #[repr(C)] #[allow(dead_code)] // Variants constructed by C++. From 96993a9b5e971b3e5ecd5cd75bb79bfd62e18d5e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 22:06:29 +1100 Subject: [PATCH 276/366] Use LLVM-C APIs for getting/setting linkage --- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 33 +++++--- compiler/rustc_codegen_llvm/src/llvm/mod.rs | 4 +- .../rustc_llvm/llvm-wrapper/RustWrapper.cpp | 80 ------------------- 3 files changed, 24 insertions(+), 93 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index b295331f8ec3..3258a6c43cc6 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -5,6 +5,7 @@ use std::fmt::Debug; use std::marker::PhantomData; use libc::{c_char, c_int, c_uint, c_ulonglong, c_void, size_t}; +use rustc_macros::TryFromU32; use rustc_target::spec::SymbolVisibility; use super::RustString; @@ -133,21 +134,31 @@ pub enum CallConv { AvrInterrupt = 85, } -/// LLVMRustLinkage -#[derive(Copy, Clone, PartialEq)] +/// Must match the layout of `LLVMLinkage`. +#[derive(Copy, Clone, PartialEq, TryFromU32)] #[repr(C)] pub enum Linkage { ExternalLinkage = 0, AvailableExternallyLinkage = 1, LinkOnceAnyLinkage = 2, LinkOnceODRLinkage = 3, - WeakAnyLinkage = 4, - WeakODRLinkage = 5, - AppendingLinkage = 6, - InternalLinkage = 7, - PrivateLinkage = 8, - ExternalWeakLinkage = 9, - CommonLinkage = 10, + #[deprecated = "marked obsolete by LLVM"] + LinkOnceODRAutoHideLinkage = 4, + WeakAnyLinkage = 5, + WeakODRLinkage = 6, + AppendingLinkage = 7, + InternalLinkage = 8, + PrivateLinkage = 9, + #[deprecated = "marked obsolete by LLVM"] + DLLImportLinkage = 10, + #[deprecated = "marked obsolete by LLVM"] + DLLExportLinkage = 11, + ExternalWeakLinkage = 12, + #[deprecated = "marked obsolete by LLVM"] + GhostLinkage = 13, + CommonLinkage = 14, + LinkerPrivateLinkage = 15, + LinkerPrivateWeakLinkage = 16, } // LLVMRustVisibility @@ -970,6 +981,8 @@ unsafe extern "C" { // Operations on global variables, functions, and aliases (globals) pub fn LLVMIsDeclaration(Global: &Value) -> Bool; + pub fn LLVMGetLinkage(Global: &Value) -> RawEnum; + pub fn LLVMSetLinkage(Global: &Value, RustLinkage: Linkage); pub fn LLVMSetSection(Global: &Value, Section: *const c_char); pub fn LLVMGetAlignment(Global: &Value) -> c_uint; pub fn LLVMSetAlignment(Global: &Value, Bytes: c_uint); @@ -1546,8 +1559,6 @@ unsafe extern "C" { ) -> bool; // Operations on global variables, functions, and aliases (globals) - pub fn LLVMRustGetLinkage(Global: &Value) -> Linkage; - pub fn LLVMRustSetLinkage(Global: &Value, RustLinkage: Linkage); pub fn LLVMRustGetVisibility(Global: &Value) -> Visibility; pub fn LLVMRustSetVisibility(Global: &Value, Viz: Visibility); pub fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool); diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index 235b5794b8c5..3eef9e623614 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -233,12 +233,12 @@ pub fn set_global_constant(llglobal: &Value, is_constant: bool) { } pub fn get_linkage(llglobal: &Value) -> Linkage { - unsafe { LLVMRustGetLinkage(llglobal) } + unsafe { LLVMGetLinkage(llglobal) }.to_rust() } pub fn set_linkage(llglobal: &Value, linkage: Linkage) { unsafe { - LLVMRustSetLinkage(llglobal, linkage); + LLVMSetLinkage(llglobal, linkage); } } diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index cb75888abd76..6c3fa9622f3b 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1619,86 +1619,6 @@ extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B, unwrap(B)->SetInsertPoint(unwrap(BB), Point); } -enum class LLVMRustLinkage { - ExternalLinkage = 0, - AvailableExternallyLinkage = 1, - LinkOnceAnyLinkage = 2, - LinkOnceODRLinkage = 3, - WeakAnyLinkage = 4, - WeakODRLinkage = 5, - AppendingLinkage = 6, - InternalLinkage = 7, - PrivateLinkage = 8, - ExternalWeakLinkage = 9, - CommonLinkage = 10, -}; - -static LLVMRustLinkage toRust(LLVMLinkage Linkage) { - switch (Linkage) { - case LLVMExternalLinkage: - return LLVMRustLinkage::ExternalLinkage; - case LLVMAvailableExternallyLinkage: - return LLVMRustLinkage::AvailableExternallyLinkage; - case LLVMLinkOnceAnyLinkage: - return LLVMRustLinkage::LinkOnceAnyLinkage; - case LLVMLinkOnceODRLinkage: - return LLVMRustLinkage::LinkOnceODRLinkage; - case LLVMWeakAnyLinkage: - return LLVMRustLinkage::WeakAnyLinkage; - case LLVMWeakODRLinkage: - return LLVMRustLinkage::WeakODRLinkage; - case LLVMAppendingLinkage: - return LLVMRustLinkage::AppendingLinkage; - case LLVMInternalLinkage: - return LLVMRustLinkage::InternalLinkage; - case LLVMPrivateLinkage: - return LLVMRustLinkage::PrivateLinkage; - case LLVMExternalWeakLinkage: - return LLVMRustLinkage::ExternalWeakLinkage; - case LLVMCommonLinkage: - return LLVMRustLinkage::CommonLinkage; - default: - report_fatal_error("Invalid LLVMRustLinkage value!"); - } -} - -static LLVMLinkage fromRust(LLVMRustLinkage Linkage) { - switch (Linkage) { - case LLVMRustLinkage::ExternalLinkage: - return LLVMExternalLinkage; - case LLVMRustLinkage::AvailableExternallyLinkage: - return LLVMAvailableExternallyLinkage; - case LLVMRustLinkage::LinkOnceAnyLinkage: - return LLVMLinkOnceAnyLinkage; - case LLVMRustLinkage::LinkOnceODRLinkage: - return LLVMLinkOnceODRLinkage; - case LLVMRustLinkage::WeakAnyLinkage: - return LLVMWeakAnyLinkage; - case LLVMRustLinkage::WeakODRLinkage: - return LLVMWeakODRLinkage; - case LLVMRustLinkage::AppendingLinkage: - return LLVMAppendingLinkage; - case LLVMRustLinkage::InternalLinkage: - return LLVMInternalLinkage; - case LLVMRustLinkage::PrivateLinkage: - return LLVMPrivateLinkage; - case LLVMRustLinkage::ExternalWeakLinkage: - return LLVMExternalWeakLinkage; - case LLVMRustLinkage::CommonLinkage: - return LLVMCommonLinkage; - } - report_fatal_error("Invalid LLVMRustLinkage value!"); -} - -extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) { - return toRust(LLVMGetLinkage(V)); -} - -extern "C" void LLVMRustSetLinkage(LLVMValueRef V, - LLVMRustLinkage RustLinkage) { - LLVMSetLinkage(V, fromRust(RustLinkage)); -} - extern "C" bool LLVMRustConstIntGetZExtValue(LLVMValueRef CV, uint64_t *value) { auto C = unwrap(CV); if (C->getBitWidth() > 64) From f249fdd9621ab1dd65904c46f5db634c2b677da6 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 26 Oct 2024 13:31:24 +0200 Subject: [PATCH 277/366] Add AST unpretty test for unsafe attribute --- tests/ui/unpretty/unsafe-attr.rs | 11 +++++++++++ tests/ui/unpretty/unsafe-attr.stdout | 11 +++++++++++ 2 files changed, 22 insertions(+) create mode 100644 tests/ui/unpretty/unsafe-attr.rs create mode 100644 tests/ui/unpretty/unsafe-attr.stdout diff --git a/tests/ui/unpretty/unsafe-attr.rs b/tests/ui/unpretty/unsafe-attr.rs new file mode 100644 index 000000000000..8734ea86b6d6 --- /dev/null +++ b/tests/ui/unpretty/unsafe-attr.rs @@ -0,0 +1,11 @@ +//@ compile-flags: -Zunpretty=normal +//@ check-pass + +#[no_mangle] +extern "C" fn foo() {} + +#[unsafe(no_mangle)] +extern "C" fn bar() {} + +#[cfg_attr(FALSE, unsafe(no_mangle))] +extern "C" fn zoo() {} diff --git a/tests/ui/unpretty/unsafe-attr.stdout b/tests/ui/unpretty/unsafe-attr.stdout new file mode 100644 index 000000000000..5d1993375240 --- /dev/null +++ b/tests/ui/unpretty/unsafe-attr.stdout @@ -0,0 +1,11 @@ +//@ compile-flags: -Zunpretty=normal +//@ check-pass + +#[no_mangle] +extern "C" fn foo() {} + +#[no_mangle] +extern "C" fn bar() {} + +#[cfg_attr(FALSE, unsafe(no_mangle))] +extern "C" fn zoo() {} From f5b6f938cec70d7b6ef3681217ad4c1d84e597e0 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 26 Oct 2024 13:33:36 +0200 Subject: [PATCH 278/366] Print unsafety of attribute in AST unpretty --- compiler/rustc_ast_pretty/src/pprust/state.rs | 11 +++++++++++ tests/ui/unpretty/unsafe-attr.stdout | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 2cdec2138ad3..1e18f0779f00 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -627,6 +627,13 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) { self.ibox(0); + match item.unsafety { + ast::Safety::Unsafe(_) => { + self.word("unsafe"); + self.popen(); + } + ast::Safety::Default | ast::Safety::Safe(_) => {} + } match &item.args { AttrArgs::Delimited(DelimArgs { dspan: _, delim, tokens }) => self.print_mac_common( Some(MacHeader::Path(&item.path)), @@ -655,6 +662,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere self.word(token_str); } } + match item.unsafety { + ast::Safety::Unsafe(_) => self.pclose(), + ast::Safety::Default | ast::Safety::Safe(_) => {} + } self.end(); } diff --git a/tests/ui/unpretty/unsafe-attr.stdout b/tests/ui/unpretty/unsafe-attr.stdout index 5d1993375240..8734ea86b6d6 100644 --- a/tests/ui/unpretty/unsafe-attr.stdout +++ b/tests/ui/unpretty/unsafe-attr.stdout @@ -4,7 +4,7 @@ #[no_mangle] extern "C" fn foo() {} -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn bar() {} #[cfg_attr(FALSE, unsafe(no_mangle))] From dd3dc103fcad6bfc9dcfadf00f74b034ee9d0b95 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 26 Oct 2024 15:45:05 +0200 Subject: [PATCH 279/366] Fix code HTML items making big blocks if too long --- src/librustdoc/html/static/css/rustdoc.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index 2c17fd54006f..54a1bfb895d5 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -959,7 +959,7 @@ pre, .rustdoc.src .example-wrap, .example-wrap .src-line-numbers { background: var(--table-alt-row-background-color); } -.docblock .stab, .docblock-short .stab { +.docblock .stab, .docblock-short .stab, .docblock p code { display: inline-block; } From ae66380da0d219da669e94b7e591d6853191dd0e Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 26 Oct 2024 15:45:17 +0200 Subject: [PATCH 280/366] Add GUI regression test for code in doc blocks --- tests/rustdoc-gui/check-stab-in-docblock.goml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/rustdoc-gui/check-stab-in-docblock.goml b/tests/rustdoc-gui/check-stab-in-docblock.goml index f25c88690e55..916bea6b0695 100644 --- a/tests/rustdoc-gui/check-stab-in-docblock.goml +++ b/tests/rustdoc-gui/check-stab-in-docblock.goml @@ -1,5 +1,5 @@ // This test checks that using `.stab` attributes in `.docblock` elements doesn't -// create scrollable paragraphs. +// create scrollable paragraphs and is correctly displayed (not making weird blocks). go-to: "file://" + |DOC_PATH| + "/test_docs/index.html" // Needs the text to be display to check for scrollable content. show-text: true @@ -31,3 +31,15 @@ assert-property: ( ".top-doc .docblock p:nth-of-type(3)", {"scrollHeight": |clientHeight|, "scrollWidth": |clientWidth|}, ) + +// Ensure that `` elements in code don't make big blocks. +compare-elements-size-near: ( + "#reexport\.TheStdReexport > code", + ".docblock p span[data-span='1']", + {"height": 1}, +) +compare-elements-size-near: ( + "#reexport\.TheStdReexport > code", + ".docblock p span[data-span='2']", + {"height": 1}, +) From 5f4739157abe8ac9ba3bbc652f6d7893d2a4d4c9 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 26 Oct 2024 13:07:26 +0000 Subject: [PATCH 281/366] Downgrade `untranslatable_diagnostic` and `diagnostic_outside_of_impl` to `allow` See for more context. --- compiler/rustc_lint/src/internal.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 94cc58e49568..71f6214d880c 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -427,7 +427,7 @@ declare_tool_lint! { /// More details on translatable diagnostics can be found /// [here](https://rustc-dev-guide.rust-lang.org/diagnostics/translation.html). pub rustc::UNTRANSLATABLE_DIAGNOSTIC, - Deny, + Allow, "prevent creation of diagnostics which cannot be translated", report_in_external_macro: true } @@ -440,7 +440,7 @@ declare_tool_lint! { /// More details on diagnostics implementations can be found /// [here](https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html). pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL, - Deny, + Allow, "prevent diagnostic creation outside of `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls", report_in_external_macro: true } From 00444bab2602ca487be08d5e2eaa6179833333b8 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 26 Oct 2024 18:44:05 +0200 Subject: [PATCH 282/366] Round negative signed integer towards zero in `iN::midpoint` Instead of towards negative infinity as is currently the case. This done so that the obvious expectations of `midpoint(a, b) == midpoint(b, a)` and `midpoint(-a, -b) == -midpoint(a, b)` are true, which makes the even more obvious implementation `(a + b) / 2` true. https://github.com/rust-lang/rust/issues/110840#issuecomment-2336753931 --- library/core/src/num/int_macros.rs | 38 ---------------- library/core/src/num/mod.rs | 65 ++++++++++++++++++++++++++++ library/core/tests/num/int_macros.rs | 4 +- 3 files changed, 67 insertions(+), 40 deletions(-) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 1d640ea74c4a..01ecaf2710ff 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -3181,44 +3181,6 @@ macro_rules! int_impl { } } - /// Calculates the middle point of `self` and `rhs`. - /// - /// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a - /// sufficiently-large signed integral type. This implies that the result is - /// always rounded towards negative infinity and that no overflow will ever occur. - /// - /// # Examples - /// - /// ``` - /// #![feature(num_midpoint)] - #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")] - #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-1), -1);")] - #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(0), -1);")] - /// ``` - #[unstable(feature = "num_midpoint", issue = "110840")] - #[rustc_const_unstable(feature = "const_num_midpoint", issue = "110840")] - #[rustc_allow_const_fn_unstable(const_num_midpoint)] - #[must_use = "this returns the result of the operation, \ - without modifying the original"] - #[inline] - pub const fn midpoint(self, rhs: Self) -> Self { - const U: $UnsignedT = <$SelfT>::MIN.unsigned_abs(); - - // Map an $SelfT to an $UnsignedT - // ex: i8 [-128; 127] to [0; 255] - const fn map(a: $SelfT) -> $UnsignedT { - (a as $UnsignedT) ^ U - } - - // Map an $UnsignedT to an $SelfT - // ex: u8 [0; 255] to [-128; 127] - const fn demap(a: $UnsignedT) -> $SelfT { - (a ^ U) as $SelfT - } - - demap(<$UnsignedT>::midpoint(map(self), map(rhs))) - } - /// Returns the logarithm of the number with respect to an arbitrary base, /// rounded down. /// diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index f95cfd33ae5d..9a5e211dd608 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -124,6 +124,37 @@ macro_rules! midpoint_impl { ((self ^ rhs) >> 1) + (self & rhs) } }; + ($SelfT:ty, signed) => { + /// Calculates the middle point of `self` and `rhs`. + /// + /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a + /// sufficiently-large signed integral type. This implies that the result is + /// always rounded towards zero and that no overflow will ever occur. + /// + /// # Examples + /// + /// ``` + /// #![feature(num_midpoint)] + #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")] + #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")] + #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")] + #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")] + #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")] + /// ``` + #[unstable(feature = "num_midpoint", issue = "110840")] + #[rustc_const_unstable(feature = "const_num_midpoint", issue = "110840")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub const fn midpoint(self, rhs: Self) -> Self { + // Use the well known branchless algorithm from Hacker's Delight to compute + // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`. + let t = ((self ^ rhs) >> 1) + (self & rhs); + // Except that it fails for integers whose sum is an odd negative number as + // their floor is one less than their average. So we adjust the result. + t + (if t < 0 { 1 } else { 0 } & (self ^ rhs)) + } + }; ($SelfT:ty, $WideT:ty, unsigned) => { /// Calculates the middle point of `self` and `rhs`. /// @@ -147,6 +178,32 @@ macro_rules! midpoint_impl { ((self as $WideT + rhs as $WideT) / 2) as $SelfT } }; + ($SelfT:ty, $WideT:ty, signed) => { + /// Calculates the middle point of `self` and `rhs`. + /// + /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a + /// sufficiently-large signed integral type. This implies that the result is + /// always rounded towards zero and that no overflow will ever occur. + /// + /// # Examples + /// + /// ``` + /// #![feature(num_midpoint)] + #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")] + #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")] + #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")] + #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")] + #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")] + /// ``` + #[unstable(feature = "num_midpoint", issue = "110840")] + #[rustc_const_unstable(feature = "const_num_midpoint", issue = "110840")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub const fn midpoint(self, rhs: $SelfT) -> $SelfT { + ((self as $WideT + rhs as $WideT) / 2) as $SelfT + } + }; } macro_rules! widening_impl { @@ -300,6 +357,7 @@ impl i8 { from_xe_bytes_doc = "", bound_condition = "", } + midpoint_impl! { i8, i16, signed } } impl i16 { @@ -323,6 +381,7 @@ impl i16 { from_xe_bytes_doc = "", bound_condition = "", } + midpoint_impl! { i16, i32, signed } } impl i32 { @@ -346,6 +405,7 @@ impl i32 { from_xe_bytes_doc = "", bound_condition = "", } + midpoint_impl! { i32, i64, signed } } impl i64 { @@ -369,6 +429,7 @@ impl i64 { from_xe_bytes_doc = "", bound_condition = "", } + midpoint_impl! { i64, i128, signed } } impl i128 { @@ -394,6 +455,7 @@ impl i128 { from_xe_bytes_doc = "", bound_condition = "", } + midpoint_impl! { i128, signed } } #[cfg(target_pointer_width = "16")] @@ -418,6 +480,7 @@ impl isize { from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(), bound_condition = " on 16-bit targets", } + midpoint_impl! { isize, i32, signed } } #[cfg(target_pointer_width = "32")] @@ -442,6 +505,7 @@ impl isize { from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(), bound_condition = " on 32-bit targets", } + midpoint_impl! { isize, i64, signed } } #[cfg(target_pointer_width = "64")] @@ -466,6 +530,7 @@ impl isize { from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(), bound_condition = " on 64-bit targets", } + midpoint_impl! { isize, i128, signed } } /// If the 6th bit is set ascii is lower case. diff --git a/library/core/tests/num/int_macros.rs b/library/core/tests/num/int_macros.rs index 1608080d6b60..474d57049ab6 100644 --- a/library/core/tests/num/int_macros.rs +++ b/library/core/tests/num/int_macros.rs @@ -369,8 +369,8 @@ macro_rules! int_module { assert_eq_const_safe!(<$T>::midpoint(3, 4), 3); assert_eq_const_safe!(<$T>::midpoint(4, 3), 3); - assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MAX), -1); - assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MIN), -1); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MAX), 0); + assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MIN), 0); assert_eq_const_safe!(<$T>::midpoint(<$T>::MIN, <$T>::MIN), <$T>::MIN); assert_eq_const_safe!(<$T>::midpoint(<$T>::MAX, <$T>::MAX), <$T>::MAX); From 6ab87f82384d0265b486ba2aa41dcf942bd42c4f Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 26 Oct 2024 17:38:04 +0000 Subject: [PATCH 283/366] Collect item bounds for RPITITs from trait where clauses just like associated types --- .../src/collect/item_bounds.rs | 16 ++------------ .../implied-from-self-where-clause.rs | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 14 deletions(-) create mode 100644 tests/ui/associated-type-bounds/implied-from-self-where-clause.rs diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index b2ad42be6c7f..5c4cecc02f0e 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -367,20 +367,8 @@ pub(super) fn explicit_item_bounds_with_filter( // a projection self type. Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => { let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty(); - let item_ty = Ty::new_projection_from_args( - tcx, - def_id.to_def_id(), - ty::GenericArgs::identity_for_item(tcx, def_id), - ); - let bounds = opaque_type_bounds( - tcx, - opaque_def_id.expect_local(), - opaque_ty.bounds, - item_ty, - opaque_ty.span, - filter, - ); - assert_only_contains_predicates_from(filter, bounds, item_ty); + let bounds = + associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter); return ty::EarlyBinder::bind(bounds); } Some(ty::ImplTraitInTraitData::Impl { .. }) => span_bug!( diff --git a/tests/ui/associated-type-bounds/implied-from-self-where-clause.rs b/tests/ui/associated-type-bounds/implied-from-self-where-clause.rs new file mode 100644 index 000000000000..38f556969140 --- /dev/null +++ b/tests/ui/associated-type-bounds/implied-from-self-where-clause.rs @@ -0,0 +1,21 @@ +// Make sure that, like associated type where clauses on traits, we gather item +// bounds for RPITITs from RTN where clauses. + +//@ check-pass + +#![feature(return_type_notation)] + +trait Foo +where + Self::method(..): Send, +{ + fn method() -> impl Sized; +} + +fn is_send(_: impl Send) {} + +fn test() { + is_send(T::method()); +} + +fn main() {} From 88f4425dd20d5724d00eafc9c4397f521cd8e4bb Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 26 Oct 2024 20:40:59 +0200 Subject: [PATCH 284/366] Update GUI test --- tests/rustdoc-gui/docblock-big-code-mobile.goml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/rustdoc-gui/docblock-big-code-mobile.goml b/tests/rustdoc-gui/docblock-big-code-mobile.goml index 6fc6834768eb..71e08e2c7e26 100644 --- a/tests/rustdoc-gui/docblock-big-code-mobile.goml +++ b/tests/rustdoc-gui/docblock-big-code-mobile.goml @@ -1,13 +1,15 @@ // If we have a long ``, we need to ensure that it'll be fully displayed on mobile, meaning // that it'll be on two lines. + emulate: "iPhone 8" // it has the following size: (375, 667) go-to: "file://" + |DOC_PATH| + "/test_docs/long_code_block/index.html" -// We now check that the block is on two lines: show-text: true // We need to enable text draw to be able to have the "real" size + +// We now check that the block is on two lines: // Little explanations for this test: if the text wasn't displayed on two lines, it would take -// around 20px (which is the font size). -assert-property: (".docblock p > code", {"offsetHeight": "44"}) +// around 24px (which is the font size). +assert-size: (".docblock p > code", {"height": 48}) // Same check, but where the long code block is also a link go-to: "file://" + |DOC_PATH| + "/test_docs/long_code_block_link/index.html" -assert-property: (".docblock p > a > code", {"offsetHeight": "44"}) +assert-size: (".docblock p > a > code", {"height": 48}) From b93a2dd0efeb00238543fd199ebdb8bb0f96bad7 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 26 Oct 2024 18:51:15 +0300 Subject: [PATCH 285/366] expand: Stop using artificial `ast::Item` for macros loaded from metadata --- compiler/rustc_expand/src/mbe/macro_rules.rs | 98 ++++++++----------- compiler/rustc_metadata/src/creader.rs | 4 +- .../src/rmeta/decoder/cstore_impl.rs | 28 ++---- .../rustc_resolve/src/build_reduced_graph.rs | 4 +- compiler/rustc_resolve/src/def_collector.rs | 6 +- compiler/rustc_resolve/src/macros.rs | 40 +++++--- src/librustdoc/clean/inline.rs | 26 ++--- src/librustdoc/html/format.rs | 8 +- 8 files changed, 94 insertions(+), 120 deletions(-) diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index f40f99b6ea12..fcc90c3ce0dd 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -3,12 +3,11 @@ use std::collections::hash_map::Entry; use std::{mem, slice}; use ast::token::IdentIsRaw; -use rustc_ast as ast; use rustc_ast::token::NtPatKind::*; use rustc_ast::token::TokenKind::*; use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; -use rustc_ast::{DUMMY_NODE_ID, NodeId}; +use rustc_ast::{self as ast, DUMMY_NODE_ID, NodeId}; use rustc_ast_pretty::pprust; use rustc_attr::{self as attr, TransparencyError}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; @@ -370,34 +369,32 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( pub fn compile_declarative_macro( sess: &Session, features: &Features, - def: &ast::Item, + macro_def: &ast::MacroDef, + ident: Ident, + attrs: &[ast::Attribute], + span: Span, + node_id: NodeId, edition: Edition, ) -> (SyntaxExtension, Vec<(usize, Span)>) { - debug!("compile_declarative_macro: {:?}", def); let mk_syn_ext = |expander| { SyntaxExtension::new( sess, features, SyntaxExtensionKind::LegacyBang(expander), - def.span, + span, Vec::new(), edition, - def.ident.name, - &def.attrs, - def.id != DUMMY_NODE_ID, + ident.name, + attrs, + node_id != DUMMY_NODE_ID, ) }; let dummy_syn_ext = |guar| (mk_syn_ext(Box::new(DummyExpander(guar))), Vec::new()); let dcx = sess.dcx(); - let lhs_nm = Ident::new(sym::lhs, def.span); - let rhs_nm = Ident::new(sym::rhs, def.span); + let lhs_nm = Ident::new(sym::lhs, span); + let rhs_nm = Ident::new(sym::rhs, span); let tt_spec = Some(NonterminalKind::TT); - - let macro_def = match &def.kind { - ast::ItemKind::MacroDef(def) => def, - _ => unreachable!(), - }; let macro_rules = macro_def.macro_rules; // Parse the macro_rules! invocation @@ -410,25 +407,22 @@ pub fn compile_declarative_macro( let argument_gram = vec![ mbe::TokenTree::Sequence(DelimSpan::dummy(), mbe::SequenceRepetition { tts: vec![ - mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec), - mbe::TokenTree::token(token::FatArrow, def.span), - mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec), + mbe::TokenTree::MetaVarDecl(span, lhs_nm, tt_spec), + mbe::TokenTree::token(token::FatArrow, span), + mbe::TokenTree::MetaVarDecl(span, rhs_nm, tt_spec), ], - separator: Some(Token::new( - if macro_rules { token::Semi } else { token::Comma }, - def.span, - )), - kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span), + separator: Some(Token::new(if macro_rules { token::Semi } else { token::Comma }, span)), + kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, span), num_captures: 2, }), // to phase into semicolon-termination instead of semicolon-separation mbe::TokenTree::Sequence(DelimSpan::dummy(), mbe::SequenceRepetition { tts: vec![mbe::TokenTree::token( if macro_rules { token::Semi } else { token::Comma }, - def.span, + span, )], separator: None, - kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span), + kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, span), num_captures: 0, }), ]; @@ -460,7 +454,7 @@ pub fn compile_declarative_macro( }; let s = parse_failure_msg(&token, track.get_expected_token()); - let sp = token.span.substitute_dummy(def.span); + let sp = token.span.substitute_dummy(span); let mut err = sess.dcx().struct_span_err(sp, s); err.span_label(sp, msg); annotate_doc_comment(&mut err, sess.source_map(), sp); @@ -468,7 +462,7 @@ pub fn compile_declarative_macro( return dummy_syn_ext(guar); } Error(sp, msg) => { - let guar = sess.dcx().span_err(sp.substitute_dummy(def.span), msg); + let guar = sess.dcx().span_err(sp.substitute_dummy(span), msg); return dummy_syn_ext(guar); } ErrorReported(guar) => { @@ -489,7 +483,7 @@ pub fn compile_declarative_macro( &TokenStream::new(vec![tt.clone()]), true, sess, - def.id, + node_id, features, edition, ) @@ -497,13 +491,13 @@ pub fn compile_declarative_macro( .unwrap(); // We don't handle errors here, the driver will abort // after parsing/expansion. We can report every error in every macro this way. - check_emission(check_lhs_nt_follows(sess, def, &tt)); + check_emission(check_lhs_nt_follows(sess, node_id, &tt)); return tt; } - sess.dcx().span_bug(def.span, "wrong-structured lhs") + sess.dcx().span_bug(span, "wrong-structured lhs") }) .collect::>(), - _ => sess.dcx().span_bug(def.span, "wrong-structured lhs"), + _ => sess.dcx().span_bug(span, "wrong-structured lhs"), }; let rhses = match &argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] { @@ -515,17 +509,17 @@ pub fn compile_declarative_macro( &TokenStream::new(vec![tt.clone()]), false, sess, - def.id, + node_id, features, edition, ) .pop() .unwrap(); } - sess.dcx().span_bug(def.span, "wrong-structured rhs") + sess.dcx().span_bug(span, "wrong-structured rhs") }) .collect::>(), - _ => sess.dcx().span_bug(def.span, "wrong-structured rhs"), + _ => sess.dcx().span_bug(span, "wrong-structured rhs"), }; for rhs in &rhses { @@ -537,15 +531,9 @@ pub fn compile_declarative_macro( check_emission(check_lhs_no_empty_seq(sess, slice::from_ref(lhs))); } - check_emission(macro_check::check_meta_variables( - &sess.psess, - def.id, - def.span, - &lhses, - &rhses, - )); + check_emission(macro_check::check_meta_variables(&sess.psess, node_id, span, &lhses, &rhses)); - let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules); + let (transparency, transparency_error) = attr::find_transparency(attrs, macro_rules); match transparency_error { Some(TransparencyError::UnknownTransparency(value, span)) => { dcx.span_err(span, format!("unknown macro transparency: `{value}`")); @@ -564,7 +552,7 @@ pub fn compile_declarative_macro( // Compute the spans of the macro rules for unused rule linting. // Also, we are only interested in non-foreign macros. - let rule_spans = if def.id != DUMMY_NODE_ID { + let rule_spans = if node_id != DUMMY_NODE_ID { lhses .iter() .zip(rhses.iter()) @@ -590,15 +578,15 @@ pub fn compile_declarative_macro( mbe::TokenTree::Delimited(.., delimited) => { mbe::macro_parser::compute_locs(&delimited.tts) } - _ => sess.dcx().span_bug(def.span, "malformed macro lhs"), + _ => sess.dcx().span_bug(span, "malformed macro lhs"), } }) .collect(); let expander = Box::new(MacroRulesMacroExpander { - name: def.ident, - span: def.span, - node_id: def.id, + name: ident, + span, + node_id, transparency, lhses, rhses, @@ -608,13 +596,13 @@ pub fn compile_declarative_macro( fn check_lhs_nt_follows( sess: &Session, - def: &ast::Item, + node_id: NodeId, lhs: &mbe::TokenTree, ) -> Result<(), ErrorGuaranteed> { // lhs is going to be like TokenTree::Delimited(...), where the // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens. if let mbe::TokenTree::Delimited(.., delimited) = lhs { - check_matcher(sess, def, &delimited.tts) + check_matcher(sess, node_id, &delimited.tts) } else { let msg = "invalid macro matcher; matchers must be contained in balanced delimiters"; Err(sess.dcx().span_err(lhs.span(), msg)) @@ -686,12 +674,12 @@ fn check_rhs(sess: &Session, rhs: &mbe::TokenTree) -> Result<(), ErrorGuaranteed fn check_matcher( sess: &Session, - def: &ast::Item, + node_id: NodeId, matcher: &[mbe::TokenTree], ) -> Result<(), ErrorGuaranteed> { let first_sets = FirstSets::new(matcher); let empty_suffix = TokenSet::empty(); - check_matcher_core(sess, def, &first_sets, matcher, &empty_suffix)?; + check_matcher_core(sess, node_id, &first_sets, matcher, &empty_suffix)?; Ok(()) } @@ -1028,7 +1016,7 @@ impl<'tt> TokenSet<'tt> { // see `FirstSets::new`. fn check_matcher_core<'tt>( sess: &Session, - def: &ast::Item, + node_id: NodeId, first_sets: &FirstSets<'tt>, matcher: &'tt [mbe::TokenTree], follow: &TokenSet<'tt>, @@ -1082,7 +1070,7 @@ fn check_matcher_core<'tt>( token::CloseDelim(d.delim), span.close, )); - check_matcher_core(sess, def, first_sets, &d.tts, &my_suffix)?; + check_matcher_core(sess, node_id, first_sets, &d.tts, &my_suffix)?; // don't track non NT tokens last.replace_with_irrelevant(); @@ -1114,7 +1102,7 @@ fn check_matcher_core<'tt>( // At this point, `suffix_first` is built, and // `my_suffix` is some TokenSet that we can use // for checking the interior of `seq_rep`. - let next = check_matcher_core(sess, def, first_sets, &seq_rep.tts, my_suffix)?; + let next = check_matcher_core(sess, node_id, first_sets, &seq_rep.tts, my_suffix)?; if next.maybe_empty { last.add_all(&next); } else { @@ -1144,7 +1132,7 @@ fn check_matcher_core<'tt>( // macro. (See #86567.) // Macros defined in the current crate have a real node id, // whereas macros from an external crate have a dummy id. - if def.id != DUMMY_NODE_ID + if node_id != DUMMY_NODE_ID && matches!(kind, NonterminalKind::Pat(PatParam { inferred: true })) && matches!( next_token, diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 8adec7554a83..16623915c401 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -28,7 +28,7 @@ use rustc_session::lint::{self, BuiltinLintDiag}; use rustc_session::output::validate_crate_name; use rustc_session::search_paths::PathKind; use rustc_span::edition::Edition; -use rustc_span::symbol::{Symbol, sym}; +use rustc_span::symbol::{Ident, Symbol, sym}; use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::{PanicStrategy, Target, TargetTriple}; use tracing::{debug, info, trace}; @@ -97,7 +97,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } pub enum LoadedMacro { - MacroDef(ast::Item, Edition), + MacroDef { def: MacroDef, ident: Ident, attrs: AttrVec, span: Span, edition: Edition }, ProcMacro(SyntaxExtension), } diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 71c7231a7882..926eb4f6210b 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -1,7 +1,6 @@ use std::any::Any; use std::mem; -use rustc_ast as ast; use rustc_attr::Deprecation; use rustc_data_structures::sync::Lrc; use rustc_hir::def::{CtorKind, DefKind, Res}; @@ -592,27 +591,16 @@ impl CStore { let data = self.get_crate_data(id.krate); if data.root.is_proc_macro_crate() { - return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, tcx)); - } - - let span = data.get_span(id.index, sess); - - LoadedMacro::MacroDef( - ast::Item { + LoadedMacro::ProcMacro(data.load_proc_macro(id.index, tcx)) + } else { + LoadedMacro::MacroDef { + def: data.get_macro(id.index, sess), ident: data.item_ident(id.index, sess), - id: ast::DUMMY_NODE_ID, - span, attrs: data.get_item_attrs(id.index, sess).collect(), - kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)), - vis: ast::Visibility { - span: span.shrink_to_lo(), - kind: ast::VisibilityKind::Inherited, - tokens: None, - }, - tokens: None, - }, - data.root.edition, - ) + span: data.get_span(id.index, sess), + edition: data.root.edition, + } + } } pub fn def_span_untracked(&self, def_id: DefId, sess: &Session) -> Span { diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 031ffaed808b..bdf940a04b56 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -177,7 +177,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let loaded_macro = self.cstore().load_macro_untracked(def_id, self.tcx); let macro_data = match loaded_macro { - LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition), + LoadedMacro::MacroDef { def, ident, attrs, span, edition } => { + self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition) + } LoadedMacro::ProcMacro(ext) => MacroData::new(Lrc::new(ext)), }; diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 0047f2c4b51e..a825458dc894 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -199,8 +199,10 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { }, ItemKind::Const(..) => DefKind::Const, ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn, - ItemKind::MacroDef(..) => { - let macro_data = self.resolver.compile_macro(i, self.resolver.tcx.sess.edition()); + ItemKind::MacroDef(def) => { + let edition = self.resolver.tcx.sess.edition(); + let macro_data = + self.resolver.compile_macro(def, i.ident, &i.attrs, i.span, i.id, edition); let macro_kind = macro_data.ext.macro_kind(); opt_macro_data = Some(macro_data); DefKind::Macro(macro_kind) diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index a9ebffea8a10..1dc27776cb0f 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -1122,9 +1122,25 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { /// Compile the macro into a `SyntaxExtension` and its rule spans. /// /// Possibly replace its expander to a pre-defined one for built-in macros. - pub(crate) fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> MacroData { - let (mut ext, mut rule_spans) = - compile_declarative_macro(self.tcx.sess, self.tcx.features(), item, edition); + pub(crate) fn compile_macro( + &mut self, + macro_def: &ast::MacroDef, + ident: Ident, + attrs: &[ast::Attribute], + span: Span, + node_id: NodeId, + edition: Edition, + ) -> MacroData { + let (mut ext, mut rule_spans) = compile_declarative_macro( + self.tcx.sess, + self.tcx.features(), + macro_def, + ident, + attrs, + span, + node_id, + edition, + ); if let Some(builtin_name) = ext.builtin_name { // The macro was marked with `#[rustc_builtin_macro]`. @@ -1132,28 +1148,22 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // The macro is a built-in, replace its expander function // while still taking everything else from the source code. // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'. - match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) { + match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(span)) { BuiltinMacroState::NotYetSeen(builtin_ext) => { ext.kind = builtin_ext; rule_spans = Vec::new(); } - BuiltinMacroState::AlreadySeen(span) => { - self.dcx().emit_err(errors::AttemptToDefineBuiltinMacroTwice { - span: item.span, - note_span: span, - }); + BuiltinMacroState::AlreadySeen(note_span) => { + self.dcx() + .emit_err(errors::AttemptToDefineBuiltinMacroTwice { span, note_span }); } } } else { - self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { - span: item.span, - ident: item.ident, - }); + self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident }); } } - let ItemKind::MacroDef(def) = &item.kind else { unreachable!() }; - MacroData { ext: Lrc::new(ext), rule_spans, macro_rules: def.macro_rules } + MacroData { ext: Lrc::new(ext), rule_spans, macro_rules: macro_def.macro_rules } } fn path_accessible( diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index e7f921eef7fc..97529e420e3b 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -248,9 +248,7 @@ pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemT // Check to see if it is a macro 2.0 or built-in macro if matches!( CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.tcx), - LoadedMacro::MacroDef(def, _) - if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) - if !ast_def.macro_rules) + LoadedMacro::MacroDef { def, .. } if !def.macro_rules ) { once(crate_name).chain(relative).collect() } else { @@ -747,24 +745,12 @@ fn build_macro( is_doc_hidden: bool, ) -> clean::ItemKind { match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.tcx) { - LoadedMacro::MacroDef(item_def, _) => match macro_kind { + LoadedMacro::MacroDef { def, .. } => match macro_kind { MacroKind::Bang => { - if let ast::ItemKind::MacroDef(ref def) = item_def.kind { - let vis = - cx.tcx.visibility(import_def_id.map(|d| d.to_def_id()).unwrap_or(def_id)); - clean::MacroItem(clean::Macro { - source: utils::display_macro_source( - cx, - name, - def, - def_id, - vis, - is_doc_hidden, - ), - }) - } else { - unreachable!() - } + let vis = cx.tcx.visibility(import_def_id.map(|d| d.to_def_id()).unwrap_or(def_id)); + clean::MacroItem(clean::Macro { + source: utils::display_macro_source(cx, name, &def, def_id, vis, is_doc_hidden), + }) } MacroKind::Derive | MacroKind::Attr => { clean::ProcMacroItem(clean::ProcMacro { kind: macro_kind, helpers: Vec::new() }) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index ea2f930ab837..8e8e5c6ade8c 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -16,6 +16,7 @@ use itertools::Itertools; use rustc_attr::{ConstStability, StabilityLevel, StableSince}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashSet; +use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_metadata::creader::{CStore, LoadedMacro}; @@ -25,7 +26,6 @@ use rustc_span::symbol::kw; use rustc_span::{Symbol, sym}; use rustc_target::spec::abi::Abi; use tracing::{debug, trace}; -use {rustc_ast as ast, rustc_hir as hir}; use super::url_parts_builder::{UrlPartsBuilder, estimate_item_path_byte_length}; use crate::clean::types::ExternalLocation; @@ -554,10 +554,8 @@ fn generate_macro_def_id_path( // Check to see if it is a macro 2.0 or built-in macro. // More information in . let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx) { - LoadedMacro::MacroDef(def, _) => { - // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0. - matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules) - } + // If `def.macro_rules` is `true`, then it's not a macro 2.0. + LoadedMacro::MacroDef { def, .. } => !def.macro_rules, _ => false, }; From 74b9de4af2c1200a82bfa9193423cc7889ddc924 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 26 Oct 2024 22:08:34 +0200 Subject: [PATCH 286/366] Add test for all midpoint expectations --- library/core/tests/num/midpoint.rs | 54 ++++++++++++++++++++++++++++++ library/core/tests/num/mod.rs | 1 + 2 files changed, 55 insertions(+) create mode 100644 library/core/tests/num/midpoint.rs diff --git a/library/core/tests/num/midpoint.rs b/library/core/tests/num/midpoint.rs new file mode 100644 index 000000000000..71e980067842 --- /dev/null +++ b/library/core/tests/num/midpoint.rs @@ -0,0 +1,54 @@ +//! Test the following expectations: +//! - midpoint(a, b) == (a + b) / 2 +//! - midpoint(a, b) == midpoint(b, a) +//! - midpoint(-a, -b) == -midpoint(a, b) + +#[test] +#[cfg(not(miri))] +fn midpoint_obvious_impl_i8() { + for a in i8::MIN..=i8::MAX { + for b in i8::MIN..=i8::MAX { + assert_eq!(i8::midpoint(a, b), ((a as i16 + b as i16) / 2) as i8); + } + } +} + +#[test] +#[cfg(not(miri))] +fn midpoint_obvious_impl_u8() { + for a in u8::MIN..=u8::MAX { + for b in u8::MIN..=u8::MAX { + assert_eq!(u8::midpoint(a, b), ((a as u16 + b as u16) / 2) as u8); + } + } +} + +#[test] +#[cfg(not(miri))] +fn midpoint_order_expectation_i8() { + for a in i8::MIN..=i8::MAX { + for b in i8::MIN..=i8::MAX { + assert_eq!(i8::midpoint(a, b), i8::midpoint(b, a)); + } + } +} + +#[test] +#[cfg(not(miri))] +fn midpoint_order_expectation_u8() { + for a in u8::MIN..=u8::MAX { + for b in u8::MIN..=u8::MAX { + assert_eq!(u8::midpoint(a, b), u8::midpoint(b, a)); + } + } +} + +#[test] +#[cfg(not(miri))] +fn midpoint_negative_expectation() { + for a in 0..=i8::MAX { + for b in 0..=i8::MAX { + assert_eq!(i8::midpoint(-a, -b), -i8::midpoint(a, b)); + } + } +} diff --git a/library/core/tests/num/mod.rs b/library/core/tests/num/mod.rs index 6da9b9a13293..0add9a01e682 100644 --- a/library/core/tests/num/mod.rs +++ b/library/core/tests/num/mod.rs @@ -28,6 +28,7 @@ mod dec2flt; mod flt2dec; mod int_log; mod int_sqrt; +mod midpoint; mod ops; mod wrapping; From bd95695b947291b2aac349a6f4587a6cee213e25 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 26 Oct 2024 20:54:38 +0000 Subject: [PATCH 287/366] Pass constness with span into lower_poly_trait_ref --- .../src/hir_ty_lowering/bounds.rs | 7 -- .../src/hir_ty_lowering/dyn_compatibility.rs | 2 +- .../src/hir_ty_lowering/mod.rs | 16 ++-- .../ui/consts/const-block-const-bound.stderr | 8 +- tests/ui/consts/fn_trait_refs.stderr | 92 +++++++++---------- .../unstable-const-fn-in-libcore.stderr | 8 +- .../impl-trait/normalize-tait-in-const.stderr | 16 ++-- .../ui/specialization/const_trait_impl.stderr | 24 ++--- .../ui/traits/const-traits/assoc-type.stderr | 2 +- .../const-traits/call-generic-in-impl.stderr | 8 +- .../call-generic-method-chain.stderr | 16 ++-- .../call-generic-method-dup-bound.stderr | 16 ++-- .../call-generic-method-pass.stderr | 8 +- .../const-bounds-non-const-trait.stderr | 12 +-- .../const-closure-parse-not-item.stderr | 8 +- .../const-closure-trait-method-fail.stderr | 8 +- .../const-closure-trait-method.stderr | 8 +- .../traits/const-traits/const-closures.stderr | 32 +++---- .../const-traits/const-drop-bound.stderr | 24 ++--- .../const-traits/const-drop-fail-2.stderr | 8 +- .../const-drop-fail.precise.stderr | 8 +- .../const-traits/const-drop-fail.stock.stderr | 8 +- .../const-traits/const-drop.precise.stderr | 8 +- .../const-traits/const-drop.stock.stderr | 8 +- .../derive-const-with-params.stderr | 6 -- .../ice-112822-expected-type-for-param.stderr | 8 +- .../effects/spec-effectvar-ice.stderr | 4 +- .../ice-123664-unexpected-bound-var.stderr | 8 +- .../ui/traits/const-traits/issue-92111.stderr | 8 +- .../item-bound-entailment-fails.stderr | 4 +- .../non-const-op-in-closure-in-const.stderr | 8 +- .../predicate-entailment-fails.stderr | 12 +-- .../super-traits-fail-2.nn.stderr | 12 +-- .../super-traits-fail-2.ny.stderr | 20 ++-- .../super-traits-fail-3.nn.stderr | 20 ++-- .../super-traits-fail-3.ny.stderr | 20 ++-- .../super-traits-fail-3.yn.stderr | 8 +- .../unsatisfied-const-trait-bound.stderr | 2 +- 38 files changed, 241 insertions(+), 254 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index c902e85c2673..a5709089db68 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -168,13 +168,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { match hir_bound { hir::GenericBound::Trait(poly_trait_ref) => { let hir::TraitBoundModifiers { constness, polarity } = poly_trait_ref.modifiers; - // FIXME: We could pass these directly into `lower_poly_trait_ref` - // so that we could use these spans in diagnostics within that function... - let constness = match constness { - hir::BoundConstness::Never => None, - hir::BoundConstness::Always(_) => Some(ty::BoundConstness::Const), - hir::BoundConstness::Maybe(_) => Some(ty::BoundConstness::ConstIfConst), - }; let polarity = match polarity { rustc_ast::BoundPolarity::Positive => ty::PredicatePolarity::Positive, rustc_ast::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index 890e8fa99e65..f2ee4b0ccd41 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -50,7 +50,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } = self.lower_poly_trait_ref( &trait_bound.trait_ref, trait_bound.span, - None, + hir::BoundConstness::Never, ty::PredicatePolarity::Positive, dummy_self, &mut bounds, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 863c077a9e03..4b7eb0b00bba 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -658,7 +658,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { &self, trait_ref: &hir::TraitRef<'tcx>, span: Span, - constness: Option, + constness: hir::BoundConstness, polarity: ty::PredicatePolarity, self_ty: Ty<'tcx>, bounds: &mut Bounds<'tcx>, @@ -681,11 +681,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Some(self_ty), ); - if let Some(constness) = constness + if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness && !self.tcx().is_const_trait(trait_def_id) { self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait { - span: trait_ref.path.span, + span, modifier: constness.as_str(), }); } @@ -708,7 +708,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { bounds.push_trait_bound(tcx, poly_trait_ref, span, polarity); match constness { - Some(ty::BoundConstness::Const) => { + hir::BoundConstness::Always(span) => { if polarity == ty::PredicatePolarity::Positive { bounds.push_const_bound( tcx, @@ -718,13 +718,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); } } - Some(ty::BoundConstness::ConstIfConst) => { + hir::BoundConstness::Maybe(_) => { // We don't emit a const bound here, since that would mean that we // unconditionally need to prove a `HostEffect` predicate, even when // the predicates are being instantiated in a non-const context. This // is instead handled in the `const_conditions` query. } - None => {} + hir::BoundConstness::Never => {} } } // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert @@ -734,12 +734,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // here because we only call this on self bounds, and deal with the recursive case // in `lower_assoc_item_constraint`. PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => match constness { - Some(ty::BoundConstness::ConstIfConst) => { + hir::BoundConstness::Maybe(span) => { if polarity == ty::PredicatePolarity::Positive { bounds.push_const_bound(tcx, poly_trait_ref, ty::HostPolarity::Maybe, span); } } - None | Some(ty::BoundConstness::Const) => {} + hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {} }, } diff --git a/tests/ui/consts/const-block-const-bound.stderr b/tests/ui/consts/const-block-const-bound.stderr index 8cb91d78f6ca..5e24959146b8 100644 --- a/tests/ui/consts/const-block-const-bound.stderr +++ b/tests/ui/consts/const-block-const-bound.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-block-const-bound.rs:8:22 + --> $DIR/const-block-const-bound.rs:8:15 | LL | const fn f(x: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-block-const-bound.rs:8:22 + --> $DIR/const-block-const-bound.rs:8:15 | LL | const fn f(x: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/consts/fn_trait_refs.stderr b/tests/ui/consts/fn_trait_refs.stderr index 82b2b87c4a5a..a686bc23c0f4 100644 --- a/tests/ui/consts/fn_trait_refs.stderr +++ b/tests/ui/consts/fn_trait_refs.stderr @@ -11,168 +11,168 @@ LL | #![feature(const_cmp)] | ^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:13:15 + --> $DIR/fn_trait_refs.rs:13:8 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:13:31 + --> $DIR/fn_trait_refs.rs:13:24 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:13:15 + --> $DIR/fn_trait_refs.rs:13:8 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:13:15 + --> $DIR/fn_trait_refs.rs:13:8 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:13:31 + --> $DIR/fn_trait_refs.rs:13:24 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:20:15 + --> $DIR/fn_trait_refs.rs:20:8 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:20:34 + --> $DIR/fn_trait_refs.rs:20:27 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:20:15 + --> $DIR/fn_trait_refs.rs:20:8 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:20:15 + --> $DIR/fn_trait_refs.rs:20:8 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:20:34 + --> $DIR/fn_trait_refs.rs:20:27 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:27:15 + --> $DIR/fn_trait_refs.rs:27:8 | LL | T: ~const FnOnce<()>, - | ^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:27:15 + --> $DIR/fn_trait_refs.rs:27:8 | LL | T: ~const FnOnce<()>, - | ^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:27:15 + --> $DIR/fn_trait_refs.rs:27:8 | LL | T: ~const FnOnce<()>, - | ^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:34:15 + --> $DIR/fn_trait_refs.rs:34:8 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:34:31 + --> $DIR/fn_trait_refs.rs:34:24 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:34:15 + --> $DIR/fn_trait_refs.rs:34:8 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:34:15 + --> $DIR/fn_trait_refs.rs:34:8 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:34:31 + --> $DIR/fn_trait_refs.rs:34:24 | LL | T: ~const Fn<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:48:15 + --> $DIR/fn_trait_refs.rs:48:8 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:48:34 + --> $DIR/fn_trait_refs.rs:48:27 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:48:15 + --> $DIR/fn_trait_refs.rs:48:8 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:48:15 + --> $DIR/fn_trait_refs.rs:48:8 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/fn_trait_refs.rs:48:34 + --> $DIR/fn_trait_refs.rs:48:27 | LL | T: ~const FnMut<()> + ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/consts/unstable-const-fn-in-libcore.stderr b/tests/ui/consts/unstable-const-fn-in-libcore.stderr index e546694070dd..2bdec1bf41b7 100644 --- a/tests/ui/consts/unstable-const-fn-in-libcore.stderr +++ b/tests/ui/consts/unstable-const-fn-in-libcore.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/unstable-const-fn-in-libcore.rs:19:39 + --> $DIR/unstable-const-fn-in-libcore.rs:19:32 | LL | const fn unwrap_or_else T>(self, f: F) -> T { - | ^^^^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/unstable-const-fn-in-libcore.rs:19:39 + --> $DIR/unstable-const-fn-in-libcore.rs:19:32 | LL | const fn unwrap_or_else T>(self, f: F) -> T { - | ^^^^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/impl-trait/normalize-tait-in-const.stderr b/tests/ui/impl-trait/normalize-tait-in-const.stderr index b370a5d7eb11..f9142664f1b8 100644 --- a/tests/ui/impl-trait/normalize-tait-in-const.stderr +++ b/tests/ui/impl-trait/normalize-tait-in-const.stderr @@ -1,28 +1,28 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/normalize-tait-in-const.rs:26:42 + --> $DIR/normalize-tait-in-const.rs:26:35 | LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/normalize-tait-in-const.rs:26:69 + --> $DIR/normalize-tait-in-const.rs:26:62 | LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/normalize-tait-in-const.rs:26:42 + --> $DIR/normalize-tait-in-const.rs:26:35 | LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/normalize-tait-in-const.rs:26:69 + --> $DIR/normalize-tait-in-const.rs:26:62 | LL | const fn with_positive ~const Fn(&'a Alias<'a>) + ~const Destruct>(fun: F) { - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/specialization/const_trait_impl.stderr b/tests/ui/specialization/const_trait_impl.stderr index 746b08fa7105..40ac350980ef 100644 --- a/tests/ui/specialization/const_trait_impl.stderr +++ b/tests/ui/specialization/const_trait_impl.stderr @@ -1,42 +1,42 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:34:16 + --> $DIR/const_trait_impl.rs:34:9 | LL | impl const A for T { - | ^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:40:16 + --> $DIR/const_trait_impl.rs:40:9 | LL | impl const A for T { - | ^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:46:16 + --> $DIR/const_trait_impl.rs:46:9 | LL | impl const A for T { - | ^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:40:16 + --> $DIR/const_trait_impl.rs:40:9 | LL | impl const A for T { - | ^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:34:16 + --> $DIR/const_trait_impl.rs:34:9 | LL | impl const A for T { - | ^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:46:16 + --> $DIR/const_trait_impl.rs:46:9 | LL | impl const A for T { - | ^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/assoc-type.stderr b/tests/ui/traits/const-traits/assoc-type.stderr index 5c77754200a6..672eaf26f727 100644 --- a/tests/ui/traits/const-traits/assoc-type.stderr +++ b/tests/ui/traits/const-traits/assoc-type.stderr @@ -17,7 +17,7 @@ note: required by a bound in `Foo::Bar` --> $DIR/assoc-type.rs:32:15 | LL | type Bar: ~const Add; - | ^^^^^^^^^^ required by this bound in `Foo::Bar` + | ^^^^^^ required by this bound in `Foo::Bar` error: aborting due to 1 previous error; 1 warning emitted diff --git a/tests/ui/traits/const-traits/call-generic-in-impl.stderr b/tests/ui/traits/const-traits/call-generic-in-impl.stderr index 971e77e372b8..52ee04425b2c 100644 --- a/tests/ui/traits/const-traits/call-generic-in-impl.stderr +++ b/tests/ui/traits/const-traits/call-generic-in-impl.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-in-impl.rs:10:16 + --> $DIR/call-generic-in-impl.rs:10:9 | LL | impl const MyPartialEq for T { - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-in-impl.rs:10:16 + --> $DIR/call-generic-in-impl.rs:10:9 | LL | impl const MyPartialEq for T { - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/call-generic-method-chain.stderr b/tests/ui/traits/const-traits/call-generic-method-chain.stderr index aa90305c6482..6dbf3ad25265 100644 --- a/tests/ui/traits/const-traits/call-generic-method-chain.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-chain.stderr @@ -17,30 +17,30 @@ LL | impl const PartialEq for S { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:20:32 + --> $DIR/call-generic-method-chain.rs:20:25 | LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:20:32 + --> $DIR/call-generic-method-chain.rs:20:25 | LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:24:40 + --> $DIR/call-generic-method-chain.rs:24:33 | LL | const fn equals_self_wrapper(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-chain.rs:24:40 + --> $DIR/call-generic-method-chain.rs:24:33 | LL | const fn equals_self_wrapper(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr index 029915b7646d..08877daad79d 100644 --- a/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-dup-bound.stderr @@ -17,30 +17,30 @@ LL | impl const PartialEq for S { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:20:44 + --> $DIR/call-generic-method-dup-bound.rs:20:37 | LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:20:44 + --> $DIR/call-generic-method-dup-bound.rs:20:37 | LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:27:37 + --> $DIR/call-generic-method-dup-bound.rs:27:30 | LL | const fn equals_self2(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-dup-bound.rs:27:37 + --> $DIR/call-generic-method-dup-bound.rs:27:30 | LL | const fn equals_self2(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/call-generic-method-pass.stderr b/tests/ui/traits/const-traits/call-generic-method-pass.stderr index 97ce7fe1c2a8..ac08c057435e 100644 --- a/tests/ui/traits/const-traits/call-generic-method-pass.stderr +++ b/tests/ui/traits/const-traits/call-generic-method-pass.stderr @@ -17,16 +17,16 @@ LL | impl const PartialEq for S { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-pass.rs:20:32 + --> $DIR/call-generic-method-pass.rs:20:25 | LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/call-generic-method-pass.rs:20:32 + --> $DIR/call-generic-method-pass.rs:20:25 | LL | const fn equals_self(t: &T) -> bool { - | ^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr b/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr index 6c3c11c6a475..d27be2a324b8 100644 --- a/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr +++ b/tests/ui/traits/const-traits/const-bounds-non-const-trait.stderr @@ -13,24 +13,24 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = help: use `-Znext-solver` to enable error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-bounds-non-const-trait.rs:6:28 + --> $DIR/const-bounds-non-const-trait.rs:6:21 | LL | const fn perform() {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-bounds-non-const-trait.rs:6:28 + --> $DIR/const-bounds-non-const-trait.rs:6:21 | LL | const fn perform() {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `const` can only be applied to `#[const_trait]` traits - --> $DIR/const-bounds-non-const-trait.rs:10:21 + --> $DIR/const-bounds-non-const-trait.rs:10:15 | LL | fn operate() {} - | ^^^^^^^^ + | ^^^^^ error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/const-closure-parse-not-item.stderr b/tests/ui/traits/const-traits/const-closure-parse-not-item.stderr index 12cc79f5961d..25c81ff900f2 100644 --- a/tests/ui/traits/const-traits/const-closure-parse-not-item.stderr +++ b/tests/ui/traits/const-traits/const-closure-parse-not-item.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closure-parse-not-item.rs:7:32 + --> $DIR/const-closure-parse-not-item.rs:7:25 | LL | const fn test() -> impl ~const Fn() { - | ^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closure-parse-not-item.rs:7:32 + --> $DIR/const-closure-parse-not-item.rs:7:25 | LL | const fn test() -> impl ~const Fn() { - | ^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr index f0f033bceef4..cb4c994bc2f2 100644 --- a/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr +++ b/tests/ui/traits/const-traits/const-closure-trait-method-fail.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closure-trait-method-fail.rs:14:39 + --> $DIR/const-closure-trait-method-fail.rs:14:32 | LL | const fn need_const_closure i32>(x: T) -> i32 { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closure-trait-method-fail.rs:14:39 + --> $DIR/const-closure-trait-method-fail.rs:14:32 | LL | const fn need_const_closure i32>(x: T) -> i32 { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-closure-trait-method.stderr b/tests/ui/traits/const-traits/const-closure-trait-method.stderr index 4c5a4d0cdf41..43af435ae64d 100644 --- a/tests/ui/traits/const-traits/const-closure-trait-method.stderr +++ b/tests/ui/traits/const-traits/const-closure-trait-method.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closure-trait-method.rs:14:39 + --> $DIR/const-closure-trait-method.rs:14:32 | LL | const fn need_const_closure i32>(x: T) -> i32 { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closure-trait-method.rs:14:39 + --> $DIR/const-closure-trait-method.rs:14:32 | LL | const fn need_const_closure i32>(x: T) -> i32 { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-closures.stderr b/tests/ui/traits/const-traits/const-closures.stderr index a81804a50dc2..2e9e37ba3216 100644 --- a/tests/ui/traits/const-traits/const-closures.stderr +++ b/tests/ui/traits/const-traits/const-closures.stderr @@ -1,56 +1,56 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:8:19 + --> $DIR/const-closures.rs:8:12 | LL | F: ~const FnOnce() -> u8, - | ^^^^^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:9:19 + --> $DIR/const-closures.rs:9:12 | LL | F: ~const FnMut() -> u8, - | ^^^^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:10:19 + --> $DIR/const-closures.rs:10:12 | LL | F: ~const Fn() -> u8, - | ^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:8:19 + --> $DIR/const-closures.rs:8:12 | LL | F: ~const FnOnce() -> u8, - | ^^^^^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:9:19 + --> $DIR/const-closures.rs:9:12 | LL | F: ~const FnMut() -> u8, - | ^^^^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:10:19 + --> $DIR/const-closures.rs:10:12 | LL | F: ~const Fn() -> u8, - | ^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:23:27 + --> $DIR/const-closures.rs:23:20 | LL | const fn answer u8>(f: &F) -> u8 { - | ^^^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-closures.rs:23:27 + --> $DIR/const-closures.rs:23:20 | LL | const fn answer u8>(f: &F) -> u8 { - | ^^^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-drop-bound.stderr b/tests/ui/traits/const-traits/const-drop-bound.stderr index d94b0542324f..3f7186454333 100644 --- a/tests/ui/traits/const-traits/const-drop-bound.stderr +++ b/tests/ui/traits/const-traits/const-drop-bound.stderr @@ -1,42 +1,42 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-bound.rs:9:68 + --> $DIR/const-drop-bound.rs:9:61 | LL | const fn foo(res: Result) -> Option where E: ~const Destruct { - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-bound.rs:9:68 + --> $DIR/const-drop-bound.rs:9:61 | LL | const fn foo(res: Result) -> Option where E: ~const Destruct { - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-bound.rs:20:15 + --> $DIR/const-drop-bound.rs:20:8 | LL | T: ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-bound.rs:21:15 + --> $DIR/const-drop-bound.rs:21:8 | LL | E: ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-bound.rs:20:15 + --> $DIR/const-drop-bound.rs:20:8 | LL | T: ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-bound.rs:21:15 + --> $DIR/const-drop-bound.rs:21:8 | LL | E: ~const Destruct, - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-drop-fail-2.stderr b/tests/ui/traits/const-traits/const-drop-fail-2.stderr index 27e8053c9690..82d6412ded0c 100644 --- a/tests/ui/traits/const-traits/const-drop-fail-2.stderr +++ b/tests/ui/traits/const-traits/const-drop-fail-2.stderr @@ -8,16 +8,16 @@ LL | impl const Drop for ConstDropImplWithNonConstBounds { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-fail-2.rs:20:26 + --> $DIR/const-drop-fail-2.rs:20:19 | LL | const fn check(_: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-fail-2.rs:20:26 + --> $DIR/const-drop-fail-2.rs:20:19 | LL | const fn check(_: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-drop-fail.precise.stderr b/tests/ui/traits/const-traits/const-drop-fail.precise.stderr index bde13b4d6cfa..859fdfae81ae 100644 --- a/tests/ui/traits/const-traits/const-drop-fail.precise.stderr +++ b/tests/ui/traits/const-traits/const-drop-fail.precise.stderr @@ -8,16 +8,16 @@ LL | impl const Drop for ConstImplWithDropGlue { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-fail.rs:23:26 + --> $DIR/const-drop-fail.rs:23:19 | LL | const fn check(_: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-fail.rs:23:26 + --> $DIR/const-drop-fail.rs:23:19 | LL | const fn check(_: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-drop-fail.stock.stderr b/tests/ui/traits/const-traits/const-drop-fail.stock.stderr index 064ffacca427..20dea28922b6 100644 --- a/tests/ui/traits/const-traits/const-drop-fail.stock.stderr +++ b/tests/ui/traits/const-traits/const-drop-fail.stock.stderr @@ -8,16 +8,16 @@ LL | impl const Drop for ConstImplWithDropGlue { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-fail.rs:23:26 + --> $DIR/const-drop-fail.rs:23:19 | LL | const fn check(_: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop-fail.rs:23:26 + --> $DIR/const-drop-fail.rs:23:19 | LL | const fn check(_: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-drop.precise.stderr b/tests/ui/traits/const-traits/const-drop.precise.stderr index 7b6d185c7cc8..2b8066e5ee7c 100644 --- a/tests/ui/traits/const-traits/const-drop.precise.stderr +++ b/tests/ui/traits/const-traits/const-drop.precise.stderr @@ -35,16 +35,16 @@ LL | impl const Drop for ConstDropWithNonconstBound { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop.rs:18:22 + --> $DIR/const-drop.rs:18:15 | LL | const fn a(_: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop.rs:18:22 + --> $DIR/const-drop.rs:18:15 | LL | const fn a(_: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const-drop.stock.stderr b/tests/ui/traits/const-traits/const-drop.stock.stderr index b497c39b08aa..54ed2930b90b 100644 --- a/tests/ui/traits/const-traits/const-drop.stock.stderr +++ b/tests/ui/traits/const-traits/const-drop.stock.stderr @@ -35,16 +35,16 @@ LL | impl const Drop for ConstDropWithNonconstBound { = note: adding a non-const method body in the future would be a breaking change error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop.rs:18:22 + --> $DIR/const-drop.rs:18:15 | LL | const fn a(_: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/const-drop.rs:18:22 + --> $DIR/const-drop.rs:18:15 | LL | const fn a(_: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr index 33e7e08bb235..64285cff0a6e 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr @@ -23,12 +23,6 @@ LL | #[derive_const(PartialEq)] = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/derive-const-with-params.rs:7:16 - | -LL | #[derive_const(PartialEq)] - | ^^^^^^^^^ - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const operator in constant functions --> $DIR/derive-const-with-params.rs:8:23 diff --git a/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr index edfdf8b5f781..5b0d5a8bb1d0 100644 --- a/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr +++ b/tests/ui/traits/const-traits/effects/ice-112822-expected-type-for-param.stderr @@ -23,16 +23,16 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = help: use `-Znext-solver` to enable error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/ice-112822-expected-type-for-param.rs:3:32 + --> $DIR/ice-112822-expected-type-for-param.rs:3:25 | LL | const fn test() -> impl ~const Fn() { - | ^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/ice-112822-expected-type-for-param.rs:3:32 + --> $DIR/ice-112822-expected-type-for-param.rs:3:25 | LL | const fn test() -> impl ~const Fn() { - | ^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr index d9655c4995fa..0cb172a2d14b 100644 --- a/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr +++ b/tests/ui/traits/const-traits/effects/spec-effectvar-ice.stderr @@ -37,10 +37,10 @@ LL | impl const Foo for T where T: const Specialize {} = note: adding a non-const method body in the future would be a breaking change error: `const` can only be applied to `#[const_trait]` traits - --> $DIR/spec-effectvar-ice.rs:14:40 + --> $DIR/spec-effectvar-ice.rs:14:34 | LL | impl const Foo for T where T: const Specialize {} - | ^^^^^^^^^^ + | ^^^^^ error: specialization impl does not specialize any associated items --> $DIR/spec-effectvar-ice.rs:14:1 diff --git a/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr index 03f88be00936..dcb7dd7a142a 100644 --- a/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr +++ b/tests/ui/traits/const-traits/ice-123664-unexpected-bound-var.stderr @@ -4,16 +4,16 @@ error: using `#![feature(effects)]` without enabling next trait solver globally = help: use `-Znext-solver` to enable error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/ice-123664-unexpected-bound-var.rs:4:34 + --> $DIR/ice-123664-unexpected-bound-var.rs:4:27 | LL | const fn with_positive() {} - | ^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/ice-123664-unexpected-bound-var.rs:4:34 + --> $DIR/ice-123664-unexpected-bound-var.rs:4:27 | LL | const fn with_positive() {} - | ^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/issue-92111.stderr b/tests/ui/traits/const-traits/issue-92111.stderr index 805cc5370149..51c6a22b43b3 100644 --- a/tests/ui/traits/const-traits/issue-92111.stderr +++ b/tests/ui/traits/const-traits/issue-92111.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/issue-92111.rs:20:22 + --> $DIR/issue-92111.rs:20:15 | LL | const fn a(t: T) {} - | ^^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/issue-92111.rs:20:22 + --> $DIR/issue-92111.rs:20:15 | LL | const fn a(t: T) {} - | ^^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr b/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr index 3b3868c4bc84..054a8ac75779 100644 --- a/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr +++ b/tests/ui/traits/const-traits/item-bound-entailment-fails.stderr @@ -17,7 +17,7 @@ note: required by a bound in `Foo::Assoc` --> $DIR/item-bound-entailment-fails.rs:6:20 | LL | type Assoc: ~const Bar - | ^^^^^^^^^^ required by this bound in `Foo::Assoc` + | ^^^^^^ required by this bound in `Foo::Assoc` error[E0277]: the trait bound `T: ~const Bar` is not satisfied --> $DIR/item-bound-entailment-fails.rs:25:21 @@ -29,7 +29,7 @@ note: required by a bound in `Foo::Assoc` --> $DIR/item-bound-entailment-fails.rs:6:20 | LL | type Assoc: ~const Bar - | ^^^^^^^^^^ required by this bound in `Foo::Assoc` + | ^^^^^^ required by this bound in `Foo::Assoc` error: aborting due to 2 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr index 08a40fe65bfa..837effb7ca4c 100644 --- a/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr +++ b/tests/ui/traits/const-traits/non-const-op-in-closure-in-const.stderr @@ -1,14 +1,14 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/non-const-op-in-closure-in-const.rs:10:51 + --> $DIR/non-const-op-in-closure-in-const.rs:10:44 | LL | impl const Convert for A where B: ~const From { - | ^^^^^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/non-const-op-in-closure-in-const.rs:10:51 + --> $DIR/non-const-op-in-closure-in-const.rs:10:44 | LL | impl const Convert for A where B: ~const From { - | ^^^^^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/predicate-entailment-fails.stderr b/tests/ui/traits/const-traits/predicate-entailment-fails.stderr index 7cd48ef1d488..c50009e9b8c4 100644 --- a/tests/ui/traits/const-traits/predicate-entailment-fails.stderr +++ b/tests/ui/traits/const-traits/predicate-entailment-fails.stderr @@ -14,7 +14,7 @@ LL | type Bar where T: ~const Bar; | ----------- definition of `Bar` from trait ... LL | type Bar = () where T: const Bar; - | ^^^^^^^^^ impl has extra requirement `T: const Bar` + | ^^^^^ impl has extra requirement `T: const Bar` error[E0276]: impl has stricter requirements than trait --> $DIR/predicate-entailment-fails.rs:18:26 @@ -23,7 +23,7 @@ LL | fn foo() where T: ~const Bar; | -------------------------------- definition of `foo` from trait ... LL | fn foo() where T: const Bar {} - | ^^^^^^^^^ impl has extra requirement `T: const Bar` + | ^^^^^ impl has extra requirement `T: const Bar` error[E0276]: impl has stricter requirements than trait --> $DIR/predicate-entailment-fails.rs:29:31 @@ -32,7 +32,7 @@ LL | type Bar where T: Bar; | ----------- definition of `Bar` from trait ... LL | type Bar = () where T: const Bar; - | ^^^^^^^^^ impl has extra requirement `T: const Bar` + | ^^^^^ impl has extra requirement `T: const Bar` error[E0276]: impl has stricter requirements than trait --> $DIR/predicate-entailment-fails.rs:32:26 @@ -41,7 +41,7 @@ LL | fn foo() where T: Bar; | ------------------------- definition of `foo` from trait ... LL | fn foo() where T: const Bar {} - | ^^^^^^^^^ impl has extra requirement `T: const Bar` + | ^^^^^ impl has extra requirement `T: const Bar` error[E0276]: impl has stricter requirements than trait --> $DIR/predicate-entailment-fails.rs:36:31 @@ -50,7 +50,7 @@ LL | type Bar where T: Bar; | ----------- definition of `Bar` from trait ... LL | type Bar = () where T: ~const Bar; - | ^^^^^^^^^^ impl has extra requirement `T: ~const Bar` + | ^^^^^^ impl has extra requirement `T: ~const Bar` error[E0276]: impl has stricter requirements than trait --> $DIR/predicate-entailment-fails.rs:39:26 @@ -59,7 +59,7 @@ LL | fn foo() where T: Bar; | ------------------------- definition of `foo` from trait ... LL | fn foo() where T: ~const Bar {} - | ^^^^^^^^^^ impl has extra requirement `T: ~const Bar` + | ^^^^^^ impl has extra requirement `T: ~const Bar` error: aborting due to 6 previous errors; 1 warning emitted diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr index 6277966b08e9..8de1bb07e908 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.nn.stderr @@ -11,24 +11,24 @@ LL | trait Bar: ~const Foo {} | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr index 60660ecc2797..82b306aeff6b 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-2.ny.stderr @@ -1,38 +1,38 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-2.rs:12:19 + --> $DIR/super-traits-fail-2.rs:12:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr index b39bf8d8e158..1dd4a2ed5a5f 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.nn.stderr @@ -11,38 +11,38 @@ LL | trait Bar: ~const Foo {} | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:22:24 + --> $DIR/super-traits-fail-3.rs:22:17 | LL | const fn foo(x: &T) { - | ^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:22:24 + --> $DIR/super-traits-fail-3.rs:22:17 | LL | const fn foo(x: &T) { - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr index 187cd998d95a..e619b8bd6bab 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.ny.stderr @@ -1,38 +1,38 @@ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:14:19 + --> $DIR/super-traits-fail-3.rs:14:12 | LL | trait Bar: ~const Foo {} - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr b/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr index b6747d10e83c..0a36d40d9314 100644 --- a/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr +++ b/tests/ui/traits/const-traits/super-traits-fail-3.yn.stderr @@ -11,16 +11,16 @@ LL | trait Bar: ~const Foo {} | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:22:24 + --> $DIR/super-traits-fail-3.rs:22:17 | LL | const fn foo(x: &T) { - | ^^^ + | ^^^^^^ error: `~const` can only be applied to `#[const_trait]` traits - --> $DIR/super-traits-fail-3.rs:22:24 + --> $DIR/super-traits-fail-3.rs:22:17 | LL | const fn foo(x: &T) { - | ^^^ + | ^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr b/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr index e0cf062ad95e..35f3019b6eee 100644 --- a/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr +++ b/tests/ui/traits/const-traits/unsatisfied-const-trait-bound.stderr @@ -28,7 +28,7 @@ note: required by a bound in `require` --> $DIR/unsatisfied-const-trait-bound.rs:8:15 | LL | fn require() {} - | ^^^^^^^^^^^ required by this bound in `require` + | ^^^^^ required by this bound in `require` error: aborting due to 4 previous errors From c1a08f97637671b4e8ef69f69ddb811c472acaf1 Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sat, 26 Oct 2024 17:31:03 -0400 Subject: [PATCH 288/366] Make clearer that guarantees in ABI compatibility are for Rust only --- library/core/src/primitive_docs.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index bf9bfd84b565..4a6fca5085c4 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1612,6 +1612,9 @@ mod prim_ref {} /// pointers, make your type [`Option`](core::option#options-and-pointers-nullable-pointers) /// with your required signature. /// +/// Note that FFI requires additional care to ensure that the ABI for both sides of the call match. +/// The exact requirements are not currently documented. +/// /// ### Safety /// /// Plain function pointers are obtained by casting either plain functions, or closures that don't @@ -1750,8 +1753,13 @@ mod prim_ref {} /// is also used rarely. So, most likely you do not have to worry about ABI compatibility. /// /// But assuming such circumstances, what are the rules? For this section, we are only considering -/// the ABI of direct Rust-to-Rust calls, not linking in general -- once functions are imported via -/// `extern` blocks, there are more things to consider that we do not go into here. +/// the ABI of direct Rust-to-Rust calls (with both definition and callsite visible to the +/// Rust compiler), not linking in general -- once functions are imported via `extern` blocks, there +/// are more things to consider that we do not go into here. Note that this also applies to +/// passing/calling functions across language boundaries via function pointers. +/// +/// **Nothing in this section should be taken as a guarantee for non-Rust-to-Rust calls, even with +/// types from `core::ffi` or `libc`**. /// /// For two signatures to be considered *ABI-compatible*, they must use a compatible ABI string, /// must take the same number of arguments, the individual argument types and the return types must From d6b26588a760a2ca72c4d5504775a36fe41725e4 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 27 Oct 2024 00:47:13 +0300 Subject: [PATCH 289/366] Correctly handle `#""` in edition <2024 --- .../crates/parser/src/lexed_str.rs | 13 ++++++++++--- .../rust-analyzer/crates/parser/src/tests.rs | 17 +++++++++++++---- .../ok/guarded_str_prefix_edition_2021.rast | 4 ++++ .../lexer/ok/guarded_str_prefix_edition_2021.rs | 3 +++ 4 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rast create mode 100644 src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rs diff --git a/src/tools/rust-analyzer/crates/parser/src/lexed_str.rs b/src/tools/rust-analyzer/crates/parser/src/lexed_str.rs index 5322463a7132..3c0eb1b42a60 100644 --- a/src/tools/rust-analyzer/crates/parser/src/lexed_str.rs +++ b/src/tools/rust-analyzer/crates/parser/src/lexed_str.rs @@ -39,7 +39,9 @@ impl<'a> LexedStr<'a> { conv.offset = shebang_len; }; - for token in rustc_lexer::tokenize(&text[conv.offset..]) { + // Re-create the tokenizer from scratch every token because `GuardedStrPrefix` is one token in the lexer + // but we want to split it to two in edition <2024. + while let Some(token) = rustc_lexer::tokenize(&text[conv.offset..]).next() { let token_text = &text[conv.offset..][..token.len as usize]; conv.extend_token(&token.kind, token_text); @@ -158,7 +160,7 @@ impl<'a> Converter<'a> { } } - fn extend_token(&mut self, kind: &rustc_lexer::TokenKind, token_text: &str) { + fn extend_token(&mut self, kind: &rustc_lexer::TokenKind, mut token_text: &str) { // A note on an intended tradeoff: // We drop some useful information here (see patterns with double dots `..`) // Storing that info in `SyntaxKind` is not possible due to its layout requirements of @@ -189,10 +191,15 @@ impl<'a> Converter<'a> { rustc_lexer::TokenKind::RawIdent => IDENT, rustc_lexer::TokenKind::GuardedStrPrefix if self.edition.at_least_2024() => { + // FIXME: rustc does something better for recovery. err = "Invalid string literal (reserved syntax)"; ERROR } - rustc_lexer::TokenKind::GuardedStrPrefix => POUND, + rustc_lexer::TokenKind::GuardedStrPrefix => { + // The token is `#"` or `##`, split it into two. + token_text = &token_text[1..]; + POUND + } rustc_lexer::TokenKind::Literal { kind, .. } => { self.extend_literal(token_text.len(), kind); diff --git a/src/tools/rust-analyzer/crates/parser/src/tests.rs b/src/tools/rust-analyzer/crates/parser/src/tests.rs index e7bccb6685c9..4b19ddc752a0 100644 --- a/src/tools/rust-analyzer/crates/parser/src/tests.rs +++ b/src/tools/rust-analyzer/crates/parser/src/tests.rs @@ -15,11 +15,20 @@ use crate::{Edition, LexedStr, TopEntryPoint}; #[path = "../test_data/generated/runner.rs"] mod runner; +fn infer_edition(file_path: &Path) -> Edition { + let file_content = std::fs::read_to_string(file_path).unwrap(); + if let Some(edition) = file_content.strip_prefix("//@ edition: ") { + edition[..4].parse().expect("invalid edition directive") + } else { + Edition::CURRENT + } +} + #[test] fn lex_ok() { for case in TestCase::list("lexer/ok") { let _guard = stdx::panic_context::enter(format!("{:?}", case.rs)); - let actual = lex(&case.text); + let actual = lex(&case.text, infer_edition(&case.rs)); expect_file![case.rast].assert_eq(&actual) } } @@ -28,13 +37,13 @@ fn lex_ok() { fn lex_err() { for case in TestCase::list("lexer/err") { let _guard = stdx::panic_context::enter(format!("{:?}", case.rs)); - let actual = lex(&case.text); + let actual = lex(&case.text, infer_edition(&case.rs)); expect_file![case.rast].assert_eq(&actual) } } -fn lex(text: &str) -> String { - let lexed = LexedStr::new(Edition::CURRENT, text); +fn lex(text: &str, edition: Edition) -> String { + let lexed = LexedStr::new(edition, text); let mut res = String::new(); for i in 0..lexed.len() { diff --git a/src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rast b/src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rast new file mode 100644 index 000000000000..1bdd6720441f --- /dev/null +++ b/src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rast @@ -0,0 +1,4 @@ +COMMENT "//@ edition: 2021" +WHITESPACE "\n\n" +POUND "#" +STRING "\"foo\"" diff --git a/src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rs b/src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rs new file mode 100644 index 000000000000..f00f949f0db5 --- /dev/null +++ b/src/tools/rust-analyzer/crates/parser/test_data/lexer/ok/guarded_str_prefix_edition_2021.rs @@ -0,0 +1,3 @@ +//@ edition: 2021 + +#"foo" \ No newline at end of file From 2ebb8ecbc4938f5b8d230224a154dddee13dce90 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sat, 26 Oct 2024 14:37:11 -0700 Subject: [PATCH 290/366] docs: Correctly link riscv32e from platform-support.md --- src/doc/rustc/src/SUMMARY.md | 3 ++- src/doc/rustc/src/platform-support.md | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index e05d9a40f00e..18f76ac6fe0c 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -66,9 +66,10 @@ - [powerpc-unknown-openbsd](platform-support/powerpc-unknown-openbsd.md) - [powerpc-unknown-linux-muslspe](platform-support/powerpc-unknown-linux-muslspe.md) - [powerpc64-ibm-aix](platform-support/aix.md) + - [riscv32e*-unknown-none-elf](platform-support/riscv32e-unknown-none-elf.md) + - [riscv32i*-unknown-none-elf](platform-support/riscv32-unknown-none-elf.md) - [riscv32im-risc0-zkvm-elf](platform-support/riscv32im-risc0-zkvm-elf.md) - [riscv32imac-unknown-xous-elf](platform-support/riscv32imac-unknown-xous-elf.md) - - [riscv32*-unknown-none-elf](platform-support/riscv32-unknown-none-elf.md) - [riscv64gc-unknown-linux-gnu](platform-support/riscv64gc-unknown-linux-gnu.md) - [riscv64gc-unknown-linux-musl](platform-support/riscv64gc-unknown-linux-musl.md) - [sparc-unknown-none-elf](./platform-support/sparc-unknown-none-elf.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 5da03d26eb41..f7b8a8fc6e64 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -414,8 +414,8 @@ target | std | host | notes [`riscv32imafc-unknown-nuttx-elf`](platform-support/nuttx.md) | * | | RISC-V 32bit with NuttX [`riscv64imac-unknown-nuttx-elf`](platform-support/nuttx.md) | * | | RISC-V 64bit with NuttX [`riscv64gc-unknown-nuttx-elf`](platform-support/nuttx.md) | * | | RISC-V 64bit with NuttX -[`riscv32e-unknown-none-elf`](platform-support/riscv32-unknown-none-elf.md) | * | | Bare RISC-V (RV32E ISA) -[`riscv32em-unknown-none-elf`](platform-support/riscv32-unknown-none-elf.md) | * | | Bare RISC-V (RV32EM ISA) -[`riscv32emc-unknown-none-elf`](platform-support/riscv32-unknown-none-elf.md) | * | | Bare RISC-V (RV32EMC ISA) +[`riscv32e-unknown-none-elf`](platform-support/riscv32e-unknown-none-elf.md) | * | | Bare RISC-V (RV32E ISA) +[`riscv32em-unknown-none-elf`](platform-support/riscv32e-unknown-none-elf.md) | * | | Bare RISC-V (RV32EM ISA) +[`riscv32emc-unknown-none-elf`](platform-support/riscv32e-unknown-none-elf.md) | * | | Bare RISC-V (RV32EMC ISA) [runs on NVIDIA GPUs]: https://github.com/japaric-archived/nvptx#targets From d976ca870191e8677925ff4b76c48cae829ec5ae Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 25 Oct 2024 22:26:15 +1100 Subject: [PATCH 291/366] Use LLVM-C APIs for getting/setting visibility --- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 8 ++-- compiler/rustc_codegen_llvm/src/llvm/mod.rs | 4 +- .../rustc_llvm/llvm-wrapper/RustWrapper.cpp | 39 ------------------- compiler/rustc_macros/src/try_from.rs | 2 + 4 files changed, 8 insertions(+), 45 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 3258a6c43cc6..acc660768339 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -161,9 +161,9 @@ pub enum Linkage { LinkerPrivateWeakLinkage = 16, } -// LLVMRustVisibility +/// Must match the layout of `LLVMVisibility`. #[repr(C)] -#[derive(Copy, Clone, PartialEq)] +#[derive(Copy, Clone, PartialEq, TryFromU32)] pub enum Visibility { Default = 0, Hidden = 1, @@ -984,6 +984,8 @@ unsafe extern "C" { pub fn LLVMGetLinkage(Global: &Value) -> RawEnum; pub fn LLVMSetLinkage(Global: &Value, RustLinkage: Linkage); pub fn LLVMSetSection(Global: &Value, Section: *const c_char); + pub fn LLVMGetVisibility(Global: &Value) -> RawEnum; + pub fn LLVMSetVisibility(Global: &Value, Viz: Visibility); pub fn LLVMGetAlignment(Global: &Value) -> c_uint; pub fn LLVMSetAlignment(Global: &Value, Bytes: c_uint); pub fn LLVMSetDLLStorageClass(V: &Value, C: DLLStorageClass); @@ -1559,8 +1561,6 @@ unsafe extern "C" { ) -> bool; // Operations on global variables, functions, and aliases (globals) - pub fn LLVMRustGetVisibility(Global: &Value) -> Visibility; - pub fn LLVMRustSetVisibility(Global: &Value, Viz: Visibility); pub fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool); // Operations on global variables diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index 3eef9e623614..6aac2eea81d0 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -243,12 +243,12 @@ pub fn set_linkage(llglobal: &Value, linkage: Linkage) { } pub fn get_visibility(llglobal: &Value) -> Visibility { - unsafe { LLVMRustGetVisibility(llglobal) } + unsafe { LLVMGetVisibility(llglobal) }.to_rust() } pub fn set_visibility(llglobal: &Value, visibility: Visibility) { unsafe { - LLVMRustSetVisibility(llglobal, visibility); + LLVMSetVisibility(llglobal, visibility); } } diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 6c3fa9622f3b..9f941637d8c1 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1646,45 +1646,6 @@ extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, return true; } -enum class LLVMRustVisibility { - Default = 0, - Hidden = 1, - Protected = 2, -}; - -static LLVMRustVisibility toRust(LLVMVisibility Vis) { - switch (Vis) { - case LLVMDefaultVisibility: - return LLVMRustVisibility::Default; - case LLVMHiddenVisibility: - return LLVMRustVisibility::Hidden; - case LLVMProtectedVisibility: - return LLVMRustVisibility::Protected; - } - report_fatal_error("Invalid LLVMRustVisibility value!"); -} - -static LLVMVisibility fromRust(LLVMRustVisibility Vis) { - switch (Vis) { - case LLVMRustVisibility::Default: - return LLVMDefaultVisibility; - case LLVMRustVisibility::Hidden: - return LLVMHiddenVisibility; - case LLVMRustVisibility::Protected: - return LLVMProtectedVisibility; - } - report_fatal_error("Invalid LLVMRustVisibility value!"); -} - -extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) { - return toRust(LLVMGetVisibility(V)); -} - -extern "C" void LLVMRustSetVisibility(LLVMValueRef V, - LLVMRustVisibility RustVisibility) { - LLVMSetVisibility(V, fromRust(RustVisibility)); -} - extern "C" void LLVMRustSetDSOLocal(LLVMValueRef Global, bool is_dso_local) { unwrap(Global)->setDSOLocal(is_dso_local); } diff --git a/compiler/rustc_macros/src/try_from.rs b/compiler/rustc_macros/src/try_from.rs index fde7c8f62040..9338c1c2b336 100644 --- a/compiler/rustc_macros/src/try_from.rs +++ b/compiler/rustc_macros/src/try_from.rs @@ -34,6 +34,8 @@ pub(crate) fn try_from_u32(s: Structure<'_>) -> TokenStream { .iter() .map(|v| v.construct(|_, _| -> TokenStream { unreachable!() })) .collect::>(); + // FIXME(edition_2024): Fix the `keyword_idents_2024` lint to not trigger here? + #[allow(keyword_idents_2024)] s.gen_impl(quote! { // The surrounding code might have shadowed these identifiers. use ::core::convert::TryFrom; From 071bd3c360aaf7a6ae82f84855489a004b9f10c1 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 27 Oct 2024 02:24:15 +0200 Subject: [PATCH 292/366] Split `macro-error` diagnostic so users can ignore only parts of it Split it into `macro-error`, `proc-macros-disabled` and `proc-macro-disabled`. --- .../hir-def/src/macro_expansion_tests/mod.rs | 2 +- .../crates/hir-expand/src/lib.rs | 81 +++++++++++++------ .../crates/hir/src/diagnostics.rs | 1 + src/tools/rust-analyzer/crates/hir/src/lib.rs | 14 ++-- .../src/handlers/macro_error.rs | 13 ++- 5 files changed, 77 insertions(+), 34 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs b/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs index 450a15bd66e5..d5b94f0ae443 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -122,7 +122,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream let mut expn_text = String::new(); if let Some(err) = exp.err { - format_to!(expn_text, "/* error: {} */", err.render_to_string(&db).0); + format_to!(expn_text, "/* error: {} */", err.render_to_string(&db).message); } let (parse, token_map) = exp.value; if expect_errors { diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs b/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs index 5d5f72490d0c..7d2f556406d4 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs @@ -165,40 +165,73 @@ pub enum ExpandErrorKind { } impl ExpandError { - pub fn render_to_string(&self, db: &dyn ExpandDatabase) -> (String, bool) { + pub fn render_to_string(&self, db: &dyn ExpandDatabase) -> RenderedExpandError { self.inner.0.render_to_string(db) } } +pub struct RenderedExpandError { + pub message: String, + pub error: bool, + pub kind: &'static str, +} + +impl RenderedExpandError { + const GENERAL_KIND: &str = "macro-error"; +} + impl ExpandErrorKind { - pub fn render_to_string(&self, db: &dyn ExpandDatabase) -> (String, bool) { + pub fn render_to_string(&self, db: &dyn ExpandDatabase) -> RenderedExpandError { match self { - ExpandErrorKind::ProcMacroAttrExpansionDisabled => { - ("procedural attribute macro expansion is disabled".to_owned(), false) - } - ExpandErrorKind::MacroDisabled => { - ("proc-macro is explicitly disabled".to_owned(), false) - } + ExpandErrorKind::ProcMacroAttrExpansionDisabled => RenderedExpandError { + message: "procedural attribute macro expansion is disabled".to_owned(), + error: false, + kind: "proc-macros-disabled", + }, + ExpandErrorKind::MacroDisabled => RenderedExpandError { + message: "proc-macro is explicitly disabled".to_owned(), + error: false, + kind: "proc-macro-disabled", + }, &ExpandErrorKind::MissingProcMacroExpander(def_crate) => { match db.proc_macros().get_error_for_crate(def_crate) { - Some((e, hard_err)) => (e.to_owned(), hard_err), - None => ( - format!( - "internal error: proc-macro map is missing error entry for crate {def_crate:?}" - ), - true, - ), + Some((e, hard_err)) => RenderedExpandError { + message: e.to_owned(), + error: hard_err, + kind: RenderedExpandError::GENERAL_KIND, + }, + None => RenderedExpandError { + message: format!("internal error: proc-macro map is missing error entry for crate {def_crate:?}"), + error: true, + kind: RenderedExpandError::GENERAL_KIND, + }, } } - ExpandErrorKind::MacroDefinition => { - ("macro definition has parse errors".to_owned(), true) - } - ExpandErrorKind::Mbe(e) => (e.to_string(), true), - ExpandErrorKind::RecursionOverflow => { - ("overflow expanding the original macro".to_owned(), true) - } - ExpandErrorKind::Other(e) => ((**e).to_owned(), true), - ExpandErrorKind::ProcMacroPanic(e) => (format!("proc-macro panicked: {e}"), true), + ExpandErrorKind::MacroDefinition => RenderedExpandError { + message: "macro definition has parse errors".to_owned(), + error: true, + kind: RenderedExpandError::GENERAL_KIND, + }, + ExpandErrorKind::Mbe(e) => RenderedExpandError { + message: e.to_string(), + error: true, + kind: RenderedExpandError::GENERAL_KIND, + }, + ExpandErrorKind::RecursionOverflow => RenderedExpandError { + message: "overflow expanding the original macro".to_owned(), + error: true, + kind: RenderedExpandError::GENERAL_KIND, + }, + ExpandErrorKind::Other(e) => RenderedExpandError { + message: (**e).to_owned(), + error: true, + kind: RenderedExpandError::GENERAL_KIND, + }, + ExpandErrorKind::ProcMacroPanic(e) => RenderedExpandError { + message: format!("proc-macro panicked: {e}"), + error: true, + kind: RenderedExpandError::GENERAL_KIND, + }, } } } diff --git a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs index 2fedffe047db..8297acde857d 100644 --- a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs @@ -165,6 +165,7 @@ pub struct MacroError { pub precise_location: Option, pub message: String, pub error: bool, + pub kind: &'static str, } #[derive(Debug, Clone, Eq, PartialEq)] diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index 4a18795e7d62..f9b51b657099 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -58,7 +58,8 @@ use hir_def::{ TypeOrConstParamId, TypeParamId, UnionId, }; use hir_expand::{ - attrs::collect_attrs, proc_macro::ProcMacroKind, AstId, MacroCallKind, ValueResult, + attrs::collect_attrs, proc_macro::ProcMacroKind, AstId, MacroCallKind, RenderedExpandError, + ValueResult, }; use hir_ty::{ all_super_traits, autoderef, check_orphan_rules, @@ -838,7 +839,7 @@ fn macro_call_diagnostics( let file_id = loc.kind.file_id(); let node = InFile::new(file_id, db.ast_id_map(file_id).get_erased(loc.kind.erased_ast_id())); - let (message, error) = err.render_to_string(db.upcast()); + let RenderedExpandError { message, error, kind } = err.render_to_string(db.upcast()); let precise_location = if err.span().anchor.file_id == file_id { Some( err.span().range @@ -850,7 +851,7 @@ fn macro_call_diagnostics( } else { None }; - acc.push(MacroError { node, precise_location, message, error }.into()); + acc.push(MacroError { node, precise_location, message, error, kind }.into()); } if !parse_errors.is_empty() { @@ -916,13 +917,14 @@ fn emit_def_diagnostic_( DefDiagnosticKind::MacroError { ast, path, err } => { let item = ast.to_ptr(db.upcast()); - let (message, error) = err.render_to_string(db.upcast()); + let RenderedExpandError { message, error, kind } = err.render_to_string(db.upcast()); acc.push( MacroError { node: InFile::new(ast.file_id, item.syntax_node_ptr()), precise_location: None, message: format!("{}: {message}", path.display(db.upcast(), edition)), error, + kind, } .into(), ) @@ -1811,7 +1813,8 @@ impl DefWithBody { InactiveCode { node: *node, cfg: cfg.clone(), opts: opts.clone() }.into() } BodyDiagnostic::MacroError { node, err } => { - let (message, error) = err.render_to_string(db.upcast()); + let RenderedExpandError { message, error, kind } = + err.render_to_string(db.upcast()); let precise_location = if err.span().anchor.file_id == node.file_id { Some( @@ -1829,6 +1832,7 @@ impl DefWithBody { precise_location, message, error, + kind, } .into() } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs index 6a976697c805..e177b72e4d43 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs @@ -3,14 +3,19 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext, Severity}; // Diagnostic: macro-error // // This diagnostic is shown for macro expansion errors. + +// Diagnostic: proc-macros-disabled +// +// This diagnostic is shown for proc macros where proc macros have been disabled. + +// Diagnostic: proc-macro-disabled +// +// This diagnostic is shown for proc macros that has been specifically disabled via `rust-analyzer.procMacro.ignored`. pub(crate) fn macro_error(ctx: &DiagnosticsContext<'_>, d: &hir::MacroError) -> Diagnostic { // Use more accurate position if available. let display_range = ctx.resolve_precise_location(&d.node, d.precise_location); Diagnostic::new( - DiagnosticCode::Ra( - "macro-error", - if d.error { Severity::Error } else { Severity::WeakWarning }, - ), + DiagnosticCode::Ra(d.kind, if d.error { Severity::Error } else { Severity::WeakWarning }), d.message.clone(), display_range, ) From 42fbaf1ddde7c334ded228eff6e5fa31aff8fb94 Mon Sep 17 00:00:00 2001 From: Asuna Date: Wed, 9 Oct 2024 18:29:31 +0800 Subject: [PATCH 293/366] Add a new trait `proc_macro::ToTokens` --- library/proc_macro/src/lib.rs | 4 + library/proc_macro/src/to_tokens.rs | 310 ++++++++++++++++++++++++++++ 2 files changed, 314 insertions(+) create mode 100644 library/proc_macro/src/to_tokens.rs diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index ae47bb7adf49..15770248b310 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -32,6 +32,7 @@ #![feature(restricted_std)] #![feature(rustc_attrs)] #![feature(min_specialization)] +#![feature(extend_one)] #![recursion_limit = "256"] #![allow(internal_features)] #![deny(ffi_unwind_calls)] @@ -43,6 +44,7 @@ pub mod bridge; mod diagnostic; mod escape; +mod to_tokens; use std::ffi::CStr; use std::ops::{Range, RangeBounds}; @@ -52,6 +54,8 @@ use std::{error, fmt}; #[unstable(feature = "proc_macro_diagnostic", issue = "54140")] pub use diagnostic::{Diagnostic, Level, MultiSpan}; +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +pub use to_tokens::ToTokens; use crate::escape::{EscapeOptions, escape_bytes}; diff --git a/library/proc_macro/src/to_tokens.rs b/library/proc_macro/src/to_tokens.rs new file mode 100644 index 000000000000..8f697b416d5c --- /dev/null +++ b/library/proc_macro/src/to_tokens.rs @@ -0,0 +1,310 @@ +use std::borrow::Cow; +use std::ffi::{CStr, CString}; +use std::rc::Rc; + +use crate::{ConcatTreesHelper, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; + +/// Types that can be interpolated inside a [`quote!`] invocation. +/// +/// [`quote!`]: crate::quote! +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +pub trait ToTokens { + /// Write `self` to the given `TokenStream`. + /// + /// # Example + /// + /// Example implementation for a struct representing Rust paths like + /// `std::cmp::PartialEq`: + /// + /// ``` + /// #![feature(proc_macro_totokens)] + /// + /// use std::iter; + /// use proc_macro::{Spacing, Punct, TokenStream, TokenTree, ToTokens}; + /// + /// pub struct Path { + /// pub global: bool, + /// pub segments: Vec, + /// } + /// + /// impl ToTokens for Path { + /// fn to_tokens(&self, tokens: &mut TokenStream) { + /// for (i, segment) in self.segments.iter().enumerate() { + /// if i > 0 || self.global { + /// // Double colon `::` + /// tokens.extend(iter::once(TokenTree::from(Punct::new(':', Spacing::Joint)))); + /// tokens.extend(iter::once(TokenTree::from(Punct::new(':', Spacing::Alone)))); + /// } + /// segment.to_tokens(tokens); + /// } + /// } + /// } + /// # + /// # pub struct PathSegment; + /// # + /// # impl ToTokens for PathSegment { + /// # fn to_tokens(&self, tokens: &mut TokenStream) { + /// # unimplemented!() + /// # } + /// # } + /// ``` + fn to_tokens(&self, tokens: &mut TokenStream); + + /// Convert `self` directly into a `TokenStream` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn to_token_stream(&self) -> TokenStream { + let mut tokens = TokenStream::new(); + self.to_tokens(&mut tokens); + tokens + } + + /// Convert `self` directly into a `TokenStream` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn into_token_stream(self) -> TokenStream + where + Self: Sized, + { + self.to_token_stream() + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for TokenTree { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(self.clone()); + } + + fn into_token_stream(self) -> TokenStream { + let mut builder = ConcatTreesHelper::new(1); + builder.push(self); + builder.build() + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for TokenStream { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend(self.clone()); + } + + fn into_token_stream(self) -> TokenStream { + self + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Literal { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Ident { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Punct { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Group { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for &T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for &mut T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Box { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Rc { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Cow<'_, T> { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Option { + fn to_tokens(&self, tokens: &mut TokenStream) { + if let Some(t) = self { + t.to_tokens(tokens); + } + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u8 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u8_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u16 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u16_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u32_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u64_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u128 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u128_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i8 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i8_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i16 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i16_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i32_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i64_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i128 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i128_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for f32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::f32_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for f64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::f64_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for usize { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::usize_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for isize { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::isize_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for bool { + fn to_tokens(&self, tokens: &mut TokenStream) { + let word = if *self { "true" } else { "false" }; + Ident::new(word, Span::call_site()).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for char { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::character(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for str { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::string(self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for String { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::string(self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for CStr { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::c_string(self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for CString { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::c_string(self).to_tokens(tokens) + } +} From a8261333e12bb64a4f2071a0c320d583b9f083da Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Sun, 27 Oct 2024 08:38:20 +0300 Subject: [PATCH 294/366] don't use absolute paths on `git(Some(self.src))` It will run at the project root, so resolving absolute/top-level paths is unnecessary. Signed-off-by: onur-ozkan --- src/bootstrap/src/core/build_steps/compile.rs | 2 +- src/bootstrap/src/core/config/config.rs | 9 +-------- src/bootstrap/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 27bbc8bd8ff2..893fa9f79cbf 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -135,7 +135,7 @@ impl Step for Std { !t!(helpers::git(Some(&builder.src)) .args(["diff-index", "--quiet", &closest_merge_commit]) .arg("--") - .arg(builder.src.join("library")) + .arg("library") .as_command_mut() .status()) .success() diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 087dde0d9c6b..139ca7eb52e7 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -2871,14 +2871,7 @@ impl Config { // Warn if there were changes to the compiler or standard library since the ancestor commit. let mut git = helpers::git(Some(&self.src)); - git.args(["diff-index", "--quiet", &commit, "--"]); - - // Handle running from a directory other than the top level - let top_level = &self.src; - - for path in modified_paths { - git.arg(top_level.join(path)); - } + git.args(["diff-index", "--quiet", &commit, "--"]).args(modified_paths); let has_changes = !t!(git.as_command_mut().status()).success(); if has_changes { diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index a9db0377a507..ba74cabcd306 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -541,7 +541,7 @@ impl Build { } let output = helpers::git(Some(&self.src)) .args(["config", "--file"]) - .arg(self.config.src.join(".gitmodules")) + .arg(".gitmodules") .args(["--get-regexp", "path"]) .run_capture(self) .stdout(); From 74bfa661a5abc8b485248fa7f17e1a7104dc2fb0 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Sun, 27 Oct 2024 08:55:52 +0300 Subject: [PATCH 295/366] simplify force-recompile logic for "library" Signed-off-by: onur-ozkan --- src/bootstrap/src/core/build_steps/compile.rs | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 893fa9f79cbf..e13d4ccc6182 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -15,7 +15,6 @@ use std::path::{Path, PathBuf}; use std::process::Stdio; use std::{env, fs, str}; -use build_helper::git::get_closest_merge_commit; use serde_derive::Deserialize; use crate::core::build_steps::tool::SourceType; @@ -27,7 +26,7 @@ use crate::core::builder::{ use crate::core::config::{DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection}; use crate::utils::exec::command; use crate::utils::helpers::{ - self, exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date, + exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date, }; use crate::{CLang, Compiler, DependencyType, GitRepo, LLVM_TOOLS, Mode}; @@ -125,23 +124,9 @@ impl Step for Std { // Force compilation of the standard library from source if the `library` is modified. This allows // library team to compile the standard library without needing to compile the compiler with // the `rust.download-rustc=true` option. - let force_recompile = - if builder.rust_info().is_managed_git_subrepository() && builder.download_rustc() { - let closest_merge_commit = - get_closest_merge_commit(Some(&builder.src), &builder.config.git_config(), &[]) - .unwrap(); - - // Check if `library` has changes (returns false otherwise) - !t!(helpers::git(Some(&builder.src)) - .args(["diff-index", "--quiet", &closest_merge_commit]) - .arg("--") - .arg("library") - .as_command_mut() - .status()) - .success() - } else { - false - }; + let force_recompile = builder.rust_info().is_managed_git_subrepository() + && builder.download_rustc() + && builder.config.last_modified_commit(&["library"], "download-rustc", true).is_none(); run.builder.ensure(Std { compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()), From 442f39582d2aec5026c8d75079a75f58579059e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 27 Oct 2024 06:21:24 +0100 Subject: [PATCH 296/366] Move an impl-Trait check from AST validation to AST lowering --- compiler/rustc_ast_lowering/src/path.rs | 19 ++++- compiler/rustc_ast_passes/messages.ftl | 2 - .../rustc_ast_passes/src/ast_validation.rs | 46 ------------ compiler/rustc_ast_passes/src/errors.rs | 7 -- .../src/error_codes/E0667.md | 6 +- .../src/hir_ty_lowering/mod.rs | 9 --- tests/crashes/126725.rs | 20 ------ tests/ui/impl-trait/impl_trait_projections.rs | 11 ++- .../impl-trait/impl_trait_projections.stderr | 70 +++++-------------- .../in-trait/bad-projection-from-opaque.rs | 22 ++++++ .../bad-projection-from-opaque.stderr | 11 +++ .../issues/issue-57979-impl-trait-in-path.rs | 2 +- .../issue-57979-impl-trait-in-path.stderr | 6 +- 13 files changed, 78 insertions(+), 153 deletions(-) delete mode 100644 tests/crashes/126725.rs create mode 100644 tests/ui/impl-trait/in-trait/bad-projection-from-opaque.rs create mode 100644 tests/ui/impl-trait/in-trait/bad-projection-from-opaque.stderr diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 258655de486f..6a0f03c8b319 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -34,7 +34,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { modifiers: Option, ) -> hir::QPath<'hir> { let qself_position = qself.as_ref().map(|q| q.position); - let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx)); + let qself = qself + .as_ref() + // Reject cases like `::Assoc` and `::Assoc`. + .map(|q| self.lower_ty(&q.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Path))); let partial_res = self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err)); @@ -75,6 +78,16 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { None }; + // Only permit `impl Trait` in the final segment. E.g., we permit `Option`, + // `option::Option::Xyz` and reject `option::Option::Xyz`. + let itctx = |i| { + if i + 1 == p.segments.len() { + itctx + } else { + ImplTraitContext::Disallowed(ImplTraitPosition::Path) + } + }; + let path_span_lo = p.span.shrink_to_lo(); let proj_start = p.segments.len() - unresolved_segments; let path = self.arena.alloc(hir::Path { @@ -121,7 +134,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { segment, param_mode, generic_args_mode, - itctx, + itctx(i), bound_modifier_allowed_features.clone(), ) }, @@ -185,7 +198,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { segment, param_mode, generic_args_mode, - itctx, + itctx(i), None, )); let qpath = hir::QPath::TypeRelative(ty, hir_segment); diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index 92acaaa5f36b..d81fd53938b8 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -146,8 +146,6 @@ ast_passes_generic_before_constraints = generic arguments must come before the f ast_passes_generic_default_trailing = generic parameters with a default must be trailing -ast_passes_impl_trait_path = `impl Trait` is not allowed in path parameters - ast_passes_incompatible_features = `{$f1}` and `{$f2}` are incompatible, using them at the same time is not allowed .help = remove one of these features diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index bf6ebfb160bc..485d84b0b6dd 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -80,10 +80,6 @@ struct AstValidator<'a> { disallow_tilde_const: Option, - /// Used to ban `impl Trait` in path projections like `::Item` - /// or `Foo::Bar` - is_impl_trait_banned: bool, - /// Used to ban explicit safety on foreign items when the extern block is not marked as unsafe. extern_mod_safety: Option, @@ -123,12 +119,6 @@ impl<'a> AstValidator<'a> { self.extern_mod_safety = old; } - fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) { - let old = mem::replace(&mut self.is_impl_trait_banned, true); - f(self); - self.is_impl_trait_banned = old; - } - fn with_tilde_const( &mut self, disallowed: Option, @@ -213,37 +203,6 @@ impl<'a> AstValidator<'a> { .with_tilde_const(Some(TildeConstReason::TraitObject), |this| { visit::walk_ty(this, t) }), - TyKind::Path(qself, path) => { - // We allow these: - // - `Option` - // - `option::Option` - // - `option::Option::Foo` - // - // But not these: - // - `::Foo` - // - `option::Option::Foo`. - // - // To implement this, we disallow `impl Trait` from `qself` - // (for cases like `::Foo>`) - // but we allow `impl Trait` in `GenericArgs` - // iff there are no more PathSegments. - if let Some(qself) = qself { - // `impl Trait` in `qself` is always illegal - self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty)); - } - - // Note that there should be a call to visit_path here, - // so if any logic is added to process `Path`s a call to it should be - // added both in visit_path and here. This code mirrors visit::walk_path. - for (i, segment) in path.segments.iter().enumerate() { - // Allow `impl Trait` iff we're on the final path segment - if i == path.segments.len() - 1 { - self.visit_path_segment(segment); - } else { - self.with_banned_impl_trait(|this| this.visit_path_segment(segment)); - } - } - } _ => visit::walk_ty(self, t), } } @@ -737,10 +696,6 @@ impl<'a> AstValidator<'a> { } } TyKind::ImplTrait(_, bounds) => { - if self.is_impl_trait_banned { - self.dcx().emit_err(errors::ImplTraitPath { span: ty.span }); - } - if let Some(outer_impl_trait_sp) = self.outer_impl_trait { self.dcx().emit_err(errors::NestedImplTrait { span: ty.span, @@ -1729,7 +1684,6 @@ pub fn check_crate( has_proc_macro_decls: false, outer_impl_trait: None, disallow_tilde_const: Some(TildeConstReason::Item), - is_impl_trait_banned: false, extern_mod_safety: None, lint_buffer: lints, }; diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 4ca1acde1e28..8c3ac9864ed8 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -418,13 +418,6 @@ pub(crate) struct TraitObjectBound { pub span: Span, } -#[derive(Diagnostic)] -#[diag(ast_passes_impl_trait_path, code = E0667)] -pub(crate) struct ImplTraitPath { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag(ast_passes_nested_impl_trait, code = E0666)] pub(crate) struct NestedImplTrait { diff --git a/compiler/rustc_error_codes/src/error_codes/E0667.md b/compiler/rustc_error_codes/src/error_codes/E0667.md index 0709a24c4331..339bc0686103 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0667.md +++ b/compiler/rustc_error_codes/src/error_codes/E0667.md @@ -1,8 +1,10 @@ +#### Note: this error code is no longer emitted by the compiler. + `impl Trait` is not allowed in path parameters. Erroneous code example: -```compile_fail,E0667 +```ignore (removed error code) fn some_fn(mut x: impl Iterator) -> ::Item { // error! x.next().unwrap() } @@ -11,7 +13,7 @@ fn some_fn(mut x: impl Iterator) -> ::Item { // error! You cannot use `impl Trait` in path parameters. If you want something equivalent, you can do this instead: -``` +```ignore (removed error code) fn some_fn(mut x: T) -> T::Item { // ok! x.next().unwrap() } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 863c077a9e03..cfd1241ad69c 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -1203,15 +1203,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { err.emit() } else if let Err(reported) = qself_ty.error_reported() { reported - } else if let ty::Alias(ty::Opaque, alias_ty) = qself_ty.kind() { - // `::Assoc` makes no sense. - struct_span_code_err!( - self.dcx(), - tcx.def_span(alias_ty.def_id), - E0667, - "`impl Trait` is not allowed in path parameters" - ) - .emit() // Already reported in an earlier stage. } else { self.maybe_report_similar_assoc_fn(span, qself_ty, qself)?; diff --git a/tests/crashes/126725.rs b/tests/crashes/126725.rs deleted file mode 100644 index d7a7d21ae424..000000000000 --- a/tests/crashes/126725.rs +++ /dev/null @@ -1,20 +0,0 @@ -//@ known-bug: rust-lang/rust#126725 -trait Foo { - fn foo<'a>(&'a self) -> <&'a impl Sized as Bar>::Output; -} - -trait Bar { - type Output; -} - -struct X(i32); - -impl<'a> Bar for &'a X { - type Output = &'a i32; -} - -impl Foo for X { - fn foo<'a>(&'a self) -> <&'a Self as Bar>::Output { - &self.0 - } -} diff --git a/tests/ui/impl-trait/impl_trait_projections.rs b/tests/ui/impl-trait/impl_trait_projections.rs index 365ac85e2f66..2c277aee06da 100644 --- a/tests/ui/impl-trait/impl_trait_projections.rs +++ b/tests/ui/impl-trait/impl_trait_projections.rs @@ -10,30 +10,27 @@ fn path_parametrized_type_is_allowed() -> option::Option { } fn projection_is_disallowed(x: impl Iterator) -> ::Item { -//~^ ERROR `impl Trait` is not allowed in path parameters -//~| ERROR `impl Trait` is not allowed in path parameters +//~^ ERROR `impl Trait` is not allowed in paths x.next().unwrap() } fn projection_with_named_trait_is_disallowed(mut x: impl Iterator) -> ::Item -//~^ ERROR `impl Trait` is not allowed in path parameters +//~^ ERROR `impl Trait` is not allowed in paths { x.next().unwrap() } fn projection_with_named_trait_inside_path_is_disallowed() -> <::std::ops::Range as Iterator>::Item -//~^ ERROR `impl Trait` is not allowed in path parameters -//~| ERROR `impl Debug: Step` is not satisfied +//~^ ERROR `impl Trait` is not allowed in paths { - //~^ ERROR `impl Debug: Step` is not satisfied (1i32..100).next().unwrap() } fn projection_from_impl_trait_inside_dyn_trait_is_disallowed() -> as Iterator>::Item -//~^ ERROR `impl Trait` is not allowed in path parameters +//~^ ERROR `impl Trait` is not allowed in paths { panic!() } diff --git a/tests/ui/impl-trait/impl_trait_projections.stderr b/tests/ui/impl-trait/impl_trait_projections.stderr index d62e3ac4183f..5e0b80fcd592 100644 --- a/tests/ui/impl-trait/impl_trait_projections.stderr +++ b/tests/ui/impl-trait/impl_trait_projections.stderr @@ -1,73 +1,35 @@ -error[E0667]: `impl Trait` is not allowed in path parameters +error[E0562]: `impl Trait` is not allowed in paths --> $DIR/impl_trait_projections.rs:12:51 | LL | fn projection_is_disallowed(x: impl Iterator) -> ::Item { | ^^^^^^^^^^^^^ + | + = note: `impl Trait` is only allowed in arguments and return types of functions and methods -error[E0667]: `impl Trait` is not allowed in path parameters - --> $DIR/impl_trait_projections.rs:19:9 +error[E0562]: `impl Trait` is not allowed in paths + --> $DIR/impl_trait_projections.rs:18:9 | LL | -> ::Item | ^^^^^^^^^^^^^ + | + = note: `impl Trait` is only allowed in arguments and return types of functions and methods -error[E0667]: `impl Trait` is not allowed in path parameters - --> $DIR/impl_trait_projections.rs:26:27 +error[E0562]: `impl Trait` is not allowed in paths + --> $DIR/impl_trait_projections.rs:25:27 | LL | -> <::std::ops::Range as Iterator>::Item | ^^^^^^^^^^ + | + = note: `impl Trait` is only allowed in arguments and return types of functions and methods -error[E0667]: `impl Trait` is not allowed in path parameters - --> $DIR/impl_trait_projections.rs:35:29 +error[E0562]: `impl Trait` is not allowed in paths + --> $DIR/impl_trait_projections.rs:32:29 | LL | -> as Iterator>::Item | ^^^^^^^^^^ - -error[E0667]: `impl Trait` is not allowed in path parameters - --> $DIR/impl_trait_projections.rs:12:51 | -LL | fn projection_is_disallowed(x: impl Iterator) -> ::Item { - | ^^^^^^^^^^^^^ + = note: `impl Trait` is only allowed in arguments and return types of functions and methods -error[E0277]: the trait bound `impl Debug: Step` is not satisfied - --> $DIR/impl_trait_projections.rs:26:8 - | -LL | -> <::std::ops::Range as Iterator>::Item - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Step` is not implemented for `impl Debug`, which is required by `std::ops::Range: Iterator` - | - = help: the following other types implement trait `Step`: - Char - Ipv4Addr - Ipv6Addr - char - i128 - i16 - i32 - i64 - and 8 others - = note: required for `std::ops::Range` to implement `Iterator` +error: aborting due to 4 previous errors -error[E0277]: the trait bound `impl Debug: Step` is not satisfied - --> $DIR/impl_trait_projections.rs:29:1 - | -LL | / { -LL | | -LL | | (1i32..100).next().unwrap() -LL | | } - | |_^ the trait `Step` is not implemented for `impl Debug`, which is required by `std::ops::Range: Iterator` - | - = help: the following other types implement trait `Step`: - Char - Ipv4Addr - Ipv6Addr - char - i128 - i16 - i32 - i64 - and 8 others - = note: required for `std::ops::Range` to implement `Iterator` - -error: aborting due to 7 previous errors - -Some errors have detailed explanations: E0277, E0667. -For more information about an error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0562`. diff --git a/tests/ui/impl-trait/in-trait/bad-projection-from-opaque.rs b/tests/ui/impl-trait/in-trait/bad-projection-from-opaque.rs new file mode 100644 index 000000000000..c2c22cd1abfc --- /dev/null +++ b/tests/ui/impl-trait/in-trait/bad-projection-from-opaque.rs @@ -0,0 +1,22 @@ +// issue: rust-lang/rust#126725 + +trait Foo { + fn foo<'a>() -> <&'a impl Sized as Bar>::Output; + //~^ ERROR `impl Trait` is not allowed in paths +} + +trait Bar { + type Output; +} + +impl<'a> Bar for &'a () { + type Output = &'a i32; +} + +impl Foo for () { + fn foo<'a>() -> <&'a Self as Bar>::Output { + &0 + } +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/bad-projection-from-opaque.stderr b/tests/ui/impl-trait/in-trait/bad-projection-from-opaque.stderr new file mode 100644 index 000000000000..bea7ccd1a18d --- /dev/null +++ b/tests/ui/impl-trait/in-trait/bad-projection-from-opaque.stderr @@ -0,0 +1,11 @@ +error[E0562]: `impl Trait` is not allowed in paths + --> $DIR/bad-projection-from-opaque.rs:4:26 + | +LL | fn foo<'a>() -> <&'a impl Sized as Bar>::Output; + | ^^^^^^^^^^ + | + = note: `impl Trait` is only allowed in arguments and return types of functions and methods + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0562`. diff --git a/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.rs b/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.rs index c5ecd1caae1f..9466668b1dcd 100644 --- a/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.rs +++ b/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.rs @@ -6,7 +6,7 @@ pub trait Bar { } pub trait Quux { type Assoc; } pub fn demo(_: impl Quux<(), Assoc=<() as Quux>::Assoc>) { } -//~^ ERROR `impl Trait` is not allowed in path parameters +//~^ ERROR `impl Trait` is not allowed in paths impl Quux for () { type Assoc = u32; } fn main() { } diff --git a/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.stderr b/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.stderr index 55f47785f0ee..25547dfa66f5 100644 --- a/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.stderr +++ b/tests/ui/impl-trait/issues/issue-57979-impl-trait-in-path.stderr @@ -1,9 +1,11 @@ -error[E0667]: `impl Trait` is not allowed in path parameters +error[E0562]: `impl Trait` is not allowed in paths --> $DIR/issue-57979-impl-trait-in-path.rs:8:48 | LL | pub fn demo(_: impl Quux<(), Assoc=<() as Quux>::Assoc>) { } | ^^^^^^^^ + | + = note: `impl Trait` is only allowed in arguments and return types of functions and methods error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0667`. +For more information about this error, try `rustc --explain E0562`. From e970e07e105eb805161387494d8521d5453b70b1 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 27 Oct 2024 10:46:49 +0200 Subject: [PATCH 297/366] Support `cfg(true)` and `cfg(false)` As per RFC 3695. --- src/tools/rust-analyzer/Cargo.lock | 1 + src/tools/rust-analyzer/crates/cfg/Cargo.toml | 1 + src/tools/rust-analyzer/crates/cfg/src/lib.rs | 32 +++++++++++++++---- .../ide-completion/src/tests/attribute.rs | 2 ++ .../src/handlers/inactive_code.rs | 16 ++++++++++ .../cargo_hello_world_project_model.txt | 6 ++++ ...project_model_with_selective_overrides.txt | 6 ++++ ..._project_model_with_wildcard_overrides.txt | 6 ++++ .../output/rust_project_cfg_groups.txt | 12 +++++++ ...rust_project_hello_world_project_model.txt | 11 +++++++ 10 files changed, 87 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index 8bbccc82aee2..0313de976ed5 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -164,6 +164,7 @@ dependencies = [ "rustc-hash 2.0.0", "syntax", "syntax-bridge", + "tracing", "tt", ] diff --git a/src/tools/rust-analyzer/crates/cfg/Cargo.toml b/src/tools/rust-analyzer/crates/cfg/Cargo.toml index 29b7ad6f8fe2..040bddbd7fd3 100644 --- a/src/tools/rust-analyzer/crates/cfg/Cargo.toml +++ b/src/tools/rust-analyzer/crates/cfg/Cargo.toml @@ -14,6 +14,7 @@ doctest = false [dependencies] rustc-hash.workspace = true +tracing.workspace = true # locals deps tt = { workspace = true, optional = true } diff --git a/src/tools/rust-analyzer/crates/cfg/src/lib.rs b/src/tools/rust-analyzer/crates/cfg/src/lib.rs index c2d400860561..6a6213a871fd 100644 --- a/src/tools/rust-analyzer/crates/cfg/src/lib.rs +++ b/src/tools/rust-analyzer/crates/cfg/src/lib.rs @@ -9,7 +9,7 @@ use std::fmt; use rustc_hash::FxHashSet; -use intern::Symbol; +use intern::{sym, Symbol}; pub use cfg_expr::{CfgAtom, CfgExpr}; pub use dnf::DnfExpr; @@ -24,11 +24,17 @@ pub use dnf::DnfExpr; /// of key and value in `key_values`. /// /// See: -#[derive(Clone, PartialEq, Eq, Default)] +#[derive(Clone, PartialEq, Eq)] pub struct CfgOptions { enabled: FxHashSet, } +impl Default for CfgOptions { + fn default() -> Self { + Self { enabled: FxHashSet::from_iter([CfgAtom::Flag(sym::true_.clone())]) } + } +} + impl fmt::Debug for CfgOptions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut items = self @@ -54,23 +60,37 @@ impl CfgOptions { } pub fn insert_atom(&mut self, key: Symbol) { - self.enabled.insert(CfgAtom::Flag(key)); + self.insert_any_atom(CfgAtom::Flag(key)); } pub fn insert_key_value(&mut self, key: Symbol, value: Symbol) { - self.enabled.insert(CfgAtom::KeyValue { key, value }); + self.insert_any_atom(CfgAtom::KeyValue { key, value }); } pub fn apply_diff(&mut self, diff: CfgDiff) { for atom in diff.enable { - self.enabled.insert(atom); + self.insert_any_atom(atom); } for atom in diff.disable { + let (CfgAtom::Flag(sym) | CfgAtom::KeyValue { key: sym, .. }) = &atom; + if *sym == sym::true_ || *sym == sym::false_ { + tracing::error!("cannot remove `true` or `false` from cfg"); + continue; + } self.enabled.remove(&atom); } } + fn insert_any_atom(&mut self, atom: CfgAtom) { + let (CfgAtom::Flag(sym) | CfgAtom::KeyValue { key: sym, .. }) = &atom; + if *sym == sym::true_ || *sym == sym::false_ { + tracing::error!("cannot insert `true` or `false` to cfg"); + return; + } + self.enabled.insert(atom); + } + pub fn get_cfg_keys(&self) -> impl Iterator { self.enabled.iter().map(|it| match it { CfgAtom::Flag(key) => key, @@ -88,7 +108,7 @@ impl CfgOptions { impl Extend for CfgOptions { fn extend>(&mut self, iter: T) { - iter.into_iter().for_each(|cfg_flag| _ = self.enabled.insert(cfg_flag)); + iter.into_iter().for_each(|cfg_flag| self.insert_any_atom(cfg_flag)); } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/tests/attribute.rs b/src/tools/rust-analyzer/crates/ide-completion/src/tests/attribute.rs index 1bbe097cc6c8..45679355b427 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/tests/attribute.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/tests/attribute.rs @@ -663,6 +663,7 @@ mod cfg { ba dbg ba opt_level ba test + ba true "#]], ); check( @@ -674,6 +675,7 @@ mod cfg { ba dbg ba opt_level ba test + ba true "#]], ); } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/inactive_code.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/inactive_code.rs index 1f8f805a1e29..4c0c685e5503 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/inactive_code.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/inactive_code.rs @@ -192,6 +192,22 @@ union FooBar { //- /outline_inner.rs #![cfg(outline_inner)] //- /outline.rs +"#, + ); + } + + #[test] + fn cfg_true_false() { + check( + r#" + #[cfg(false)] fn inactive() {} +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ weak: code is inactive due to #[cfg] directives: false is disabled + + #[cfg(true)] fn active() {} + + #[cfg(any(not(true)), false)] fn inactive2() {} +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ weak: code is inactive due to #[cfg] directives: true is enabled + "#, ); } diff --git a/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model.txt b/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model.txt index 3401d7f7e47f..880e90c52a54 100644 --- a/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model.txt +++ b/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model.txt @@ -19,6 +19,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -81,6 +82,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -151,6 +153,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -221,6 +224,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -291,6 +295,7 @@ [ "feature=default", "feature=std", + "true", ], ), potential_cfg_options: Some( @@ -303,6 +308,7 @@ "feature=rustc-dep-of-std", "feature=std", "feature=use_std", + "true", ], ), ), diff --git a/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt b/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt index 3401d7f7e47f..880e90c52a54 100644 --- a/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt +++ b/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt @@ -19,6 +19,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -81,6 +82,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -151,6 +153,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -221,6 +224,7 @@ [ "rust_analyzer", "test", + "true", ], ), potential_cfg_options: None, @@ -291,6 +295,7 @@ [ "feature=default", "feature=std", + "true", ], ), potential_cfg_options: Some( @@ -303,6 +308,7 @@ "feature=rustc-dep-of-std", "feature=std", "feature=use_std", + "true", ], ), ), diff --git a/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt b/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt index 491568d4b756..7746acd225e3 100644 --- a/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt +++ b/src/tools/rust-analyzer/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt @@ -18,6 +18,7 @@ cfg_options: CfgOptions( [ "rust_analyzer", + "true", ], ), potential_cfg_options: None, @@ -79,6 +80,7 @@ cfg_options: CfgOptions( [ "rust_analyzer", + "true", ], ), potential_cfg_options: None, @@ -148,6 +150,7 @@ cfg_options: CfgOptions( [ "rust_analyzer", + "true", ], ), potential_cfg_options: None, @@ -217,6 +220,7 @@ cfg_options: CfgOptions( [ "rust_analyzer", + "true", ], ), potential_cfg_options: None, @@ -287,6 +291,7 @@ [ "feature=default", "feature=std", + "true", ], ), potential_cfg_options: Some( @@ -299,6 +304,7 @@ "feature=rustc-dep-of-std", "feature=std", "feature=use_std", + "true", ], ), ), diff --git a/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_cfg_groups.txt b/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_cfg_groups.txt index 8261e5a2d907..90f41a9c2fc8 100644 --- a/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_cfg_groups.txt +++ b/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_cfg_groups.txt @@ -17,6 +17,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -56,6 +57,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -86,6 +88,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -116,6 +119,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -146,6 +150,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -193,6 +198,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -223,6 +229,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -318,6 +325,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -348,6 +356,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -378,6 +387,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -410,6 +420,7 @@ "group1_other_cfg=other_config", "group2_cfg=yet_another_config", "rust_analyzer", + "true", ], ), potential_cfg_options: None, @@ -485,6 +496,7 @@ "group2_cfg=fourth_config", "group2_cfg=yet_another_config", "rust_analyzer", + "true", "unrelated_cfg", ], ), diff --git a/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt b/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt index c123df80a6a3..a0e14b8fcb22 100644 --- a/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt +++ b/src/tools/rust-analyzer/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt @@ -17,6 +17,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -56,6 +57,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -86,6 +88,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -116,6 +119,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -146,6 +150,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -193,6 +198,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -223,6 +229,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -318,6 +325,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -348,6 +356,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -378,6 +387,7 @@ [ "debug_assertions", "miri", + "true", ], ), potential_cfg_options: None, @@ -407,6 +417,7 @@ cfg_options: CfgOptions( [ "rust_analyzer", + "true", ], ), potential_cfg_options: None, From c50bfda34f6559211688957d50a21207f46fdcb5 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 27 Oct 2024 11:26:45 +0100 Subject: [PATCH 298/366] Add GUI regression test for doc struct fields margins --- tests/rustdoc-gui/fields.goml | 49 +++++++++++++++++++++++----- tests/rustdoc-gui/struct-fields.goml | 3 +- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/tests/rustdoc-gui/fields.goml b/tests/rustdoc-gui/fields.goml index b8139a2edac1..5d13d7be2f97 100644 --- a/tests/rustdoc-gui/fields.goml +++ b/tests/rustdoc-gui/fields.goml @@ -1,13 +1,36 @@ -// This test checks that fields are displayed as expected (one by line). -go-to: "file://" + |DOC_PATH| + "/test_docs/fields/struct.Struct.html" -store-position: ("#structfield\.a", {"y": a_y}) -store-position: ("#structfield\.b", {"y": b_y}) -assert: |a_y| < |b_y| +// This test checks that fields are displayed as expected (one by line) and they are surrounded +// by margins. -go-to: "file://" + |DOC_PATH| + "/test_docs/fields/union.Union.html" -store-position: ("#structfield\.a", {"y": a_y}) -store-position: ("#structfield\.b", {"y": b_y}) -assert: |a_y| < |b_y| +define-function: ( + "check-fields", + [path, selector_1, selector_2], + block { + go-to: "file://" + |DOC_PATH| + "/test_docs/fields/" + |path| + store-position: (|selector_1|, {"y": a_y}) + store-position: (|selector_2|, {"y": b_y}) + assert: |a_y| < |b_y| + + // Check the margins. + assert-css: (".structfield.section-header", { + "margin-top": "9.6px", + "margin-bottom": "9.6px", + "margin-left": "0px", + "margin-right": "0px", + }, ALL) + } +) + +call-function: ("check-fields", { + "path": "struct.Struct.html", + "selector_1": "#structfield\.a", + "selector_2": "#structfield\.b", +}) + +call-function: ("check-fields", { + "path": "union.Union.html", + "selector_1": "#structfield\.a", + "selector_2": "#structfield\.b", +}) go-to: "file://" + |DOC_PATH| + "/test_docs/fields/enum.Enum.html" store-position: ("#variant\.A\.field\.a", {"y": a_y}) @@ -16,3 +39,11 @@ assert: |a_y| < |b_y| store-position: ("#variant\.B\.field\.a", {"y": a_y}) store-position: ("#variant\.B\.field\.b", {"y": b_y}) assert: |a_y| < |b_y| + +// Check the margins. +assert-css: (".sub-variant-field .section-header", { + "margin-top": "0px", + "margin-bottom": "0px", + "margin-left": "0px", + "margin-right": "0px", +}, ALL) diff --git a/tests/rustdoc-gui/struct-fields.goml b/tests/rustdoc-gui/struct-fields.goml index 3c87a4cd6542..302a1a0d80bf 100644 --- a/tests/rustdoc-gui/struct-fields.goml +++ b/tests/rustdoc-gui/struct-fields.goml @@ -1,4 +1,5 @@ -// This test ensures that each field is on its own line (In other words, they have display: block). +// This test ensures that each field is on its own line (In other words, they have +// `display: block`). go-to: "file://" + |DOC_PATH| + "/test_docs/struct.StructWithPublicUndocumentedFields.html" store-property: ("//*[@id='structfield.first']", {"offsetTop": first_top}) From 6c70806b3106277e6ab9f34da49923e6cb111626 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 25 Oct 2024 13:29:07 +0200 Subject: [PATCH 299/366] Invert token iteration order in macro mapping --- .../rust-analyzer/crates/hir/src/semantics.rs | 4 +++ .../rust-analyzer/crates/ide-db/src/lib.rs | 6 +++-- .../crates/ide/src/call_hierarchy.rs | 5 ++-- .../rust-analyzer/crates/ide/src/hover.rs | 2 +- .../crates/ide/src/hover/tests.rs | 26 +++++++++---------- .../crates/ide/src/references.rs | 10 +++---- .../crates/ide/src/syntax_highlighting.rs | 3 ++- .../test_data/highlight_issue_18089.html | 2 +- 8 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index 860754d5e704..592a4b4853d5 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -954,6 +954,10 @@ impl<'db> SemanticsImpl<'db> { }; while let Some((expansion, ref mut tokens)) = stack.pop() { + // Reverse the tokens so we prefer first tokens (to accommodate for popping from the + // back) + // alternatively we could pop from the front but that would shift the content on every pop + tokens.reverse(); while let Some((token, ctx)) = tokens.pop() { let was_not_remapped = (|| { // First expand into attribute invocations diff --git a/src/tools/rust-analyzer/crates/ide-db/src/lib.rs b/src/tools/rust-analyzer/crates/ide-db/src/lib.rs index b7b133ac10ea..b764f852f048 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/lib.rs @@ -301,6 +301,8 @@ pub struct Ranker<'a> { } impl<'a> Ranker<'a> { + pub const MAX_RANK: usize = 0b1110; + pub fn from_token(token: &'a syntax::SyntaxToken) -> Self { let kind = token.kind(); Ranker { kind, text: token.text(), ident_kind: kind.is_any_identifier() } @@ -317,9 +319,9 @@ impl<'a> Ranker<'a> { // anything that mapped into a token tree has likely no semantic information let no_tt_parent = tok.parent().map_or(false, |it| it.kind() != parser::SyntaxKind::TOKEN_TREE); - !((both_idents as usize) + (both_idents as usize) | ((exact_same_kind as usize) << 1) | ((same_text as usize) << 2) - | ((no_tt_parent as usize) << 3)) + | ((no_tt_parent as usize) << 3) } } diff --git a/src/tools/rust-analyzer/crates/ide/src/call_hierarchy.rs b/src/tools/rust-analyzer/crates/ide/src/call_hierarchy.rs index 1b82c00d1dc0..e5b4ed17b2a4 100644 --- a/src/tools/rust-analyzer/crates/ide/src/call_hierarchy.rs +++ b/src/tools/rust-analyzer/crates/ide/src/call_hierarchy.rs @@ -510,6 +510,7 @@ fn caller$0() { expect![[]], ); } + #[test] fn test_call_hierarchy_in_macros_incoming_different_files() { check_hierarchy( @@ -591,9 +592,9 @@ macro_rules! call { "#, expect!["callee Function FileId(0) 22..37 30..36"], expect![[r#" - callee Function FileId(0) 38..52 44..50 : FileId(0):44..50 caller Function FileId(0) 38..52 : FileId(0):44..50 - caller Function FileId(1) 130..136 130..136 : FileId(0):44..50"#]], + caller Function FileId(1) 130..136 130..136 : FileId(0):44..50 + callee Function FileId(0) 38..52 44..50 : FileId(0):44..50"#]], expect![[]], ); } diff --git a/src/tools/rust-analyzer/crates/ide/src/hover.rs b/src/tools/rust-analyzer/crates/ide/src/hover.rs index 91ec672febac..6cac4f1ee489 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover.rs @@ -184,7 +184,7 @@ fn hover_offset( let ranker = Ranker::from_token(&original_token); - descended.sort_by_cached_key(|tok| ranker.rank_token(tok)); + descended.sort_by_cached_key(|tok| !ranker.rank_token(tok)); let mut res = vec![]; for token in descended { diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs index ef835f5bef8d..3e4026304195 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs @@ -288,19 +288,6 @@ m!(ab$0c); expect![[r#" *abc* - ```rust - test::module - ``` - - ```rust - fn abc() - ``` - - --- - - Inner - --- - ```rust test ``` @@ -312,6 +299,19 @@ m!(ab$0c); --- Outer + --- + + ```rust + test::module + ``` + + ```rust + fn abc() + ``` + + --- + + Inner "#]], ); } diff --git a/src/tools/rust-analyzer/crates/ide/src/references.rs b/src/tools/rust-analyzer/crates/ide/src/references.rs index e7cb8a253f40..339315db5710 100644 --- a/src/tools/rust-analyzer/crates/ide/src/references.rs +++ b/src/tools/rust-analyzer/crates/ide/src/references.rs @@ -1701,14 +1701,14 @@ fn f() { } "#, expect![[r#" - func Function FileId(0) 137..146 140..144 - - FileId(0) 161..165 - - func Function FileId(0) 137..146 140..144 module FileId(0) 181..185 + + + func Function FileId(0) 137..146 140..144 + + FileId(0) 161..165 "#]], ) } diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs index 54d5307adff1..0747d1b404b4 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs @@ -397,6 +397,7 @@ fn traverse( Some(AttrOrDerive::Derive(_)) => inside_attribute, None => false, }; + let descended_element = if in_macro { // Attempt to descend tokens into macro-calls. let res = match element { @@ -412,7 +413,7 @@ fn traverse( let tok = tok.value; let my_rank = ranker.rank_token(&tok); - if my_rank > 0b1110 { + if my_rank >= Ranker::MAX_RANK { // a rank of 0b1110 means that we have found a maximally interesting // token so stop early. t = Some(tok); diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_issue_18089.html b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_issue_18089.html index d07ba74db249..361dcd1bc37c 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_issue_18089.html +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_issue_18089.html @@ -50,4 +50,4 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd } #[proc_macros::issue_18089] -fn template() {}
\ No newline at end of file +fn template() {} \ No newline at end of file From f50b201c865c5883f254c46c162ffffe3b2171da Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 27 Oct 2024 05:08:49 +0200 Subject: [PATCH 300/366] Put leading `|` in patterns under `OrPat` Previously it was one level above, and that caused problems with macros that expand to it, because macros expect to get only one top-level node. --- .../crates/hir-def/src/body/lower.rs | 4 +++ .../src/handlers/unmerge_match_arm.rs | 3 ++ .../crates/parser/src/grammar/patterns.rs | 13 ++++---- .../crates/parser/src/tests/top_entries.rs | 32 +++++++++++++++++++ .../test_data/parser/inline/ok/match_arm.rast | 15 +++++---- .../test_data/parser/inline/ok/slice_pat.rast | 11 ++++--- .../test_data/parser/inline/ok/tuple_pat.rast | 15 +++++---- .../parser/inline/ok/tuple_pat_fields.rast | 11 ++++--- .../rust-analyzer/crates/syntax/rust.ungram | 2 +- .../crates/syntax/src/ast/generated/nodes.rs | 2 ++ .../crates/syntax/src/ast/node_ext.rs | 10 ++++++ 11 files changed, 87 insertions(+), 31 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs index b87e94f9c51d..6117664c64c8 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs @@ -1598,6 +1598,10 @@ impl ExprCollector<'_> { for (id, _) in current_is_used.into_iter() { binding_list.check_is_used(self, id); } + if let &[pat] = &*pats { + // Leading pipe without real OR pattern. Leaving an one-item OR pattern may confuse later stages. + return pat; + } Pat::Or(pats.into()) } ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat(), binding_list), diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unmerge_match_arm.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unmerge_match_arm.rs index db789cfa3342..648bf358b4bb 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unmerge_match_arm.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unmerge_match_arm.rs @@ -34,6 +34,9 @@ use crate::{AssistContext, AssistId, AssistKind, Assists}; pub(crate) fn unmerge_match_arm(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let pipe_token = ctx.find_token_syntax_at_offset(T![|])?; let or_pat = ast::OrPat::cast(pipe_token.parent()?)?.clone_for_update(); + if or_pat.leading_pipe().is_some_and(|it| it == pipe_token) { + return None; + } let match_arm = ast::MatchArm::cast(or_pat.syntax().parent()?)?; let match_arm_body = match_arm.expr()?; diff --git a/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs b/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs index 3db1a10ca5ce..ed01fca2acdb 100644 --- a/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs +++ b/src/tools/rust-analyzer/crates/parser/src/grammar/patterns.rs @@ -21,7 +21,8 @@ const RANGE_PAT_END_FIRST: TokenSet = expressions::LITERAL_FIRST.union(paths::PATH_FIRST).union(TokenSet::new(&[T![-], T![const]])); pub(crate) fn pattern(p: &mut Parser<'_>) { - pattern_r(p, PAT_RECOVERY_SET); + let m = p.start(); + pattern_r(p, m, false, PAT_RECOVERY_SET); } /// Parses a pattern list separated by pipes `|`. @@ -36,8 +37,9 @@ pub(crate) fn pattern_single(p: &mut Parser<'_>) { /// Parses a pattern list separated by pipes `|` /// using the given `recovery_set`. pub(super) fn pattern_top_r(p: &mut Parser<'_>, recovery_set: TokenSet) { - p.eat(T![|]); - pattern_r(p, recovery_set); + let m = p.start(); + let has_leading_pipe = p.eat(T![|]); + pattern_r(p, m, has_leading_pipe, recovery_set); } // test or_pattern @@ -51,11 +53,10 @@ pub(super) fn pattern_top_r(p: &mut Parser<'_>, recovery_set: TokenSet) { // } /// Parses a pattern list separated by pipes `|`, with no leading `|`,using the /// given `recovery_set`. -fn pattern_r(p: &mut Parser<'_>, recovery_set: TokenSet) { - let m = p.start(); +fn pattern_r(p: &mut Parser<'_>, m: Marker, has_leading_pipe: bool, recovery_set: TokenSet) { pattern_single_r(p, recovery_set); - if !p.at(T![|]) { + if !p.at(T![|]) && !has_leading_pipe { m.abandon(p); return; } diff --git a/src/tools/rust-analyzer/crates/parser/src/tests/top_entries.rs b/src/tools/rust-analyzer/crates/parser/src/tests/top_entries.rs index c56bf0b64485..7076e03ba4b9 100644 --- a/src/tools/rust-analyzer/crates/parser/src/tests/top_entries.rs +++ b/src/tools/rust-analyzer/crates/parser/src/tests/top_entries.rs @@ -195,6 +195,38 @@ fn macro_pattern() { error 0: expected pattern "#]], ); + + check( + TopEntryPoint::Pattern, + "| 42 | 43", + expect![[r#" + OR_PAT + PIPE "|" + WHITESPACE " " + LITERAL_PAT + LITERAL + INT_NUMBER "42" + WHITESPACE " " + PIPE "|" + WHITESPACE " " + LITERAL_PAT + LITERAL + INT_NUMBER "43" + "#]], + ); + + check( + TopEntryPoint::Pattern, + "| 42", + expect![[r#" + OR_PAT + PIPE "|" + WHITESPACE " " + LITERAL_PAT + LITERAL + INT_NUMBER "42" + "#]], + ); } #[test] diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/match_arm.rast b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/match_arm.rast index 8189cf0a8e51..922102816292 100644 --- a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/match_arm.rast +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/match_arm.rast @@ -102,9 +102,9 @@ SOURCE_FILE COMMA "," WHITESPACE "\n " MATCH_ARM - PIPE "|" - WHITESPACE " " OR_PAT + PIPE "|" + WHITESPACE " " IDENT_PAT NAME IDENT "X" @@ -132,11 +132,12 @@ SOURCE_FILE COMMA "," WHITESPACE "\n " MATCH_ARM - PIPE "|" - WHITESPACE " " - IDENT_PAT - NAME - IDENT "X" + OR_PAT + PIPE "|" + WHITESPACE " " + IDENT_PAT + NAME + IDENT "X" WHITESPACE " " FAT_ARROW "=>" WHITESPACE " " diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/slice_pat.rast b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/slice_pat.rast index dff72ba886fe..06c30bba59f6 100644 --- a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/slice_pat.rast +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/slice_pat.rast @@ -43,11 +43,12 @@ SOURCE_FILE WHITESPACE " " SLICE_PAT L_BRACK "[" - PIPE "|" - WHITESPACE " " - IDENT_PAT - NAME - IDENT "a" + OR_PAT + PIPE "|" + WHITESPACE " " + IDENT_PAT + NAME + IDENT "a" COMMA "," WHITESPACE " " REST_PAT diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat.rast b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat.rast index 1a01e0f69381..c7cd11f774b6 100644 --- a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat.rast +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat.rast @@ -91,9 +91,9 @@ SOURCE_FILE WHITESPACE " " TUPLE_PAT L_PAREN "(" - PIPE "|" - WHITESPACE " " OR_PAT + PIPE "|" + WHITESPACE " " IDENT_PAT NAME IDENT "a" @@ -105,11 +105,12 @@ SOURCE_FILE IDENT "a" COMMA "," WHITESPACE " " - PIPE "|" - WHITESPACE " " - IDENT_PAT - NAME - IDENT "b" + OR_PAT + PIPE "|" + WHITESPACE " " + IDENT_PAT + NAME + IDENT "b" R_PAREN ")" WHITESPACE " " EQ "=" diff --git a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat_fields.rast b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat_fields.rast index 55baf2fdcb4f..96353f46976c 100644 --- a/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat_fields.rast +++ b/src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/tuple_pat_fields.rast @@ -110,11 +110,12 @@ SOURCE_FILE NAME_REF IDENT "S" L_PAREN "(" - PIPE "|" - WHITESPACE " " - IDENT_PAT - NAME - IDENT "a" + OR_PAT + PIPE "|" + WHITESPACE " " + IDENT_PAT + NAME + IDENT "a" R_PAREN ")" WHITESPACE " " EQ "=" diff --git a/src/tools/rust-analyzer/crates/syntax/rust.ungram b/src/tools/rust-analyzer/crates/syntax/rust.ungram index 3609da0bb263..02c59646a99e 100644 --- a/src/tools/rust-analyzer/crates/syntax/rust.ungram +++ b/src/tools/rust-analyzer/crates/syntax/rust.ungram @@ -736,7 +736,7 @@ PathPat = Path OrPat = - (Pat ('|' Pat)* '|'?) + '|'? (Pat ('|' Pat)*) BoxPat = 'box' Pat diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs index b9eb1abb1129..23d2b355a94f 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs @@ -1283,6 +1283,8 @@ pub struct OrPat { impl OrPat { #[inline] pub fn pats(&self) -> AstChildren { support::children(&self.syntax) } + #[inline] + pub fn pipe_token(&self) -> Option { support::token(&self.syntax, T![|]) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs index 11f5e662e3d6..6ec73e76f78d 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs @@ -1140,3 +1140,13 @@ impl From for ast::AnyHasAttrs { Self::new(node) } } + +impl ast::OrPat { + pub fn leading_pipe(&self) -> Option { + self.syntax + .children_with_tokens() + .find(|it| !it.kind().is_trivia()) + .and_then(NodeOrToken::into_token) + .filter(|it| it.kind() == T![|]) + } +} From 924ded6b72a83d550a7d60f434a1472ef1ddb30e Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sun, 27 Oct 2024 04:30:51 -0700 Subject: [PATCH 301/366] Clean up some comments on lint implementation --- compiler/rustc_lint/src/builtin.rs | 17 +++++------------ compiler/rustc_lint/src/context.rs | 20 +++----------------- compiler/rustc_lint/src/early.rs | 18 ++++-------------- compiler/rustc_lint/src/late.rs | 17 +++-------------- compiler/rustc_lint/src/lib.rs | 12 +++--------- 5 files changed, 18 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 3ee4980a9482..dbb8c6675323 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -4,21 +4,14 @@ //! AST visitor. Also see `rustc_session::lint::builtin`, which contains the //! definitions of lints that are emitted directly inside the main compiler. //! -//! To add a new lint to rustc, declare it here using `declare_lint!()`. +//! To add a new lint to rustc, declare it here using [`declare_lint!`]. //! Then add code to emit the new lint in the appropriate circumstances. -//! You can do that in an existing `LintPass` if it makes sense, or in a -//! new `LintPass`, or using `Session::add_lint` elsewhere in the -//! compiler. Only do the latter if the check can't be written cleanly as a -//! `LintPass` (also, note that such lints will need to be defined in -//! `rustc_session::lint::builtin`, not here). //! -//! If you define a new `EarlyLintPass`, you will also need to add it to the -//! `add_early_builtin!` or `add_early_builtin_with_new!` invocation in -//! `lib.rs`. Use the former for unit-like structs and the latter for structs -//! with a `pub fn new()`. +//! If you define a new [`EarlyLintPass`], you will also need to add it to the +//! [`crate::early_lint_methods!`] invocation in `lib.rs`. //! -//! If you define a new `LateLintPass`, you will also need to add it to the -//! `late_lint_methods!` invocation in `lib.rs`. +//! If you define a new [`LateLintPass`], you will also need to add it to the +//! [`crate::late_lint_methods!`] invocation in `lib.rs`. use std::fmt::Write; diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 39f90a8e9ed1..4af1fd1baf9c 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -1,18 +1,7 @@ -//! Implementation of lint checking. +//! Basic types for managing and implementing lints. //! -//! The lint checking is mostly consolidated into one pass which runs -//! after all other analyses. Throughout compilation, lint warnings -//! can be added via the `add_lint` method on the Session structure. This -//! requires a span and an ID of the node that the lint is being added to. The -//! lint isn't actually emitted at that time because it is unknown what the -//! actual lint level at that location is. -//! -//! To actually emit lint warnings/errors, a separate pass is used. -//! A context keeps track of the current state of all lint levels. -//! Upon entering a node of the ast which can modify the lint settings, the -//! previous lint state is pushed onto a stack and the ast is then recursed -//! upon. As the ast is traversed, this keeps track of the current lint level -//! for all lint attributes. +//! See for an +//! overview of how lints are implemented. use std::cell::Cell; use std::{iter, slice}; @@ -52,9 +41,6 @@ type LateLintPassFactory = dyn for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx> + sync::DynSend + sync::DynSync; /// Information about the registered lints. -/// -/// This is basically the subset of `Context` that we can -/// build early in the compile pipeline. pub struct LintStore { /// Registered lints. lints: Vec<&'static Lint>, diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index e2247d3a1f6c..acccff77a10a 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -1,18 +1,8 @@ -//! Implementation of lint checking. +//! Implementation of the early lint pass. //! -//! The lint checking is mostly consolidated into one pass which runs -//! after all other analyses. Throughout compilation, lint warnings -//! can be added via the `add_lint` method on the Session structure. This -//! requires a span and an ID of the node that the lint is being added to. The -//! lint isn't actually emitted at that time because it is unknown what the -//! actual lint level at that location is. -//! -//! To actually emit lint warnings/errors, a separate pass is used. -//! A context keeps track of the current state of all lint levels. -//! Upon entering a node of the ast which can modify the lint settings, the -//! previous lint state is pushed onto a stack and the ast is then recursed -//! upon. As the ast is traversed, this keeps track of the current lint level -//! for all lint attributes. +//! The early lint pass works on AST nodes after macro expansion and name +//! resolution, just before AST lowering. These lints are for purely +//! syntactical lints. use rustc_ast::ptr::P; use rustc_ast::visit::{self as ast_visit, Visitor, walk_list}; diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 9b1877599bae..9d35ce19b570 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -1,18 +1,7 @@ -//! Implementation of lint checking. +//! Implementation of the late lint pass. //! -//! The lint checking is mostly consolidated into one pass which runs -//! after all other analyses. Throughout compilation, lint warnings -//! can be added via the `add_lint` method on the Session structure. This -//! requires a span and an ID of the node that the lint is being added to. The -//! lint isn't actually emitted at that time because it is unknown what the -//! actual lint level at that location is. -//! -//! To actually emit lint warnings/errors, a separate pass is used. -//! A context keeps track of the current state of all lint levels. -//! Upon entering a node of the ast which can modify the lint settings, the -//! previous lint state is pushed onto a stack and the ast is then recursed -//! upon. As the ast is traversed, this keeps track of the current lint level -//! for all lint attributes. +//! The late lint pass Works on HIR nodes, towards the end of analysis (after +//! borrow checking, etc.). These lints have full type information available. use std::any::Any; use std::cell::Cell; diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 5389860e23bb..d950b1ff5ec8 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -6,20 +6,14 @@ //! other phases of the compiler, which are generally required to hold in order //! to compile the program at all. //! -//! Most lints can be written as [LintPass] instances. These run after +//! Most lints can be written as [`LintPass`] instances. These run after //! all other analyses. The `LintPass`es built into rustc are defined //! within [rustc_session::lint::builtin], //! which has further comments on how to add such a lint. //! rustc can also load external lint plugins, as is done for Clippy. //! -//! Some of rustc's lints are defined elsewhere in the compiler and work by -//! calling `add_lint()` on the overall `Session` object. This works when -//! it happens before the main lint pass, which emits the lints stored by -//! `add_lint()`. To emit lints after the main lint pass (from codegen, for -//! example) requires more effort. See `emit_lint` and `GatherNodeLevels` -//! in `context.rs`. -//! -//! Some code also exists in [rustc_session::lint], [rustc_middle::lint]. +//! See for an +//! overview of how lints are implemented. //! //! ## Note //! From 0abb563bf1001024013ae7408f93052c5ba4bbfa Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Sat, 26 Oct 2024 03:14:32 +0900 Subject: [PATCH 302/366] fix: Allow public re-export of `extern crate` import --- .../crates/hir-def/src/item_tree.rs | 5 ++ .../crates/hir-def/src/nameres/collector.rs | 31 +++++++++++-- .../crates/hir-def/src/nameres/tests.rs | 46 +++++++++++++++++++ 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs index 91a8cbab1a29..dba11d4b76e1 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs @@ -967,6 +967,11 @@ impl UseTree { self.expand_impl(None, &mut cb) } + /// The [`UseTreeKind`] of this `UseTree`. + pub fn kind(&self) -> &UseTreeKind { + &self.kind + } + fn expand_impl( &self, prefix: Option, diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs index b9aec9369035..a37e3c70e22a 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs @@ -31,7 +31,7 @@ use crate::{ item_scope::{ImportId, ImportOrExternCrate, ImportType, PerNsGlobImports}, item_tree::{ self, AttrOwner, FieldsShape, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, - ItemTreeNode, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, TreeId, + ItemTreeNode, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, TreeId, UseTreeKind, }, macro_call_as_call_id, macro_call_as_call_id_with_eager, nameres::{ @@ -1058,8 +1058,33 @@ impl DefCollector<'_> { vis: Visibility, def_import_type: Option, ) -> bool { - if let Some((_, v, _)) = defs.types.as_mut() { - *v = v.min(vis, &self.def_map).unwrap_or(vis); + // `extern crate crate_name` things can be re-exported as `pub use crate_name`. + // But they cannot be re-exported as `pub use self::crate_name`, `pub use crate::crate_name` + // or `pub use ::crate_name`. + // + // This has been historically allowed, but may be not allowed in future + // https://github.com/rust-lang/rust/issues/127909 + if let Some((_, v, it)) = defs.types.as_mut() { + let is_extern_crate_reimport_without_prefix = || { + let Some(ImportOrExternCrate::ExternCrate(_)) = it else { + return false; + }; + let Some(ImportType::Import(id)) = def_import_type else { + return false; + }; + let use_id = id.import.lookup(self.db).id; + let item_tree = use_id.item_tree(self.db); + let use_kind = item_tree[use_id.value].use_tree.kind(); + let UseTreeKind::Single { path, .. } = use_kind else { + return false; + }; + path.segments().len() < 2 + }; + if is_extern_crate_reimport_without_prefix() { + *v = vis; + } else { + *v = v.min(vis, &self.def_map).unwrap_or(vis); + } } if let Some((_, v, _)) = defs.values.as_mut() { *v = v.min(vis, &self.def_map).unwrap_or(vis); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests.rs index 7b02a89e5de7..e1e30e5cec9a 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/tests.rs @@ -385,6 +385,52 @@ pub struct Arc; ); } +#[test] +fn extern_crate_reexport() { + check( + r#" +//- /main.rs crate:main deps:importer +use importer::*; +use importer::extern_crate1::exported::*; +use importer::allowed_reexport::*; +use importer::extern_crate2::*; +use importer::not_allowed_reexport1; +use importer::not_allowed_reexport2; + +//- /importer.rs crate:importer deps:extern_crate1,extern_crate2 +extern crate extern_crate1; +extern crate extern_crate2; + +pub use extern_crate1; +pub use extern_crate1 as allowed_reexport; + +pub use ::extern_crate; +pub use self::extern_crate as not_allowed_reexport1; +pub use crate::extern_crate as not_allowed_reexport2; + +//- /extern_crate1.rs crate:extern_crate1 +pub mod exported { + pub struct PublicItem; + struct PrivateItem; +} + +pub struct Exported; + +//- /extern_crate2.rs crate:extern_crate2 +pub struct NotExported; +"#, + expect![[r#" + crate + Exported: t v + PublicItem: t v + allowed_reexport: t + exported: t + not_allowed_reexport1: _ + not_allowed_reexport2: _ + "#]], + ); +} + #[test] fn extern_crate_rename_2015_edition() { check( From 9bb6e0789c2eb9a39c26d52f905326182669c093 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Sun, 27 Oct 2024 14:53:50 +0000 Subject: [PATCH 303/366] Dynamically link run-make support --- src/tools/compiletest/src/runtest/run_make.rs | 1 + src/tools/run-make-support/Cargo.toml | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/tools/compiletest/src/runtest/run_make.rs b/src/tools/compiletest/src/runtest/run_make.rs index e7ae773ffa1d..04bc2d7787da 100644 --- a/src/tools/compiletest/src/runtest/run_make.rs +++ b/src/tools/compiletest/src/runtest/run_make.rs @@ -329,6 +329,7 @@ impl TestCx<'_> { .arg(format!("run_make_support={}", &support_lib_path.to_string_lossy())) .arg("--edition=2021") .arg(&self.testpaths.file.join("rmake.rs")) + .arg("-Cprefer-dynamic") // Provide necessary library search paths for rustc. .env(dylib_env_var(), &env::join_paths(host_dylib_search_paths).unwrap()); diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index d3605cd3dce0..3affa199fa50 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -13,3 +13,6 @@ gimli = "0.31.0" build_helper = { path = "../build_helper" } serde_json = "1.0" libc = "0.2" + +[lib] +crate-type = ["lib", "dylib"] From 4ccaef12a65ccdd0d1071c08c15e2c41fa425000 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Sun, 27 Oct 2024 16:20:14 +0000 Subject: [PATCH 304/366] Revert "ci update freebsd version proposal, freebsd 12 being eol." This reverts commit 1239c81c145d2bfb96f32856f377cd741d5c7256. Fix GH-132185 revert for now until early next year/FreeBSD 13.3 becomes EOL. --- .../host-x86_64/dist-various-2/Dockerfile | 6 +++--- .../host-x86_64/dist-x86_64-freebsd/Dockerfile | 6 +++--- src/ci/docker/scripts/freebsd-toolchain.sh | 8 ++++---- src/doc/rustc/src/platform-support.md | 18 +++++++++--------- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile index 8aabfaafbabb..ece5f174d06d 100644 --- a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile @@ -56,9 +56,9 @@ ENV \ CFLAGS_x86_64_fortanix_unknown_sgx="-D__ELF__ -isystem/usr/include/x86_64-linux-gnu -mlvi-hardening -mllvm -x86-experimental-lvi-inline-asm-hardening" \ CXX_x86_64_fortanix_unknown_sgx=clang++-11 \ CXXFLAGS_x86_64_fortanix_unknown_sgx="-D__ELF__ -isystem/usr/include/x86_64-linux-gnu -mlvi-hardening -mllvm -x86-experimental-lvi-inline-asm-hardening" \ - AR_i686_unknown_freebsd=i686-unknown-freebsd13-ar \ - CC_i686_unknown_freebsd=i686-unknown-freebsd13-clang \ - CXX_i686_unknown_freebsd=i686-unknown-freebsd13-clang++ \ + AR_i686_unknown_freebsd=i686-unknown-freebsd12-ar \ + CC_i686_unknown_freebsd=i686-unknown-freebsd12-clang \ + CXX_i686_unknown_freebsd=i686-unknown-freebsd12-clang++ \ CC_aarch64_unknown_uefi=clang-11 \ CXX_aarch64_unknown_uefi=clang++-11 \ CC_i686_unknown_uefi=clang-11 \ diff --git a/src/ci/docker/host-x86_64/dist-x86_64-freebsd/Dockerfile b/src/ci/docker/host-x86_64/dist-x86_64-freebsd/Dockerfile index fd0f5da8c495..f42e6f770ebe 100644 --- a/src/ci/docker/host-x86_64/dist-x86_64-freebsd/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-x86_64-freebsd/Dockerfile @@ -29,9 +29,9 @@ COPY scripts/cmake.sh /scripts/ RUN /scripts/cmake.sh ENV \ - AR_x86_64_unknown_freebsd=x86_64-unknown-freebsd13-ar \ - CC_x86_64_unknown_freebsd=x86_64-unknown-freebsd13-clang \ - CXX_x86_64_unknown_freebsd=x86_64-unknown-freebsd13-clang++ + AR_x86_64_unknown_freebsd=x86_64-unknown-freebsd12-ar \ + CC_x86_64_unknown_freebsd=x86_64-unknown-freebsd12-clang \ + CXX_x86_64_unknown_freebsd=x86_64-unknown-freebsd12-clang++ ENV HOSTS=x86_64-unknown-freebsd diff --git a/src/ci/docker/scripts/freebsd-toolchain.sh b/src/ci/docker/scripts/freebsd-toolchain.sh index 4826b81d56ce..0d02636db919 100755 --- a/src/ci/docker/scripts/freebsd-toolchain.sh +++ b/src/ci/docker/scripts/freebsd-toolchain.sh @@ -5,8 +5,8 @@ set -eux arch=$1 binutils_version=2.40 -freebsd_version=13.2 -triple=$arch-unknown-freebsd13 +freebsd_version=12.3 +triple=$arch-unknown-freebsd12 sysroot=/usr/local/$triple hide_output() { @@ -59,7 +59,7 @@ done # Originally downloaded from: # URL=https://download.freebsd.org/ftp/releases/${freebsd_arch}/${freebsd_version}-RELEASE/base.txz -URL=https://ci-mirrors.rust-lang.org/rustc/2024-02-18-freebsd-${freebsd_version}-${freebsd_arch}-base.txz +URL=https://ci-mirrors.rust-lang.org/rustc/2022-05-06-freebsd-${freebsd_version}-${freebsd_arch}-base.txz curl "$URL" | tar xJf - -C "$sysroot" --wildcards "${files_to_extract[@]}" # Clang can do cross-builds out of the box, if we give it the right @@ -68,7 +68,7 @@ curl "$URL" | tar xJf - -C "$sysroot" --wildcards "${files_to_extract[@]}" # there might be other problems.) # # The --target option is last because the cross-build of LLVM uses -# --target without an OS version ("-freebsd" vs. "-freebsd13"). This +# --target without an OS version ("-freebsd" vs. "-freebsd12"). This # makes Clang default to libstdc++ (which no longer exists), and also # controls other features, like GNU-style symbol table hashing and # anything predicated on the version number in the __FreeBSD__ diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index f7b8a8fc6e64..04bb40d750c9 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -100,7 +100,7 @@ target | notes [`riscv64gc-unknown-linux-gnu`](platform-support/riscv64gc-unknown-linux-gnu.md) | RISC-V Linux (kernel 4.20, glibc 2.29) [`riscv64gc-unknown-linux-musl`](platform-support/riscv64gc-unknown-linux-musl.md) | RISC-V Linux (kernel 4.20, musl 1.2.3) `s390x-unknown-linux-gnu` | S390x Linux (kernel 3.2, glibc 2.17) -`x86_64-unknown-freebsd` | 64-bit FreeBSD (version 13.2) +`x86_64-unknown-freebsd` | 64-bit FreeBSD `x86_64-unknown-illumos` | illumos `x86_64-unknown-linux-musl` | 64-bit Linux with musl 1.2.3 [`x86_64-unknown-netbsd`](platform-support/netbsd.md) | NetBSD/amd64 @@ -166,7 +166,7 @@ target | std | notes `i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, musl 1.2.3 [^x86_32-floats-x87] [`i686-linux-android`](platform-support/android.md) | ✓ | 32-bit x86 Android [^x86_32-floats-return-ABI] [`i686-pc-windows-gnullvm`](platform-support/pc-windows-gnullvm.md) | ✓ | 32-bit x86 MinGW (Windows 10+), LLVM ABI [^x86_32-floats-return-ABI] -`i686-unknown-freebsd` | ✓ | 32-bit FreeBSD (version 13.2) [^x86_32-floats-return-ABI] +`i686-unknown-freebsd` | ✓ | 32-bit FreeBSD [^x86_32-floats-return-ABI] `i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 [^x86_32-floats-return-ABI] [`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? | 32-bit UEFI [`loongarch64-unknown-none`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64D ABI) @@ -258,7 +258,7 @@ target | std | host | notes [`aarch64-unknown-teeos`](platform-support/aarch64-unknown-teeos.md) | ? | | ARM64 TEEOS | [`aarch64-unknown-nto-qnx700`](platform-support/nto-qnx.md) | ? | | ARM64 QNX Neutrino 7.0 RTOS | [`aarch64-unknown-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | ARM64 QNX Neutrino 7.1 RTOS | -`aarch64-unknown-freebsd` | ✓ | ✓ | ARM64 FreeBSD (version 13.2) +`aarch64-unknown-freebsd` | ✓ | ✓ | ARM64 FreeBSD [`aarch64-unknown-hermit`](platform-support/hermit.md) | ✓ | | ARM64 Hermit `aarch64-unknown-illumos` | ✓ | ✓ | ARM64 illumos `aarch64-unknown-linux-gnu_ilp32` | ✓ | ✓ | ARM64 Linux (ILP32 ABI) @@ -277,14 +277,14 @@ target | std | host | notes `armv4t-unknown-linux-gnueabi` | ? | | Armv4T Linux [`armv5te-none-eabi`](platform-support/armv5te-none-eabi.md) | * | | Bare Armv5TE `armv5te-unknown-linux-uclibceabi` | ? | | Armv5TE Linux with uClibc -`armv6-unknown-freebsd` | ✓ | ✓ | Armv6 FreeBSD (version 13.2) +`armv6-unknown-freebsd` | ✓ | ✓ | Armv6 FreeBSD [`armv6-unknown-netbsd-eabihf`](platform-support/netbsd.md) | ✓ | ✓ | Armv6 NetBSD w/hard-float [`armv6k-nintendo-3ds`](platform-support/armv6k-nintendo-3ds.md) | ? | | Armv6k Nintendo 3DS, Horizon (Requires devkitARM toolchain) [`armv7-rtems-eabihf`](platform-support/armv7-rtems-eabihf.md) | ? | | RTEMS OS for ARM BSPs [`armv7-sony-vita-newlibeabihf`](platform-support/armv7-sony-vita-newlibeabihf.md) | ✓ | | Armv7-A Cortex-A9 Sony PlayStation Vita (requires VITASDK toolchain) [`armv7-unknown-linux-uclibceabi`](platform-support/armv7-unknown-linux-uclibceabi.md) | ✓ | ✓ | Armv7-A Linux with uClibc, softfloat [`armv7-unknown-linux-uclibceabihf`](platform-support/armv7-unknown-linux-uclibceabihf.md) | ✓ | ? | Armv7-A Linux with uClibc, hardfloat -`armv7-unknown-freebsd` | ✓ | ✓ | Armv7-A FreeBSD (version 13.2) +`armv7-unknown-freebsd` | ✓ | ✓ | Armv7-A FreeBSD [`armv7-unknown-netbsd-eabihf`](platform-support/netbsd.md) | ✓ | ✓ | Armv7-A NetBSD w/hard-float [`armv7-unknown-trusty`](platform-support/trusty.md) | ? | | [`armv7-wrs-vxworks-eabihf`](platform-support/vxworks.md) | ✓ | | Armv7-A for VxWorks @@ -343,9 +343,9 @@ target | std | host | notes [`powerpc-unknown-openbsd`](platform-support/powerpc-unknown-openbsd.md) | * | | [`powerpc-wrs-vxworks-spe`](platform-support/vxworks.md) | ✓ | | [`powerpc-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | -`powerpc64-unknown-freebsd` | ✓ | ✓ | PPC64 FreeBSD (ELFv1 and ELFv2, version 13.2) -`powerpc64le-unknown-freebsd` | | | PPC64LE FreeBSD (version 13.2) -`powerpc-unknown-freebsd` | | | PowerPC FreeBSD (version 13.2) +`powerpc64-unknown-freebsd` | ✓ | ✓ | PPC64 FreeBSD (ELFv1 and ELFv2) +`powerpc64le-unknown-freebsd` | | | PPC64LE FreeBSD +`powerpc-unknown-freebsd` | | | PowerPC FreeBSD `powerpc64-unknown-linux-musl` | ? | | 64-bit PowerPC Linux with musl 1.2.3 [`powerpc64-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | `powerpc64le-unknown-linux-musl` | ? | | 64-bit PowerPC Linux with musl 1.2.3, Little Endian @@ -361,7 +361,7 @@ target | std | host | notes [`riscv32imafc-esp-espidf`](platform-support/esp-idf.md) | ✓ | | RISC-V ESP-IDF [`riscv32-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | [`riscv64gc-unknown-hermit`](platform-support/hermit.md) | ✓ | | RISC-V Hermit -`riscv64gc-unknown-freebsd` | | | RISC-V FreeBSD (version 13.2) +`riscv64gc-unknown-freebsd` | | | RISC-V FreeBSD `riscv64gc-unknown-fuchsia` | | | RISC-V Fuchsia [`riscv64gc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | RISC-V NetBSD [`riscv64gc-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/riscv64 From 709805a5fd9c9e46100e710ef1b4859e4bbfc9a8 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Sun, 27 Oct 2024 19:23:12 +0200 Subject: [PATCH 305/366] Properly resolve prelude paths inside modules inside blocks I.e. the following situation: ``` fn foo() { mod bar { fn qux() { // Prelude path here (e.g. macro use prelude or extern prelude). } } } ``` Those were previously unresolved, because, in order to support `self` and `super` properly, since #15148 we do not ascend block paths when there is a module in between, but only crate def maps register preludes, not block def maps, and we can't change this because block def map prelude can always be overridden by another block. E.g. ``` fn foo() { struct WithTheSameNameAsPreludeItem; { WithTheSameNameAsPreludeItem } } ``` Here `WithTheSameNameAsPreludeItem` refer to the item from the top block, but if we would register prelude items in each block the child block would overwrite it incorrectly. --- .../hir-def/src/nameres/path_resolution.rs | 207 +++++++++++++----- .../src/handlers/unresolved_macro_call.rs | 25 +++ 2 files changed, 180 insertions(+), 52 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/path_resolution.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/path_resolution.rs index 75cab137f78b..29379d007493 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/path_resolution.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/path_resolution.rs @@ -10,6 +10,7 @@ //! //! `ReachedFixedPoint` signals about this. +use either::Either; use hir_expand::{name::Name, Lookup}; use span::Edition; use triomphe::Arc; @@ -150,17 +151,8 @@ impl DefMap { let mut arc; let mut current_map = self; - loop { - let new = current_map.resolve_path_fp_with_macro_single( - db, - mode, - original_module, - path, - shadow, - expected_macro_subns, - ); - // Merge `new` into `result`. + let mut merge = |new: ResolvePathResult| { result.resolved_def = result.resolved_def.or(new.resolved_def); if result.reached_fixedpoint == ReachedFixedPoint::No { result.reached_fixedpoint = new.reached_fixedpoint; @@ -171,7 +163,9 @@ impl DefMap { (Some(old), Some(new)) => Some(old.max(new)), (None, new) => new, }; + }; + loop { match current_map.block { Some(block) if original_module == Self::ROOT => { // Block modules "inherit" names from its parent module. @@ -180,8 +174,38 @@ impl DefMap { current_map = &arc; } // Proper (non-block) modules, including those in block `DefMap`s, don't. - _ => return result, + _ => { + if original_module != Self::ROOT && current_map.block.is_some() { + // A module inside a block. Do not resolve items declared in upper blocks, but we do need to get + // the prelude items (which are not inserted into blocks because they can be overridden there). + original_module = Self::ROOT; + arc = db.crate_def_map(self.krate); + current_map = &arc; + + let new = current_map.resolve_path_fp_in_all_preludes( + db, + mode, + original_module, + path, + shadow, + ); + merge(new); + } + + return result; + } } + + let new = current_map.resolve_path_fp_with_macro_single( + db, + mode, + original_module, + path, + shadow, + expected_macro_subns, + ); + + merge(new); } } @@ -195,7 +219,7 @@ impl DefMap { expected_macro_subns: Option, ) -> ResolvePathResult { let mut segments = path.segments().iter().enumerate(); - let mut curr_per_ns = match path.kind { + let curr_per_ns = match path.kind { PathKind::DollarCrate(krate) => { if krate == self.krate { cov_mark::hit!(macro_dollar_crate_self); @@ -296,25 +320,96 @@ impl DefMap { PerNs::types(module.into(), Visibility::Public, None) } - PathKind::Abs => { - // 2018-style absolute path -- only extern prelude - let segment = match segments.next() { - Some((_, segment)) => segment, + PathKind::Abs => match self.resolve_path_abs(&mut segments, path) { + Either::Left(it) => it, + Either::Right(reached_fixed_point) => { + return ResolvePathResult::empty(reached_fixed_point) + } + }, + }; + + self.resolve_remaining_segments(segments, curr_per_ns, path, db, shadow, original_module) + } + + /// Resolves a path only in the preludes, without accounting for item scopes. + pub(super) fn resolve_path_fp_in_all_preludes( + &self, + db: &dyn DefDatabase, + mode: ResolveMode, + original_module: LocalModuleId, + path: &ModPath, + shadow: BuiltinShadowMode, + ) -> ResolvePathResult { + let mut segments = path.segments().iter().enumerate(); + let curr_per_ns = match path.kind { + // plain import or absolute path in 2015: crate-relative with + // fallback to extern prelude (with the simplification in + // rust-lang/rust#57745) + // FIXME there must be a nicer way to write this condition + PathKind::Plain | PathKind::Abs + if self.data.edition == Edition::Edition2015 + && (path.kind == PathKind::Abs || mode == ResolveMode::Import) => + { + let (_, segment) = match segments.next() { + Some((idx, segment)) => (idx, segment), None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), }; - if let Some(&(def, extern_crate)) = self.data.extern_prelude.get(segment) { - tracing::debug!("absolute path {:?} resolved to crate {:?}", path, def); - PerNs::types( - def.into(), - Visibility::Public, - extern_crate.map(ImportOrExternCrate::ExternCrate), - ) - } else { - return ResolvePathResult::empty(ReachedFixedPoint::No); // extern crate declarations can add to the extern prelude + tracing::debug!("resolving {:?} in crate root (+ extern prelude)", segment); + self.resolve_name_in_extern_prelude(segment) + } + PathKind::Plain => { + let (_, segment) = match segments.next() { + Some((idx, segment)) => (idx, segment), + None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), + }; + tracing::debug!("resolving {:?} in module", segment); + self.resolve_name_in_all_preludes(db, segment) + } + PathKind::Abs => match self.resolve_path_abs(&mut segments, path) { + Either::Left(it) => it, + Either::Right(reached_fixed_point) => { + return ResolvePathResult::empty(reached_fixed_point) } + }, + PathKind::DollarCrate(_) | PathKind::Crate | PathKind::Super(_) => { + return ResolvePathResult::empty(ReachedFixedPoint::Yes) } }; + self.resolve_remaining_segments(segments, curr_per_ns, path, db, shadow, original_module) + } + + /// 2018-style absolute path -- only extern prelude + fn resolve_path_abs<'a>( + &self, + segments: &mut impl Iterator, + path: &ModPath, + ) -> Either { + let segment = match segments.next() { + Some((_, segment)) => segment, + None => return Either::Right(ReachedFixedPoint::Yes), + }; + if let Some(&(def, extern_crate)) = self.data.extern_prelude.get(segment) { + tracing::debug!("absolute path {:?} resolved to crate {:?}", path, def); + Either::Left(PerNs::types( + def.into(), + Visibility::Public, + extern_crate.map(ImportOrExternCrate::ExternCrate), + )) + } else { + Either::Right(ReachedFixedPoint::No) // extern crate declarations can add to the extern prelude + } + } + + fn resolve_remaining_segments<'a>( + &self, + segments: impl Iterator, + mut curr_per_ns: PerNs, + path: &ModPath, + db: &dyn DefDatabase, + shadow: BuiltinShadowMode, + original_module: LocalModuleId, + ) -> ResolvePathResult { for (i, segment) in segments { let (curr, vis, imp) = match curr_per_ns.take_types_full() { Some(r) => r, @@ -475,24 +570,9 @@ impl DefMap { // they might been shadowed by local names. return PerNs::none(); } - self.data.extern_prelude.get(name).map_or(PerNs::none(), |&(it, extern_crate)| { - PerNs::types( - it.into(), - Visibility::Public, - extern_crate.map(ImportOrExternCrate::ExternCrate), - ) - }) - }; - let macro_use_prelude = || { - self.macro_use_prelude.get(name).map_or(PerNs::none(), |&(it, _extern_crate)| { - PerNs::macros( - it, - Visibility::Public, - // FIXME? - None, // extern_crate.map(ImportOrExternCrate::ExternCrate), - ) - }) + self.resolve_name_in_extern_prelude(name) }; + let macro_use_prelude = || self.resolve_in_macro_use_prelude(name); let prelude = || { if self.block.is_some() && module == DefMap::ROOT { return PerNs::none(); @@ -507,6 +587,38 @@ impl DefMap { .or_else(prelude) } + fn resolve_name_in_all_preludes(&self, db: &dyn DefDatabase, name: &Name) -> PerNs { + // Resolve in: + // - extern prelude / macro_use prelude + // - std prelude + let extern_prelude = self.resolve_name_in_extern_prelude(name); + let macro_use_prelude = || self.resolve_in_macro_use_prelude(name); + let prelude = || self.resolve_in_prelude(db, name); + + extern_prelude.or_else(macro_use_prelude).or_else(prelude) + } + + fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs { + self.data.extern_prelude.get(name).map_or(PerNs::none(), |&(it, extern_crate)| { + PerNs::types( + it.into(), + Visibility::Public, + extern_crate.map(ImportOrExternCrate::ExternCrate), + ) + }) + } + + fn resolve_in_macro_use_prelude(&self, name: &Name) -> PerNs { + self.macro_use_prelude.get(name).map_or(PerNs::none(), |&(it, _extern_crate)| { + PerNs::macros( + it, + Visibility::Public, + // FIXME? + None, // extern_crate.map(ImportOrExternCrate::ExternCrate), + ) + }) + } + fn resolve_name_in_crate_root_or_extern_prelude( &self, db: &dyn DefDatabase, @@ -525,16 +637,7 @@ impl DefMap { // Don't resolve extern prelude in pseudo-module of a block. return PerNs::none(); } - self.data.extern_prelude.get(name).copied().map_or( - PerNs::none(), - |(it, extern_crate)| { - PerNs::types( - it.into(), - Visibility::Public, - extern_crate.map(ImportOrExternCrate::ExternCrate), - ) - }, - ) + self.resolve_name_in_extern_prelude(name) }; from_crate_root.or_else(from_extern_prelude) diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs index 5b596123e75f..0d1c97750627 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs @@ -82,4 +82,29 @@ self::m!(); self::m2!(); "#, ); } + + #[test] + fn no_unresolved_panic_inside_mod_inside_fn() { + check_diagnostics( + r#" +//- /core.rs library crate:core +#[macro_export] +macro_rules! panic { + () => {}; +} + +//- /lib.rs crate:foo deps:core +#[macro_use] +extern crate core; + +fn foo() { + mod init { + pub fn init() { + panic!(); + } + } +} + "#, + ); + } } From 8a9f40043fb6177a8a6d720103bac4e8889e0732 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Sun, 27 Oct 2024 17:47:00 +0100 Subject: [PATCH 306/366] add test for panicking drop in Box/Rc/Arc --- library/alloc/tests/arc.rs | 40 ++++++++++++++++++++++++++++++++++-- library/alloc/tests/boxed.rs | 38 ++++++++++++++++++++++++++++++++++ library/alloc/tests/rc.rs | 38 +++++++++++++++++++++++++++++++++- 3 files changed, 113 insertions(+), 3 deletions(-) diff --git a/library/alloc/tests/arc.rs b/library/alloc/tests/arc.rs index dc27c578b57e..a259c0131ecd 100644 --- a/library/alloc/tests/arc.rs +++ b/library/alloc/tests/arc.rs @@ -1,5 +1,5 @@ use std::any::Any; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::iter::TrustedLen; use std::mem; use std::sync::{Arc, Weak}; @@ -89,7 +89,7 @@ fn eq() { // The test code below is identical to that in `rc.rs`. // For better maintainability we therefore define this type alias. -type Rc = Arc; +type Rc = Arc; const SHARED_ITER_MAX: u16 = 100; @@ -210,6 +210,42 @@ fn weak_may_dangle() { // borrow might be used here, when `val` is dropped and runs the `Drop` code for type `std::sync::Weak` } +/// Test that a panic from a destructor does not leak the allocation. +#[test] +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +fn panic_no_leak() { + use std::alloc::{AllocError, Allocator, Global, Layout}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::ptr::NonNull; + + struct AllocCount(Cell); + unsafe impl Allocator for AllocCount { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.0.set(self.0.get() + 1); + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + self.0.set(self.0.get() - 1); + unsafe { Global.deallocate(ptr, layout) } + } + } + + struct PanicOnDrop; + impl Drop for PanicOnDrop { + fn drop(&mut self) { + panic!("PanicOnDrop"); + } + } + + let alloc = AllocCount(Cell::new(0)); + let rc = Rc::new_in(PanicOnDrop, &alloc); + assert_eq!(alloc.0.get(), 1); + + let panic_message = catch_unwind(AssertUnwindSafe(|| drop(rc))).unwrap_err(); + assert_eq!(*panic_message.downcast_ref::<&'static str>().unwrap(), "PanicOnDrop"); + assert_eq!(alloc.0.get(), 0); +} + /// This is similar to the doc-test for `Arc::make_mut()`, but on an unsized type (slice). #[test] fn make_mut_unsized() { diff --git a/library/alloc/tests/boxed.rs b/library/alloc/tests/boxed.rs index bfc31a626fad..2d172fc21379 100644 --- a/library/alloc/tests/boxed.rs +++ b/library/alloc/tests/boxed.rs @@ -59,6 +59,44 @@ fn box_deref_lval() { assert_eq!(x.get(), 1000); } +/// Test that a panic from a destructor does not leak the allocation. +#[test] +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +fn panic_no_leak() { + use std::alloc::{AllocError, Allocator, Global, Layout}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::ptr::NonNull; + + struct AllocCount(Cell); + unsafe impl Allocator for AllocCount { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.0.set(self.0.get() + 1); + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + self.0.set(self.0.get() - 1); + unsafe { Global.deallocate(ptr, layout) } + } + } + + struct PanicOnDrop { + _data: u8, + } + impl Drop for PanicOnDrop { + fn drop(&mut self) { + panic!("PanicOnDrop"); + } + } + + let alloc = AllocCount(Cell::new(0)); + let b = Box::new_in(PanicOnDrop { _data: 42 }, &alloc); + assert_eq!(alloc.0.get(), 1); + + let panic_message = catch_unwind(AssertUnwindSafe(|| drop(b))).unwrap_err(); + assert_eq!(*panic_message.downcast_ref::<&'static str>().unwrap(), "PanicOnDrop"); + assert_eq!(alloc.0.get(), 0); +} + #[allow(unused)] pub struct ConstAllocator; diff --git a/library/alloc/tests/rc.rs b/library/alloc/tests/rc.rs index 29dbdcf225eb..451765d72428 100644 --- a/library/alloc/tests/rc.rs +++ b/library/alloc/tests/rc.rs @@ -1,5 +1,5 @@ use std::any::Any; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::iter::TrustedLen; use std::mem; use std::rc::{Rc, Weak}; @@ -206,6 +206,42 @@ fn weak_may_dangle() { // borrow might be used here, when `val` is dropped and runs the `Drop` code for type `std::rc::Weak` } +/// Test that a panic from a destructor does not leak the allocation. +#[test] +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +fn panic_no_leak() { + use std::alloc::{AllocError, Allocator, Global, Layout}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::ptr::NonNull; + + struct AllocCount(Cell); + unsafe impl Allocator for AllocCount { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.0.set(self.0.get() + 1); + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + self.0.set(self.0.get() - 1); + unsafe { Global.deallocate(ptr, layout) } + } + } + + struct PanicOnDrop; + impl Drop for PanicOnDrop { + fn drop(&mut self) { + panic!("PanicOnDrop"); + } + } + + let alloc = AllocCount(Cell::new(0)); + let rc = Rc::new_in(PanicOnDrop, &alloc); + assert_eq!(alloc.0.get(), 1); + + let panic_message = catch_unwind(AssertUnwindSafe(|| drop(rc))).unwrap_err(); + assert_eq!(*panic_message.downcast_ref::<&'static str>().unwrap(), "PanicOnDrop"); + assert_eq!(alloc.0.get(), 0); +} + #[allow(unused)] mod pin_coerce_unsized { use alloc::rc::{Rc, UniqueRc}; From 4a71a592819b6fe87377dd5f857218ed37dbf195 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Sun, 27 Oct 2024 17:48:15 +0100 Subject: [PATCH 307/366] Rc/Arc: don't leak the allocation if drop panics --- library/alloc/src/rc.rs | 17 +++++++---------- library/alloc/src/sync.rs | 16 +++++++++------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 9fdd51ce331f..52ec8237d834 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -2256,17 +2256,14 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc { unsafe { self.inner().dec_strong(); if self.inner().strong() == 0 { - // destroy the contained object - ptr::drop_in_place(Self::get_mut_unchecked(self)); + // Reconstruct the "strong weak" pointer and drop it when this + // variable goes out of scope. This ensures that the memory is + // deallocated even if the destructor of `T` panics. + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; - // remove the implicit "strong weak" pointer now that we've - // destroyed the contents. - self.inner().dec_weak(); - - if self.inner().weak() == 0 { - self.alloc - .deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); - } + // Destroy the contained object. + // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed. + ptr::drop_in_place(&mut (*self.ptr.as_ptr()).value); } } } diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 15a1b0f28344..98a2fe242570 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -1872,15 +1872,17 @@ impl Arc { // Non-inlined part of `drop`. #[inline(never)] unsafe fn drop_slow(&mut self) { + // Drop the weak ref collectively held by all strong references when this + // variable goes out of scope. This ensures that the memory is deallocated + // even if the destructor of `T` panics. + // Take a reference to `self.alloc` instead of cloning because 1. it'll last long + // enough, and 2. you should be able to drop `Arc`s with unclonable allocators + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + // Destroy the data at this time, even though we must not free the box // allocation itself (there might still be weak pointers lying around). - unsafe { ptr::drop_in_place(Self::get_mut_unchecked(self)) }; - - // Drop the weak ref collectively held by all strong references - // Take a reference to `self.alloc` instead of cloning because 1. it'll - // last long enough, and 2. you should be able to drop `Arc`s with - // unclonable allocators - drop(Weak { ptr: self.ptr, alloc: &self.alloc }); + // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed. + unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) }; } /// Returns `true` if the two `Arc`s point to the same allocation in a vein similar to From ad80da672915a89163838f9adbfe5b6e4c1e616e Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 27 Oct 2024 20:34:13 +0100 Subject: [PATCH 308/366] Use Hacker's Delight impl in `i64::midpoint` instead of wide `i128` impl As LLVM seems to be outperformed by the complexity of signed 128-bits number compared to our Hacker's Delight implementation.[^1] It doesn't seems like it's an improvement for the other sizes[^2], so we let them with the wide implementation. [^1]: https://rust.godbolt.org/z/ravE75EYj [^2]: https://rust.godbolt.org/z/fzr171zKh --- library/core/src/num/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 9a5e211dd608..6a0b40ff5177 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -429,7 +429,7 @@ impl i64 { from_xe_bytes_doc = "", bound_condition = "", } - midpoint_impl! { i64, i128, signed } + midpoint_impl! { i64, signed } } impl i128 { @@ -530,7 +530,7 @@ impl isize { from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(), bound_condition = " on 64-bit targets", } - midpoint_impl! { isize, i128, signed } + midpoint_impl! { isize, signed } } /// If the 6th bit is set ascii is lower case. From 66209cd9b57f9414c9b8bc826ca97c4b7d52489a Mon Sep 17 00:00:00 2001 From: ultrabear Date: Sun, 27 Oct 2024 14:31:58 -0700 Subject: [PATCH 309/366] Support `char::is_digit` in const contexts --- library/core/src/char/methods.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index 9c667edb4761..206bbf5690ef 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -320,8 +320,9 @@ impl char { /// '1'.is_digit(37); /// ``` #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_char_is_digit", issue = "132241")] #[inline] - pub fn is_digit(self, radix: u32) -> bool { + pub const fn is_digit(self, radix: u32) -> bool { self.to_digit(radix).is_some() } From 47e5759da9a3b289935c81f4d2d1f37cdbb55a92 Mon Sep 17 00:00:00 2001 From: LastExceed Date: Wed, 16 Oct 2024 21:39:38 +0200 Subject: [PATCH 310/366] add LetStmt arm --- .../crates/ide/src/file_structure.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/tools/rust-analyzer/crates/ide/src/file_structure.rs b/src/tools/rust-analyzer/crates/ide/src/file_structure.rs index 92458185849b..7b296b27013f 100644 --- a/src/tools/rust-analyzer/crates/ide/src/file_structure.rs +++ b/src/tools/rust-analyzer/crates/ide/src/file_structure.rs @@ -187,6 +187,24 @@ fn structure_node(node: &SyntaxNode) -> Option { }; Some(node) }, + ast::LetStmt(it) => { + let pat = it.pat()?; + + let mut label = String::new(); + collapse_ws(pat.syntax(), &mut label); + + let node = StructureNode { + parent: None, + label, + navigation_range: pat.syntax().text_range(), + node_range: it.syntax().text_range(), + kind: StructureNodeKind::SymbolKind(SymbolKind::Local), + detail: it.ty().map(|ty| ty.to_string()), + deprecated: false, + }; + + Some(node) + }, ast::Macro(it) => decl(it, StructureNodeKind::SymbolKind(SymbolKind::Macro)), _ => None, } From b889a11d7981df34b8aaf2e4ba5e1fc53ac684bd Mon Sep 17 00:00:00 2001 From: LastExceed Date: Sun, 27 Oct 2024 23:26:38 +0100 Subject: [PATCH 311/366] add test --- .../crates/ide/src/file_structure.rs | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/src/tools/rust-analyzer/crates/ide/src/file_structure.rs b/src/tools/rust-analyzer/crates/ide/src/file_structure.rs index 7b296b27013f..055080ad17b1 100644 --- a/src/tools/rust-analyzer/crates/ide/src/file_structure.rs +++ b/src/tools/rust-analyzer/crates/ide/src/file_structure.rs @@ -326,6 +326,17 @@ fn f() {} // endregion fn g() {} } + +fn let_statements() { + let x = 42; + let mut y = x; + let Foo { + .. + } = Foo { x }; + if let None = Some(x) {} + _ = (); + let _ = g(); +} "#, expect![[r#" [ @@ -651,6 +662,71 @@ fn g() {} ), deprecated: false, }, + StructureNode { + parent: None, + label: "let_statements", + navigation_range: 641..655, + node_range: 638..798, + kind: SymbolKind( + Function, + ), + detail: Some( + "fn()", + ), + deprecated: false, + }, + StructureNode { + parent: Some( + 26, + ), + label: "x", + navigation_range: 668..669, + node_range: 664..675, + kind: SymbolKind( + Local, + ), + detail: None, + deprecated: false, + }, + StructureNode { + parent: Some( + 26, + ), + label: "mut y", + navigation_range: 684..689, + node_range: 680..694, + kind: SymbolKind( + Local, + ), + detail: None, + deprecated: false, + }, + StructureNode { + parent: Some( + 26, + ), + label: "Foo { .. }", + navigation_range: 703..725, + node_range: 699..738, + kind: SymbolKind( + Local, + ), + detail: None, + deprecated: false, + }, + StructureNode { + parent: Some( + 26, + ), + label: "_", + navigation_range: 788..789, + node_range: 784..796, + kind: SymbolKind( + Local, + ), + detail: None, + deprecated: false, + }, ] "#]], ); From 2507e83d7bb0dd9e7217b10b13afc61763dc1eca Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 27 Oct 2024 22:35:17 +0000 Subject: [PATCH 312/366] Stop using the whole match expr span for an arm's obligation span --- compiler/rustc_hir_typeck/src/_match.rs | 16 +++++++--------- compiler/rustc_middle/src/traits/mod.rs | 2 ++ .../src/error_reporting/infer/mod.rs | 7 ++++--- tests/ui/wf/wf-dyn-incompat-trait-obj-match.rs | 4 ++-- .../ui/wf/wf-dyn-incompat-trait-obj-match.stderr | 10 +++------- 5 files changed, 18 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index e68caa3e2e35..3372cae7a510 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -94,14 +94,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (None, arm.body.span) }; - let (span, code) = match prior_arm { + let code = match prior_arm { // The reason for the first arm to fail is not that the match arms diverge, // but rather that there's a prior obligation that doesn't hold. - None => { - (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id, match_src)) - } - Some((prior_arm_block_id, prior_arm_ty, prior_arm_span)) => ( - expr.span, + None => ObligationCauseCode::BlockTailExpression(arm.body.hir_id, match_src), + Some((prior_arm_block_id, prior_arm_ty, prior_arm_span)) => { ObligationCauseCode::MatchExpressionArm(Box::new(MatchExpressionArmCause { arm_block_id, arm_span, @@ -110,13 +107,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { prior_arm_ty, prior_arm_span, scrut_span: scrut.span, + expr_span: expr.span, source: match_src, prior_non_diverging_arms: prior_non_diverging_arms.clone(), tail_defines_return_position_impl_trait, - })), - ), + })) + } }; - let cause = self.cause(span, code); + let cause = self.cause(arm_span, code); // This is the moral equivalent of `coercion.coerce(self, cause, arm.body, arm_ty)`. // We use it this way to be able to expand on the potential error and detect when a diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 8ee8b4c4823a..7237a7014e87 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -519,6 +519,8 @@ pub struct MatchExpressionArmCause<'tcx> { pub prior_arm_span: Span, pub scrut_span: Span, pub source: hir::MatchSource, + // Span of the *whole* match expr + pub expr_span: Span, pub prior_non_diverging_arms: Vec, // Is the expectation of this match expression an RPIT? pub tail_defines_return_position_impl_trait: Option, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index b9a569d25e32..0cbb43b87638 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -412,6 +412,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { source, ref prior_non_diverging_arms, scrut_span, + expr_span, .. }) => match source { hir::MatchSource::TryDesugar(scrut_hir_id) => { @@ -460,12 +461,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { format!("this and all prior arms are found to be of type `{t}`"), ); } - let outer = if any_multiline_arm || !source_map.is_multiline(cause.span) { + let outer = if any_multiline_arm || !source_map.is_multiline(expr_span) { // Cover just `match` and the scrutinee expression, not // the entire match body, to reduce diagram noise. - cause.span.shrink_to_lo().to(scrut_span) + expr_span.shrink_to_lo().to(scrut_span) } else { - cause.span + expr_span }; let msg = "`match` arms have incompatible types"; err.span_label(outer, msg); diff --git a/tests/ui/wf/wf-dyn-incompat-trait-obj-match.rs b/tests/ui/wf/wf-dyn-incompat-trait-obj-match.rs index 07e90538b85d..6eba6b7abecd 100644 --- a/tests/ui/wf/wf-dyn-incompat-trait-obj-match.rs +++ b/tests/ui/wf/wf-dyn-incompat-trait-obj-match.rs @@ -22,8 +22,8 @@ fn main() { Some(()) => &S, None => &R, //~ ERROR E0308 } - let t: &dyn Trait = match opt() { //~ ERROR E0038 + let t: &dyn Trait = match opt() { Some(()) => &S, //~ ERROR E0038 - None => &R, + None => &R, //~ ERROR E0038 }; } diff --git a/tests/ui/wf/wf-dyn-incompat-trait-obj-match.stderr b/tests/ui/wf/wf-dyn-incompat-trait-obj-match.stderr index d7366e12256a..6cd4ebf8412b 100644 --- a/tests/ui/wf/wf-dyn-incompat-trait-obj-match.stderr +++ b/tests/ui/wf/wf-dyn-incompat-trait-obj-match.stderr @@ -31,14 +31,10 @@ LL | trait Trait: Sized {} = note: required for the cast from `&S` to `&dyn Trait` error[E0038]: the trait `Trait` cannot be made into an object - --> $DIR/wf-dyn-incompat-trait-obj-match.rs:25:25 + --> $DIR/wf-dyn-incompat-trait-obj-match.rs:27:17 | -LL | let t: &dyn Trait = match opt() { - | _________________________^ -LL | | Some(()) => &S, -LL | | None => &R, -LL | | }; - | |_____^ `Trait` cannot be made into an object +LL | None => &R, + | ^^ `Trait` cannot be made into an object | note: for a trait to be "dyn-compatible" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit --> $DIR/wf-dyn-incompat-trait-obj-match.rs:6:14 From 7f54b9ecefc38a8a3fde9a98b253eeb6f775b25a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 27 Oct 2024 22:53:14 +0000 Subject: [PATCH 313/366] Remove ObligationCause::span() method --- .../src/check/compare_impl_item.rs | 4 ++-- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 2 +- .../rustc_hir_typeck/src/method/confirm.rs | 2 +- compiler/rustc_middle/src/traits/mod.rs | 19 +++++++------------ .../src/error_reporting/infer/mod.rs | 10 +++++----- .../nice_region_error/placeholder_error.rs | 2 +- .../src/traits/project.rs | 4 ++-- .../src/traits/query/evaluate_obligation.rs | 2 +- 9 files changed, 21 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 02cf1a502f16..9de96b7ba776 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -611,7 +611,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( Err(terr) => { let mut diag = struct_span_code_err!( tcx.dcx(), - cause.span(), + cause.span, E0053, "method `{}` has an incompatible return type for trait", trait_m.name @@ -1169,7 +1169,7 @@ fn extract_spans_for_error_reporting<'tcx>( TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => { (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i))) } - _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)), + _ => (cause.span, tcx.hir().span_if_local(trait_m.def_id)), } } diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index f2f9c69e49f7..58210aaa0668 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -612,7 +612,7 @@ pub fn check_function_signature<'tcx>( match err { TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => args.nth(i).unwrap(), - _ => cause.span(), + _ => cause.span, } } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 92c2a9060558..d6e5fab610ed 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -2027,7 +2027,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } Err(_) => { span_bug!( - cause.span(), + cause.span, "subtyping remaining fields of type changing FRU failed: {target_ty} != {fru_ty}: {}::{}", variant.name, ident.name, diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 96784fcb61b2..f2b55d3aa4e1 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -550,7 +550,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // This has/will have errored in wfcheck, which we cannot depend on from here, as typeck on functions // may run before wfcheck if the function is used in const eval. self.dcx().span_delayed_bug( - cause.span(), + cause.span, format!("{self_ty} was a subtype of {method_self_ty} but now is not?"), ); } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 7237a7014e87..40e5ec459598 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -92,16 +92,6 @@ impl<'tcx> ObligationCause<'tcx> { ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() } } - pub fn span(&self) -> Span { - match *self.code() { - ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause { - arm_span, - .. - }) => arm_span, - _ => self.span, - } - } - #[inline] pub fn code(&self) -> &ObligationCauseCode<'tcx> { &self.code @@ -517,12 +507,17 @@ pub struct MatchExpressionArmCause<'tcx> { pub prior_arm_block_id: Option, pub prior_arm_ty: Ty<'tcx>, pub prior_arm_span: Span, + /// Span of the scrutinee of the match (the matched value). pub scrut_span: Span, + /// Source of the match, i.e. `match` or a desugaring. pub source: hir::MatchSource, - // Span of the *whole* match expr + /// Span of the *whole* match expr. pub expr_span: Span, + /// Spans of the previous arms except for those that diverge (i.e. evaluate to `!`). + /// + /// These are used for pointing out errors that may affect several arms. pub prior_non_diverging_arms: Vec, - // Is the expectation of this match expression an RPIT? + /// Is the expectation of this match expression an RPIT? pub tail_defines_return_position_impl_trait: Option, } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index 0cbb43b87638..574cf1e88b16 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -392,7 +392,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { Some(ty) if expected == ty => { let source_map = self.tcx.sess.source_map(); err.span_suggestion( - source_map.end_point(cause.span()), + source_map.end_point(cause.span), "try removing this `?`", "", Applicability::MachineApplicable, @@ -431,7 +431,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { Some(ty) if expected == ty => { let source_map = self.tcx.sess.source_map(); err.span_suggestion( - source_map.end_point(cause.span()), + source_map.end_point(cause.span), "try removing this `?`", "", Applicability::MachineApplicable, @@ -1149,7 +1149,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { terr: TypeError<'tcx>, prefer_label: bool, ) { - let span = cause.span(); + let span = cause.span; // For some types of errors, expected-found does not make // sense, so just ignore the values we were given. @@ -1643,7 +1643,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { terr: TypeError<'tcx>, ) -> Vec { let mut suggestions = Vec::new(); - let span = trace.cause.span(); + let span = trace.cause.span; let values = self.resolve_vars_if_possible(trace.values); if let Some((expected, found)) = values.ty() { match (expected.kind(), found.kind()) { @@ -1793,7 +1793,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ) -> Diag<'a> { debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr); - let span = trace.cause.span(); + let span = trace.cause.span; let failure_code = trace.cause.as_failure_code_diag( terr, span, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs index 14c2bf19a9cf..4398af76ab2c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs @@ -237,7 +237,7 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { expected_args: GenericArgsRef<'tcx>, actual_args: GenericArgsRef<'tcx>, ) -> Diag<'tcx> { - let span = cause.span(); + let span = cause.span; let (leading_ellipsis, satisfy_span, where_span, dup_span, def_id) = if let ObligationCauseCode::WhereClause(def_id, span) diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 38722c0ff7c5..0803dd74b89b 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1180,7 +1180,7 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( selcx.tcx(), selcx.tcx().require_lang_item( LangItem::Sized, - Some(obligation.cause.span()), + Some(obligation.cause.span), ), [self_ty], ), @@ -1600,7 +1600,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( // exist. Instead, `Pointee` should be a supertrait of `Sized`. let sized_predicate = ty::TraitRef::new( tcx, - tcx.require_lang_item(LangItem::Sized, Some(obligation.cause.span())), + tcx.require_lang_item(LangItem::Sized, Some(obligation.cause.span)), [self_ty], ); obligations.push(obligation.with(tcx, sized_predicate)); diff --git a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs index 76017299f2c0..bb44645a4ce1 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -90,7 +90,7 @@ impl<'tcx> InferCtxt<'tcx> { assert!(!self.intercrate); let c_pred = self.canonicalize_query(param_env.and(obligation.predicate), &mut _orig_values); - self.tcx.at(obligation.cause.span()).evaluate_obligation(c_pred) + self.tcx.at(obligation.cause.span).evaluate_obligation(c_pred) } } From d792e1f50af4c7006c351ff1eed8c32eee10d3e8 Mon Sep 17 00:00:00 2001 From: jyn Date: Sun, 24 Dec 2023 18:34:20 -0500 Subject: [PATCH 314/366] remove dead code in CGREP script --- src/etc/cat-and-grep.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/src/etc/cat-and-grep.sh b/src/etc/cat-and-grep.sh index 238f7f5b6602..68c6993ac15e 100755 --- a/src/etc/cat-and-grep.sh +++ b/src/etc/cat-and-grep.sh @@ -33,7 +33,6 @@ while getopts ':vieh' OPTION; do case "$OPTION" in v) INVERT=1 - ERROR_MSG='should not be found' ;; i) GREPFLAGS="i$GREPFLAGS" From 3141a65d253829eadcb525abb9f418fd752c5718 Mon Sep 17 00:00:00 2001 From: jyn Date: Sun, 24 Dec 2023 18:34:31 -0500 Subject: [PATCH 315/366] give a better error for tuple structs in `derive(Diagnostic)` --- .../src/diagnostics/diagnostic_builder.rs | 5 +- .../rustc_macros/src/diagnostics/error.rs | 2 +- .../rustc_macros/src/diagnostics/utils.rs | 2 +- .../diagnostic-derive.stderr | 136 +++++++++--------- .../enforce_slug_naming.stderr | 2 +- .../subdiagnostic-derive.stderr | 134 ++++++++--------- 6 files changed, 142 insertions(+), 139 deletions(-) diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 72f1e5992472..1055f27c1e48 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -253,7 +253,10 @@ impl DiagnosticDeriveVariantBuilder { let mut field_binding = binding_info.binding.clone(); field_binding.set_span(field.ty.span()); - let ident = field.ident.as_ref().unwrap(); + let Some(ident) = field.ident.as_ref() else { + span_err(field.span().unwrap(), "tuple structs are not supported").emit(); + return TokenStream::new(); + }; let ident = format_ident!("{}", ident); // strip `r#` prefix, if present quote! { diff --git a/compiler/rustc_macros/src/diagnostics/error.rs b/compiler/rustc_macros/src/diagnostics/error.rs index 9cdb9fbab12a..a78cf2b63d06 100644 --- a/compiler/rustc_macros/src/diagnostics/error.rs +++ b/compiler/rustc_macros/src/diagnostics/error.rs @@ -56,7 +56,7 @@ fn path_to_string(path: &syn::Path) -> String { /// Returns an error diagnostic on span `span` with msg `msg`. #[must_use] pub(crate) fn span_err>(span: impl MultiSpan, msg: T) -> Diagnostic { - Diagnostic::spanned(span, Level::Error, msg) + Diagnostic::spanned(span, Level::Error, format!("derive(Diagnostic): {}", msg.into())) } /// Emit a diagnostic on span `$span` with msg `$msg` (optionally performing additional decoration diff --git a/compiler/rustc_macros/src/diagnostics/utils.rs b/compiler/rustc_macros/src/diagnostics/utils.rs index 5946b11828ea..612a36ba9aa5 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -243,7 +243,7 @@ impl SetOnce for SpannedOption { *self = Some((value, span)); } Some((_, prev_span)) => { - span_err(span, "specified multiple times") + span_err(span, "attribute specified multiple times") .span_note(*prev_span, "previously specified here") .emit(); } diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index ff7af3885148..03fca17aa55d 100644 --- a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -1,10 +1,10 @@ -error: unsupported type attribute for diagnostic derive enum +error: derive(Diagnostic): unsupported type attribute for diagnostic derive enum --> $DIR/diagnostic-derive.rs:47:1 | LL | #[diag(no_crate_example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:50:5 | LL | Foo, @@ -12,7 +12,7 @@ LL | Foo, | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:52:5 | LL | Bar, @@ -20,13 +20,13 @@ LL | Bar, | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: `#[nonsense(...)]` is not a valid attribute +error: derive(Diagnostic): `#[nonsense(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:63:1 | LL | #[nonsense(no_crate_example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:63:1 | LL | #[nonsense(no_crate_example, code = E0123)] @@ -34,7 +34,7 @@ LL | #[nonsense(no_crate_example, code = E0123)] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:70:1 | LL | #[diag(code = E0123)] @@ -42,13 +42,13 @@ LL | #[diag(code = E0123)] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: diagnostic slug must be the first argument +error: derive(Diagnostic): diagnostic slug must be the first argument --> $DIR/diagnostic-derive.rs:80:16 | LL | #[diag(nonsense("foo"), code = E0123, slug = "foo")] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:80:1 | LL | #[diag(nonsense("foo"), code = E0123, slug = "foo")] @@ -56,7 +56,7 @@ LL | #[diag(nonsense("foo"), code = E0123, slug = "foo")] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: unknown argument +error: derive(Diagnostic): unknown argument --> $DIR/diagnostic-derive.rs:86:8 | LL | #[diag(nonsense = "...", code = E0123, slug = "foo")] @@ -64,7 +64,7 @@ LL | #[diag(nonsense = "...", code = E0123, slug = "foo")] | = note: only the `code` parameter is valid after the slug -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:86:1 | LL | #[diag(nonsense = "...", code = E0123, slug = "foo")] @@ -72,7 +72,7 @@ LL | #[diag(nonsense = "...", code = E0123, slug = "foo")] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: unknown argument +error: derive(Diagnostic): unknown argument --> $DIR/diagnostic-derive.rs:92:8 | LL | #[diag(nonsense = 4, code = E0123, slug = "foo")] @@ -80,7 +80,7 @@ LL | #[diag(nonsense = 4, code = E0123, slug = "foo")] | = note: only the `code` parameter is valid after the slug -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:92:1 | LL | #[diag(nonsense = 4, code = E0123, slug = "foo")] @@ -88,7 +88,7 @@ LL | #[diag(nonsense = 4, code = E0123, slug = "foo")] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: unknown argument +error: derive(Diagnostic): unknown argument --> $DIR/diagnostic-derive.rs:98:40 | LL | #[diag(no_crate_example, code = E0123, slug = "foo")] @@ -96,13 +96,13 @@ LL | #[diag(no_crate_example, code = E0123, slug = "foo")] | = note: only the `code` parameter is valid after the slug -error: `#[suggestion = ...]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion = ...]` is not a valid attribute --> $DIR/diagnostic-derive.rs:105:5 | LL | #[suggestion = "bar"] | ^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:112:8 | LL | #[diag(no_crate_example, code = E0456)] @@ -114,7 +114,7 @@ note: previously specified here LL | #[diag(no_crate_example, code = E0123)] | ^^^^^^^^^^^^^^^^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:112:26 | LL | #[diag(no_crate_example, code = E0456)] @@ -126,7 +126,7 @@ note: previously specified here LL | #[diag(no_crate_example, code = E0123)] | ^^^^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:118:40 | LL | #[diag(no_crate_example, code = E0123, code = E0456)] @@ -138,13 +138,13 @@ note: previously specified here LL | #[diag(no_crate_example, code = E0123, code = E0456)] | ^^^^ -error: diagnostic slug must be the first argument +error: derive(Diagnostic): diagnostic slug must be the first argument --> $DIR/diagnostic-derive.rs:123:43 | LL | #[diag(no_crate_example, no_crate::example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:128:1 | LL | struct KindNotProvided {} @@ -152,7 +152,7 @@ LL | struct KindNotProvided {} | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:131:1 | LL | #[diag(code = E0123)] @@ -160,25 +160,25 @@ LL | #[diag(code = E0123)] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: the `#[primary_span]` attribute can only be applied to fields of type `Span` or `MultiSpan` +error: derive(Diagnostic): the `#[primary_span]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/diagnostic-derive.rs:142:5 | LL | #[primary_span] | ^ -error: `#[nonsense]` is not a valid attribute +error: derive(Diagnostic): `#[nonsense]` is not a valid attribute --> $DIR/diagnostic-derive.rs:150:5 | LL | #[nonsense] | ^ -error: the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` +error: derive(Diagnostic): the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/diagnostic-derive.rs:167:5 | LL | #[label(no_crate_label)] | ^ -error: `name` doesn't refer to a field on this type +error: derive(Diagnostic): `name` doesn't refer to a field on this type --> $DIR/diagnostic-derive.rs:175:46 | LL | #[suggestion(no_crate_suggestion, code = "{name}")] @@ -202,19 +202,19 @@ LL | #[derive(Diagnostic)] = note: if you intended to print `}`, you can escape it using `}}` = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) -error: the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` +error: derive(Diagnostic): the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/diagnostic-derive.rs:210:5 | LL | #[label(no_crate_label)] | ^ -error: suggestion without `code = "..."` +error: derive(Diagnostic): suggestion without `code = "..."` --> $DIR/diagnostic-derive.rs:229:5 | LL | #[suggestion(no_crate_suggestion)] | ^ -error: invalid nested attribute +error: derive(Diagnostic): invalid nested attribute --> $DIR/diagnostic-derive.rs:237:18 | LL | #[suggestion(nonsense = "bar")] @@ -222,13 +222,13 @@ LL | #[suggestion(nonsense = "bar")] | = help: only `no_span`, `style`, `code` and `applicability` are valid nested attributes -error: suggestion without `code = "..."` +error: derive(Diagnostic): suggestion without `code = "..."` --> $DIR/diagnostic-derive.rs:237:5 | LL | #[suggestion(nonsense = "bar")] | ^ -error: invalid nested attribute +error: derive(Diagnostic): invalid nested attribute --> $DIR/diagnostic-derive.rs:246:18 | LL | #[suggestion(msg = "bar")] @@ -236,13 +236,13 @@ LL | #[suggestion(msg = "bar")] | = help: only `no_span`, `style`, `code` and `applicability` are valid nested attributes -error: suggestion without `code = "..."` +error: derive(Diagnostic): suggestion without `code = "..."` --> $DIR/diagnostic-derive.rs:246:5 | LL | #[suggestion(msg = "bar")] | ^ -error: wrong field type for suggestion +error: derive(Diagnostic): wrong field type for suggestion --> $DIR/diagnostic-derive.rs:269:5 | LL | #[suggestion(no_crate_suggestion, code = "This is suggested code")] @@ -250,7 +250,7 @@ LL | #[suggestion(no_crate_suggestion, code = "This is suggested code")] | = help: `#[suggestion(...)]` should be applied to fields of type `Span` or `(Span, Applicability)` -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:285:24 | LL | suggestion: (Span, Span, Applicability), @@ -262,7 +262,7 @@ note: previously specified here LL | suggestion: (Span, Span, Applicability), | ^^^^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:293:33 | LL | suggestion: (Applicability, Applicability, Span), @@ -274,13 +274,13 @@ note: previously specified here LL | suggestion: (Applicability, Applicability, Span), | ^^^^^^^^^^^^^ -error: `#[label = ...]` is not a valid attribute +error: derive(Diagnostic): `#[label = ...]` is not a valid attribute --> $DIR/diagnostic-derive.rs:300:5 | LL | #[label = "bar"] | ^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:451:5 | LL | #[suggestion(no_crate_suggestion, code = "...", applicability = "maybe-incorrect")] @@ -292,37 +292,37 @@ note: previously specified here LL | suggestion: (Span, Applicability), | ^^^^^^^^^^^^^ -error: invalid applicability +error: derive(Diagnostic): invalid applicability --> $DIR/diagnostic-derive.rs:459:69 | LL | #[suggestion(no_crate_suggestion, code = "...", applicability = "batman")] | ^^^^^^^^ -error: the `#[help(...)]` attribute can only be applied to fields of type `Span`, `MultiSpan`, `bool` or `()` +error: derive(Diagnostic): the `#[help(...)]` attribute can only be applied to fields of type `Span`, `MultiSpan`, `bool` or `()` --> $DIR/diagnostic-derive.rs:526:5 | LL | #[help(no_crate_help)] | ^ -error: a diagnostic slug must be the first argument to the attribute +error: derive(Diagnostic): a diagnostic slug must be the first argument to the attribute --> $DIR/diagnostic-derive.rs:535:32 | LL | #[label(no_crate_label, foo)] | ^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/diagnostic-derive.rs:543:29 | LL | #[label(no_crate_label, foo = "...")] | ^^^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/diagnostic-derive.rs:551:29 | LL | #[label(no_crate_label, foo("..."))] | ^^^ -error: `#[primary_span]` is not a valid attribute +error: derive(Diagnostic): `#[primary_span]` is not a valid attribute --> $DIR/diagnostic-derive.rs:563:5 | LL | #[primary_span] @@ -330,13 +330,13 @@ LL | #[primary_span] | = help: the `primary_span` field attribute is not valid for lint diagnostics -error: `#[error(...)]` is not a valid attribute +error: derive(Diagnostic): `#[error(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:583:1 | LL | #[error(no_crate_example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:583:1 | LL | #[error(no_crate_example, code = E0123)] @@ -344,13 +344,13 @@ LL | #[error(no_crate_example, code = E0123)] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: `#[warn_(...)]` is not a valid attribute +error: derive(Diagnostic): `#[warn_(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:590:1 | LL | #[warn_(no_crate_example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:590:1 | LL | #[warn_(no_crate_example, code = E0123)] @@ -358,13 +358,13 @@ LL | #[warn_(no_crate_example, code = E0123)] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: `#[lint(...)]` is not a valid attribute +error: derive(Diagnostic): `#[lint(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:597:1 | LL | #[lint(no_crate_example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:597:1 | LL | #[lint(no_crate_example, code = E0123)] @@ -372,13 +372,13 @@ LL | #[lint(no_crate_example, code = E0123)] | = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` -error: `#[lint(...)]` is not a valid attribute +error: derive(Diagnostic): `#[lint(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:604:1 | LL | #[lint(no_crate_example, code = E0123)] | ^ -error: diagnostic slug not specified +error: derive(Diagnostic): diagnostic slug not specified --> $DIR/diagnostic-derive.rs:604:1 | LL | #[lint(no_crate_example, code = E0123)] @@ -386,7 +386,7 @@ LL | #[lint(no_crate_example, code = E0123)] | = help: specify the slug as the first argument to the attribute, such as `#[diag(compiletest_example)]` -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:613:53 | LL | #[suggestion(no_crate_suggestion, code = "...", code = ",,,")] @@ -398,7 +398,7 @@ note: previously specified here LL | #[suggestion(no_crate_suggestion, code = "...", code = ",,,")] | ^^^^ -error: wrong types for suggestion +error: derive(Diagnostic): wrong types for suggestion --> $DIR/diagnostic-derive.rs:622:24 | LL | suggestion: (Span, usize), @@ -406,7 +406,7 @@ LL | suggestion: (Span, usize), | = help: `#[suggestion(...)]` on a tuple field must be applied to fields of type `(Span, Applicability)` -error: wrong types for suggestion +error: derive(Diagnostic): wrong types for suggestion --> $DIR/diagnostic-derive.rs:630:17 | LL | suggestion: (Span,), @@ -414,13 +414,13 @@ LL | suggestion: (Span,), | = help: `#[suggestion(...)]` on a tuple field must be applied to fields of type `(Span, Applicability)` -error: suggestion without `code = "..."` +error: derive(Diagnostic): suggestion without `code = "..."` --> $DIR/diagnostic-derive.rs:637:5 | LL | #[suggestion(no_crate_suggestion)] | ^ -error: `#[multipart_suggestion(...)]` is not a valid attribute +error: derive(Diagnostic): `#[multipart_suggestion(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:644:1 | LL | #[multipart_suggestion(no_crate_suggestion)] @@ -428,7 +428,7 @@ LL | #[multipart_suggestion(no_crate_suggestion)] | = help: consider creating a `Subdiagnostic` instead -error: `#[multipart_suggestion(...)]` is not a valid attribute +error: derive(Diagnostic): `#[multipart_suggestion(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:647:1 | LL | #[multipart_suggestion()] @@ -436,7 +436,7 @@ LL | #[multipart_suggestion()] | = help: consider creating a `Subdiagnostic` instead -error: `#[multipart_suggestion(...)]` is not a valid attribute +error: derive(Diagnostic): `#[multipart_suggestion(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:651:5 | LL | #[multipart_suggestion(no_crate_suggestion)] @@ -444,7 +444,7 @@ LL | #[multipart_suggestion(no_crate_suggestion)] | = help: consider creating a `Subdiagnostic` instead -error: `#[suggestion(...)]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:659:1 | LL | #[suggestion(no_crate_suggestion, code = "...")] @@ -452,7 +452,7 @@ LL | #[suggestion(no_crate_suggestion, code = "...")] | = help: `#[label]` and `#[suggestion]` can only be applied to fields -error: `#[label]` is not a valid attribute +error: derive(Diagnostic): `#[label]` is not a valid attribute --> $DIR/diagnostic-derive.rs:668:1 | LL | #[label] @@ -460,61 +460,61 @@ LL | #[label] | = help: `#[label]` and `#[suggestion]` can only be applied to fields -error: `#[subdiagnostic(...)]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:702:5 | LL | #[subdiagnostic(bad)] | ^ -error: `#[subdiagnostic = ...]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic = ...]` is not a valid attribute --> $DIR/diagnostic-derive.rs:710:5 | LL | #[subdiagnostic = "bad"] | ^ -error: `#[subdiagnostic(...)]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:718:5 | LL | #[subdiagnostic(bad, bad)] | ^ -error: `#[subdiagnostic(...)]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:726:5 | LL | #[subdiagnostic("bad")] | ^ -error: `#[subdiagnostic(...)]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:734:5 | LL | #[subdiagnostic(eager)] | ^ -error: `#[subdiagnostic(...)]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:742:5 | LL | #[subdiagnostic(eager)] | ^ -error: `#[subdiagnostic(...)]` is not a valid attribute +error: derive(Diagnostic): `#[subdiagnostic(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:763:5 | LL | #[subdiagnostic(eager)] | ^ -error: expected at least one string literal for `code(...)` +error: derive(Diagnostic): expected at least one string literal for `code(...)` --> $DIR/diagnostic-derive.rs:794:23 | LL | #[suggestion(code())] | ^ -error: `code(...)` must contain only string literals +error: derive(Diagnostic): `code(...)` must contain only string literals --> $DIR/diagnostic-derive.rs:802:23 | LL | #[suggestion(code(foo))] | ^^^ -error: `#[suggestion(...)]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion(...)]` is not a valid attribute --> $DIR/diagnostic-derive.rs:826:5 | LL | #[suggestion(no_crate_suggestion, code = "")] diff --git a/tests/ui-fulldeps/session-diagnostic/enforce_slug_naming.stderr b/tests/ui-fulldeps/session-diagnostic/enforce_slug_naming.stderr index df1bad3cad0c..4f54239f0fa3 100644 --- a/tests/ui-fulldeps/session-diagnostic/enforce_slug_naming.stderr +++ b/tests/ui-fulldeps/session-diagnostic/enforce_slug_naming.stderr @@ -1,4 +1,4 @@ -error: diagnostic slug and crate name do not match +error: derive(Diagnostic): diagnostic slug and crate name do not match --> $DIR/enforce_slug_naming.rs:22:8 | LL | #[diag(compiletest_example, code = E0123)] diff --git a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr index 96f6ef06d1dc..0ae7ba4c4973 100644 --- a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr @@ -1,142 +1,142 @@ -error: label without `#[primary_span]` field +error: derive(Diagnostic): label without `#[primary_span]` field --> $DIR/subdiagnostic-derive.rs:51:1 | LL | #[label(no_crate_example)] | ^ -error: diagnostic slug must be first argument of a `#[label(...)]` attribute +error: derive(Diagnostic): diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:58:1 | LL | #[label] | ^ -error: `#[foo]` is not a valid attribute +error: derive(Diagnostic): `#[foo]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:67:1 | LL | #[foo] | ^ -error: `#[label = ...]` is not a valid attribute +error: derive(Diagnostic): `#[label = ...]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:77:1 | LL | #[label = "..."] | ^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:86:9 | LL | #[label(bug = "...")] | ^^^ -error: diagnostic slug must be first argument of a `#[label(...)]` attribute +error: derive(Diagnostic): diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:86:1 | LL | #[label(bug = "...")] | ^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:106:9 | LL | #[label(slug = 4)] | ^^^^ -error: diagnostic slug must be first argument of a `#[label(...)]` attribute +error: derive(Diagnostic): diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:106:1 | LL | #[label(slug = 4)] | ^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:116:9 | LL | #[label(slug("..."))] | ^^^^ -error: diagnostic slug must be first argument of a `#[label(...)]` attribute +error: derive(Diagnostic): diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:116:1 | LL | #[label(slug("..."))] | ^ -error: diagnostic slug must be first argument of a `#[label(...)]` attribute +error: derive(Diagnostic): diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:136:1 | LL | #[label()] | ^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:145:27 | LL | #[label(no_crate_example, code = "...")] | ^^^^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:154:27 | LL | #[label(no_crate_example, applicability = "machine-applicable")] | ^^^^^^^^^^^^^ -error: unsupported type attribute for subdiagnostic enum +error: derive(Diagnostic): unsupported type attribute for subdiagnostic enum --> $DIR/subdiagnostic-derive.rs:163:1 | LL | #[foo] | ^ -error: `#[bar]` is not a valid attribute +error: derive(Diagnostic): `#[bar]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:177:5 | LL | #[bar] | ^ -error: `#[bar = ...]` is not a valid attribute +error: derive(Diagnostic): `#[bar = ...]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:189:5 | LL | #[bar = "..."] | ^ -error: `#[bar = ...]` is not a valid attribute +error: derive(Diagnostic): `#[bar = ...]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:201:5 | LL | #[bar = 4] | ^ -error: `#[bar(...)]` is not a valid attribute +error: derive(Diagnostic): `#[bar(...)]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:213:5 | LL | #[bar("...")] | ^ -error: only `no_span` is a valid nested attribute +error: derive(Diagnostic): only `no_span` is a valid nested attribute --> $DIR/subdiagnostic-derive.rs:225:13 | LL | #[label(code = "...")] | ^^^^ -error: diagnostic slug must be first argument of a `#[label(...)]` attribute +error: derive(Diagnostic): diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:225:5 | LL | #[label(code = "...")] | ^ -error: the `#[primary_span]` attribute can only be applied to fields of type `Span` or `MultiSpan` +error: derive(Diagnostic): the `#[primary_span]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/subdiagnostic-derive.rs:254:5 | LL | #[primary_span] | ^ -error: label without `#[primary_span]` field +error: derive(Diagnostic): label without `#[primary_span]` field --> $DIR/subdiagnostic-derive.rs:251:1 | LL | #[label(no_crate_example)] | ^ -error: `#[applicability]` is only valid on suggestions +error: derive(Diagnostic): `#[applicability]` is only valid on suggestions --> $DIR/subdiagnostic-derive.rs:264:5 | LL | #[applicability] | ^ -error: `#[bar]` is not a valid attribute +error: derive(Diagnostic): `#[bar]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:274:5 | LL | #[bar] @@ -144,13 +144,13 @@ LL | #[bar] | = help: only `primary_span`, `applicability` and `skip_arg` are valid field attributes -error: `#[bar = ...]` is not a valid attribute +error: derive(Diagnostic): `#[bar = ...]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:285:5 | LL | #[bar = "..."] | ^ -error: `#[bar(...)]` is not a valid attribute +error: derive(Diagnostic): `#[bar(...)]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:296:5 | LL | #[bar("...")] @@ -158,13 +158,13 @@ LL | #[bar("...")] | = help: only `primary_span`, `applicability` and `skip_arg` are valid field attributes -error: a diagnostic slug must be the first argument to the attribute +error: derive(Diagnostic): a diagnostic slug must be the first argument to the attribute --> $DIR/subdiagnostic-derive.rs:328:44 | LL | #[label(no_crate_example, no_crate::example)] | ^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/subdiagnostic-derive.rs:341:5 | LL | #[primary_span] @@ -176,13 +176,13 @@ note: previously specified here LL | #[primary_span] | ^ -error: subdiagnostic kind not specified +error: derive(Diagnostic): subdiagnostic kind not specified --> $DIR/subdiagnostic-derive.rs:347:8 | LL | struct AG { | ^^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/subdiagnostic-derive.rs:384:46 | LL | #[suggestion(no_crate_example, code = "...", code = "...")] @@ -194,7 +194,7 @@ note: previously specified here LL | #[suggestion(no_crate_example, code = "...", code = "...")] | ^^^^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/subdiagnostic-derive.rs:402:5 | LL | #[applicability] @@ -206,49 +206,49 @@ note: previously specified here LL | #[applicability] | ^ -error: the `#[applicability]` attribute can only be applied to fields of type `Applicability` +error: derive(Diagnostic): the `#[applicability]` attribute can only be applied to fields of type `Applicability` --> $DIR/subdiagnostic-derive.rs:412:5 | LL | #[applicability] | ^ -error: suggestion without `code = "..."` +error: derive(Diagnostic): suggestion without `code = "..."` --> $DIR/subdiagnostic-derive.rs:425:1 | LL | #[suggestion(no_crate_example)] | ^ -error: invalid applicability +error: derive(Diagnostic): invalid applicability --> $DIR/subdiagnostic-derive.rs:435:62 | LL | #[suggestion(no_crate_example, code = "...", applicability = "foo")] | ^^^^^ -error: suggestion without `#[primary_span]` field +error: derive(Diagnostic): suggestion without `#[primary_span]` field --> $DIR/subdiagnostic-derive.rs:453:1 | LL | #[suggestion(no_crate_example, code = "...")] | ^ -error: unsupported type attribute for subdiagnostic enum +error: derive(Diagnostic): unsupported type attribute for subdiagnostic enum --> $DIR/subdiagnostic-derive.rs:467:1 | LL | #[label] | ^ -error: `var` doesn't refer to a field on this type +error: derive(Diagnostic): `var` doesn't refer to a field on this type --> $DIR/subdiagnostic-derive.rs:487:39 | LL | #[suggestion(no_crate_example, code = "{var}", applicability = "machine-applicable")] | ^^^^^^^ -error: `var` doesn't refer to a field on this type +error: derive(Diagnostic): `var` doesn't refer to a field on this type --> $DIR/subdiagnostic-derive.rs:506:43 | LL | #[suggestion(no_crate_example, code = "{var}", applicability = "machine-applicable")] | ^^^^^^^ -error: `#[suggestion_part]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion_part]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:529:5 | LL | #[suggestion_part] @@ -256,7 +256,7 @@ LL | #[suggestion_part] | = help: `#[suggestion_part(...)]` is only valid in multipart suggestions, use `#[primary_span]` instead -error: `#[suggestion_part(...)]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion_part(...)]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:532:5 | LL | #[suggestion_part(code = "...")] @@ -264,13 +264,13 @@ LL | #[suggestion_part(code = "...")] | = help: `#[suggestion_part(...)]` is only valid in multipart suggestions -error: suggestion without `#[primary_span]` field +error: derive(Diagnostic): suggestion without `#[primary_span]` field --> $DIR/subdiagnostic-derive.rs:526:1 | LL | #[suggestion(no_crate_example, code = "...")] | ^ -error: invalid nested attribute +error: derive(Diagnostic): invalid nested attribute --> $DIR/subdiagnostic-derive.rs:541:42 | LL | #[multipart_suggestion(no_crate_example, code = "...", applicability = "machine-applicable")] @@ -278,25 +278,25 @@ LL | #[multipart_suggestion(no_crate_example, code = "...", applicability = "mac | = help: only `no_span`, `style` and `applicability` are valid nested attributes -error: multipart suggestion without any `#[suggestion_part(...)]` fields +error: derive(Diagnostic): multipart suggestion without any `#[suggestion_part(...)]` fields --> $DIR/subdiagnostic-derive.rs:541:1 | LL | #[multipart_suggestion(no_crate_example, code = "...", applicability = "machine-applicable")] | ^ -error: `#[suggestion_part(...)]` attribute without `code = "..."` +error: derive(Diagnostic): `#[suggestion_part(...)]` attribute without `code = "..."` --> $DIR/subdiagnostic-derive.rs:551:5 | LL | #[suggestion_part] | ^ -error: `#[suggestion_part(...)]` attribute without `code = "..."` +error: derive(Diagnostic): `#[suggestion_part(...)]` attribute without `code = "..."` --> $DIR/subdiagnostic-derive.rs:559:5 | LL | #[suggestion_part()] | ^ -error: `#[primary_span]` is not a valid attribute +error: derive(Diagnostic): `#[primary_span]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:568:5 | LL | #[primary_span] @@ -304,43 +304,43 @@ LL | #[primary_span] | = help: multipart suggestions use one or more `#[suggestion_part]`s rather than one `#[primary_span]` -error: multipart suggestion without any `#[suggestion_part(...)]` fields +error: derive(Diagnostic): multipart suggestion without any `#[suggestion_part(...)]` fields --> $DIR/subdiagnostic-derive.rs:565:1 | LL | #[multipart_suggestion(no_crate_example)] | ^ -error: `#[suggestion_part(...)]` attribute without `code = "..."` +error: derive(Diagnostic): `#[suggestion_part(...)]` attribute without `code = "..."` --> $DIR/subdiagnostic-derive.rs:576:5 | LL | #[suggestion_part] | ^ -error: `#[suggestion_part(...)]` attribute without `code = "..."` +error: derive(Diagnostic): `#[suggestion_part(...)]` attribute without `code = "..."` --> $DIR/subdiagnostic-derive.rs:579:5 | LL | #[suggestion_part()] | ^ -error: `code` is the only valid nested attribute +error: derive(Diagnostic): `code` is the only valid nested attribute --> $DIR/subdiagnostic-derive.rs:582:23 | LL | #[suggestion_part(foo = "bar")] | ^^^ -error: the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` +error: derive(Diagnostic): the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/subdiagnostic-derive.rs:587:5 | LL | #[suggestion_part(code = "...")] | ^ -error: the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` +error: derive(Diagnostic): the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/subdiagnostic-derive.rs:590:5 | LL | #[suggestion_part()] | ^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/subdiagnostic-derive.rs:598:37 | LL | #[suggestion_part(code = "...", code = ",,,")] @@ -352,37 +352,37 @@ note: previously specified here LL | #[suggestion_part(code = "...", code = ",,,")] | ^^^^ -error: `#[applicability]` has no effect if all `#[suggestion]`/`#[multipart_suggestion]` attributes have a static `applicability = "..."` +error: derive(Diagnostic): `#[applicability]` has no effect if all `#[suggestion]`/`#[multipart_suggestion]` attributes have a static `applicability = "..."` --> $DIR/subdiagnostic-derive.rs:627:5 | LL | #[applicability] | ^ -error: expected exactly one string literal for `code = ...` +error: derive(Diagnostic): expected exactly one string literal for `code = ...` --> $DIR/subdiagnostic-derive.rs:675:34 | LL | #[suggestion_part(code("foo"))] | ^ -error: expected exactly one string literal for `code = ...` +error: derive(Diagnostic): expected exactly one string literal for `code = ...` --> $DIR/subdiagnostic-derive.rs:686:41 | LL | #[suggestion_part(code("foo", "bar"))] | ^ -error: expected exactly one string literal for `code = ...` +error: derive(Diagnostic): expected exactly one string literal for `code = ...` --> $DIR/subdiagnostic-derive.rs:697:30 | LL | #[suggestion_part(code(3))] | ^ -error: expected exactly one string literal for `code = ...` +error: derive(Diagnostic): expected exactly one string literal for `code = ...` --> $DIR/subdiagnostic-derive.rs:708:29 | LL | #[suggestion_part(code())] | ^ -error: specified multiple times +error: derive(Diagnostic): attribute specified multiple times --> $DIR/subdiagnostic-derive.rs:763:1 | LL | #[suggestion(no_crate_example, code = "", style = "hidden", style = "normal")] @@ -394,7 +394,7 @@ note: previously specified here LL | #[suggestion(no_crate_example, code = "", style = "hidden", style = "normal")] | ^ -error: `#[suggestion_hidden(...)]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion_hidden(...)]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:772:1 | LL | #[suggestion_hidden(no_crate_example, code = "")] @@ -402,7 +402,7 @@ LL | #[suggestion_hidden(no_crate_example, code = "")] | = help: Use `#[suggestion(..., style = "hidden")]` instead -error: `#[suggestion_hidden(...)]` is not a valid attribute +error: derive(Diagnostic): `#[suggestion_hidden(...)]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:780:1 | LL | #[suggestion_hidden(no_crate_example, code = "", style = "normal")] @@ -410,7 +410,7 @@ LL | #[suggestion_hidden(no_crate_example, code = "", style = "normal")] | = help: Use `#[suggestion(..., style = "hidden")]` instead -error: invalid suggestion style +error: derive(Diagnostic): invalid suggestion style --> $DIR/subdiagnostic-derive.rs:788:51 | LL | #[suggestion(no_crate_example, code = "", style = "foo")] @@ -418,25 +418,25 @@ LL | #[suggestion(no_crate_example, code = "", style = "foo")] | = help: valid styles are `normal`, `short`, `hidden`, `verbose` and `tool-only` -error: expected `= "xxx"` +error: derive(Diagnostic): expected `= "xxx"` --> $DIR/subdiagnostic-derive.rs:796:49 | LL | #[suggestion(no_crate_example, code = "", style = 42)] | ^ -error: a diagnostic slug must be the first argument to the attribute +error: derive(Diagnostic): a diagnostic slug must be the first argument to the attribute --> $DIR/subdiagnostic-derive.rs:804:48 | LL | #[suggestion(no_crate_example, code = "", style)] | ^ -error: expected `= "xxx"` +error: derive(Diagnostic): expected `= "xxx"` --> $DIR/subdiagnostic-derive.rs:812:48 | LL | #[suggestion(no_crate_example, code = "", style("foo"))] | ^ -error: `#[primary_span]` is not a valid attribute +error: derive(Diagnostic): `#[primary_span]` is not a valid attribute --> $DIR/subdiagnostic-derive.rs:825:5 | LL | #[primary_span] @@ -445,7 +445,7 @@ LL | #[primary_span] = note: there must be exactly one primary span = help: to create a suggestion with multiple spans, use `#[multipart_suggestion]` instead -error: suggestion without `#[primary_span]` field +error: derive(Diagnostic): suggestion without `#[primary_span]` field --> $DIR/subdiagnostic-derive.rs:822:1 | LL | #[suggestion(no_crate_example, code = "")] From f1e5b365f07975c63e2116973a0ed85e251ebe17 Mon Sep 17 00:00:00 2001 From: jyn Date: Thu, 19 Sep 2024 10:08:53 -0400 Subject: [PATCH 316/366] port `tests/ui/linkage-attr/framework` to run-make this makes it much easier to understand test failures. before: ``` diff of stderr: 1 error: linking with `LINKER` failed: exit status: 1 2 | - ld: Undefined symbols: 4 _CFRunLoopGetTypeID, referenced from: 5 clang: error: linker command failed with exit code 1 (use -v to see invocation) ``` after: ``` === HAYSTACK === error: linking with `cc` failed: exit status: 1 | = note: use `--verbose` to show all linker arguments = note: Undefined symbols for architecture arm64: "_CFRunLoopGetTypeID", referenced from: main::main::hbb553f5dda62d3ea in main.main.d17f5fbe6225cf88-cgu.0.rcgu.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) error: aborting due to 1 previous error === NEEDLE === _CFRunLoopGetTypeID\.?, referenced from: thread 'main' panicked at /Users/jyn/git/rust-lang/rust/tests/run-make/linkage-attr-framework/rmake.rs:22:10: needle was not found in haystack ``` this also fixes a failure related to missing whitespace; we don't actually care about whitespace in this test. --- tests/run-make/linkage-attr-framework/main.rs | 17 ++++++++++ .../run-make/linkage-attr-framework/rmake.rs | 26 +++++++++++++++ tests/ui/linkage-attr/framework.omit.stderr | 8 ----- tests/ui/linkage-attr/framework.rs | 32 ------------------- 4 files changed, 43 insertions(+), 40 deletions(-) create mode 100644 tests/run-make/linkage-attr-framework/main.rs create mode 100644 tests/run-make/linkage-attr-framework/rmake.rs delete mode 100644 tests/ui/linkage-attr/framework.omit.stderr delete mode 100644 tests/ui/linkage-attr/framework.rs diff --git a/tests/run-make/linkage-attr-framework/main.rs b/tests/run-make/linkage-attr-framework/main.rs new file mode 100644 index 000000000000..8efabc83e620 --- /dev/null +++ b/tests/run-make/linkage-attr-framework/main.rs @@ -0,0 +1,17 @@ +#![cfg_attr(any(weak, both), feature(link_arg_attribute))] + +#[cfg_attr(any(link, both), link(name = "CoreFoundation", kind = "framework"))] +#[cfg_attr( + any(weak, both), + link(name = "-weak_framework", kind = "link-arg", modifiers = "+verbatim"), + link(name = "CoreFoundation", kind = "link-arg", modifiers = "+verbatim") +)] +extern "C" { + fn CFRunLoopGetTypeID() -> core::ffi::c_ulong; +} + +fn main() { + unsafe { + CFRunLoopGetTypeID(); + } +} diff --git a/tests/run-make/linkage-attr-framework/rmake.rs b/tests/run-make/linkage-attr-framework/rmake.rs new file mode 100644 index 000000000000..4450350f96e4 --- /dev/null +++ b/tests/run-make/linkage-attr-framework/rmake.rs @@ -0,0 +1,26 @@ +//! Check that linking frameworks on Apple platforms works. + +//@ only-apple + +use run_make_support::{Rustc, run, rustc}; + +fn compile(cfg: &str) -> Rustc { + let mut rustc = rustc(); + rustc.cfg(cfg).input("main.rs"); + rustc +} + +fn main() { + for cfg in ["link", "weak", "both"] { + compile(cfg).run(); + run("main"); + } + + let errs = compile("omit").run_fail(); + // The linker's exact error output changes between Xcode versions, depends on + // linker invocation details, and the linker sometimes outputs more warnings. + errs.assert_stderr_contains_regex(r"error: linking with `.*` failed"); + errs.assert_stderr_contains_regex(r"(Undefined symbols|ld: symbol[^\s]* not found)"); + errs.assert_stderr_contains_regex(r".?_CFRunLoopGetTypeID.?, referenced from:"); + errs.assert_stderr_contains("clang: error: linker command failed with exit code 1"); +} diff --git a/tests/ui/linkage-attr/framework.omit.stderr b/tests/ui/linkage-attr/framework.omit.stderr deleted file mode 100644 index 23e017cb0122..000000000000 --- a/tests/ui/linkage-attr/framework.omit.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: linking with `LINKER` failed: exit status: 1 - | - ld: Undefined symbols: - _CFRunLoopGetTypeID, referenced from: - clang: error: linker command failed with exit code 1 (use -v to see invocation) - - -error: aborting due to 1 previous error diff --git a/tests/ui/linkage-attr/framework.rs b/tests/ui/linkage-attr/framework.rs deleted file mode 100644 index 08f4394db21f..000000000000 --- a/tests/ui/linkage-attr/framework.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Check that linking frameworks on Apple platforms works. -//@ only-apple -//@ revisions: omit link weak both -//@ [omit]build-fail -//@ [link]run-pass -//@ [weak]run-pass -//@ [both]run-pass - -// The linker's exact error output changes between Xcode versions, depends on -// linker invocation details, and the linker sometimes outputs more warnings. -//@ compare-output-lines-by-subset -//@ normalize-stderr-test: "linking with `.*` failed" -> "linking with `LINKER` failed" -//@ normalize-stderr-test: "Undefined symbols for architecture .*" -> "ld: Undefined symbols:" -//@ normalize-stderr-test: "._CFRunLoopGetTypeID.," -> "_CFRunLoopGetTypeID," - -#![cfg_attr(any(weak, both), feature(link_arg_attribute))] - -#[cfg_attr(any(link, both), link(name = "CoreFoundation", kind = "framework"))] -#[cfg_attr( - any(weak, both), - link(name = "-weak_framework", kind = "link-arg", modifiers = "+verbatim"), - link(name = "CoreFoundation", kind = "link-arg", modifiers = "+verbatim") -)] -extern "C" { - fn CFRunLoopGetTypeID() -> core::ffi::c_ulong; -} - -pub fn main() { - unsafe { - CFRunLoopGetTypeID(); - } -} From 675f447d886ea4cf1c3d0e39676cd3bf36cf88ba Mon Sep 17 00:00:00 2001 From: jyn Date: Sat, 27 Jan 2024 19:15:10 -0500 Subject: [PATCH 317/366] don't pass `-L .../auxiliary` unless it exists this avoids warnings from macOS ld --- src/tools/compiletest/src/runtest.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 3a6eca7dc5db..a8a71c196fc0 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1096,6 +1096,10 @@ impl<'test> TestCx<'test> { self.config.target.contains("vxworks") && !self.is_vxworks_pure_static() } + fn has_aux_dir(&self) -> bool { + !self.props.aux.builds.is_empty() || !self.props.aux.crates.is_empty() + } + fn aux_output_dir(&self) -> PathBuf { let aux_dir = self.aux_output_dir_name(); @@ -1649,7 +1653,11 @@ impl<'test> TestCx<'test> { } if let LinkToAux::Yes = link_to_aux { - rustc.arg("-L").arg(self.aux_output_dir_name()); + // if we pass an `-L` argument to a directory that doesn't exist, + // macOS ld emits warnings which disrupt the .stderr files + if self.has_aux_dir() { + rustc.arg("-L").arg(self.aux_output_dir_name()); + } } rustc.args(&self.props.compile_flags); From 27207069d81c52cabc0e98d7eaecdede8c0f6356 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 27 Oct 2024 17:21:23 -0700 Subject: [PATCH 318/366] rustc_transmute: Directly use types from rustc_abi --- Cargo.lock | 2 +- compiler/rustc_transmute/Cargo.toml | 6 +++--- compiler/rustc_transmute/src/layout/mod.rs | 2 +- compiler/rustc_transmute/src/layout/tree.rs | 10 +++++----- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e814e7d7fd..f0e035c025ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4496,6 +4496,7 @@ name = "rustc_transmute" version = "0.0.0" dependencies = [ "itertools", + "rustc_abi", "rustc_ast_ir", "rustc_data_structures", "rustc_hir", @@ -4503,7 +4504,6 @@ dependencies = [ "rustc_macros", "rustc_middle", "rustc_span", - "rustc_target", "tracing", ] diff --git a/compiler/rustc_transmute/Cargo.toml b/compiler/rustc_transmute/Cargo.toml index 4732e968f6b4..6a98be185039 100644 --- a/compiler/rustc_transmute/Cargo.toml +++ b/compiler/rustc_transmute/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start +rustc_abi = { path = "../rustc_abi", optional = true } rustc_ast_ir = { path = "../rustc_ast_ir", optional = true } rustc_data_structures = { path = "../rustc_data_structures" } rustc_hir = { path = "../rustc_hir", optional = true } @@ -12,19 +13,18 @@ rustc_infer = { path = "../rustc_infer", optional = true } rustc_macros = { path = "../rustc_macros", optional = true } rustc_middle = { path = "../rustc_middle", optional = true } rustc_span = { path = "../rustc_span", optional = true } -rustc_target = { path = "../rustc_target", optional = true } tracing = "0.1" # tidy-alphabetical-end [features] rustc = [ + "dep:rustc_abi", + "dep:rustc_ast_ir", "dep:rustc_hir", "dep:rustc_infer", "dep:rustc_macros", "dep:rustc_middle", "dep:rustc_span", - "dep:rustc_target", - "dep:rustc_ast_ir", ] [dev-dependencies] diff --git a/compiler/rustc_transmute/src/layout/mod.rs b/compiler/rustc_transmute/src/layout/mod.rs index a5c47c480e18..c4c01a8fac31 100644 --- a/compiler/rustc_transmute/src/layout/mod.rs +++ b/compiler/rustc_transmute/src/layout/mod.rs @@ -62,10 +62,10 @@ impl Ref for ! { pub mod rustc { use std::fmt::{self, Write}; + use rustc_abi::Layout; use rustc_middle::mir::Mutability; use rustc_middle::ty::layout::{HasTyCtxt, LayoutCx, LayoutError}; use rustc_middle::ty::{self, Ty}; - use rustc_target::abi::Layout; /// A reference in the layout. #[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)] diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index 17eddbfcd7f5..94ca4c13d084 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -171,12 +171,12 @@ where #[cfg(feature = "rustc")] pub(crate) mod rustc { + use rustc_abi::{ + FieldIdx, FieldsShape, Layout, Size, TagEncoding, TyAndLayout, VariantIdx, Variants, + }; use rustc_middle::ty::layout::{HasTyCtxt, LayoutCx, LayoutError}; use rustc_middle::ty::{self, AdtDef, AdtKind, List, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::ErrorGuaranteed; - use rustc_target::abi::{ - FieldIdx, FieldsShape, Layout, Size, TagEncoding, TyAndLayout, VariantIdx, Variants, - }; use super::Tree; use crate::layout::rustc::{Def, Ref, layout_of}; @@ -206,7 +206,7 @@ pub(crate) mod rustc { impl<'tcx> Tree, Ref<'tcx>> { pub(crate) fn from_ty(ty: Ty<'tcx>, cx: LayoutCx<'tcx>) -> Result { - use rustc_target::abi::HasDataLayout; + use rustc_abi::HasDataLayout; let layout = layout_of(cx, ty)?; if let Err(e) = ty.error_reported() { @@ -446,7 +446,7 @@ pub(crate) mod rustc { /// Constructs a `Tree` representing the value of a enum tag. fn from_tag(tag: ScalarInt, tcx: TyCtxt<'tcx>) -> Self { - use rustc_target::abi::Endian; + use rustc_abi::Endian; let size = tag.size(); let bits = tag.to_bits(size); let bytes: [u8; 16]; From 4839d6e6e51f29c6bd9b581df520a8f1a6d278b9 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 27 Oct 2024 20:38:33 -0700 Subject: [PATCH 319/366] compiler: Add rustc_abi dependence to the compiler Depend on rustc_abi in compiler crates that use it indirectly but have not yet taken on that dependency, and are not entangled in my other PRs. This leaves an "excise rustc_target" step after the dust settles. --- Cargo.lock | 8 ++++++++ compiler/rustc_errors/Cargo.toml | 1 + compiler/rustc_errors/src/diagnostic_impls.rs | 2 +- compiler/rustc_hir_analysis/Cargo.toml | 1 + compiler/rustc_hir_analysis/src/check/check.rs | 2 +- compiler/rustc_hir_analysis/src/check/intrinsicck.rs | 2 +- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- compiler/rustc_metadata/Cargo.toml | 1 + compiler/rustc_metadata/src/rmeta/mod.rs | 2 +- compiler/rustc_mir_dataflow/Cargo.toml | 1 + compiler/rustc_mir_dataflow/src/drop_flag_effects.rs | 2 +- compiler/rustc_mir_dataflow/src/elaborate_drops.rs | 2 +- compiler/rustc_mir_dataflow/src/value_analysis.rs | 2 +- compiler/rustc_passes/Cargo.toml | 1 + compiler/rustc_passes/src/dead.rs | 2 +- compiler/rustc_passes/src/layout_test.rs | 2 +- compiler/rustc_pattern_analysis/Cargo.toml | 3 +++ compiler/rustc_pattern_analysis/src/rustc.rs | 2 +- compiler/rustc_pattern_analysis/src/rustc/print.rs | 2 +- compiler/rustc_session/Cargo.toml | 1 + compiler/rustc_session/src/code_stats.rs | 2 +- compiler/rustc_session/src/config/cfg.rs | 2 +- compiler/rustc_symbol_mangling/Cargo.toml | 2 ++ compiler/rustc_symbol_mangling/src/v0.rs | 2 +- 24 files changed, 34 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e814e7d7fd..021cb3db5687 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3621,6 +3621,7 @@ version = "0.0.0" dependencies = [ "annotate-snippets 0.11.4", "derive_setters", + "rustc_abi", "rustc_ast", "rustc_ast_pretty", "rustc_data_structures", @@ -3718,6 +3719,7 @@ name = "rustc_hir_analysis" version = "0.0.0" dependencies = [ "itertools", + "rustc_abi", "rustc_arena", "rustc_ast", "rustc_attr", @@ -3980,6 +3982,7 @@ dependencies = [ "bitflags 2.6.0", "libloading", "odht", + "rustc_abi", "rustc_ast", "rustc_attr", "rustc_data_structures", @@ -4074,6 +4077,7 @@ version = "0.0.0" dependencies = [ "polonius-engine", "regex", + "rustc_abi", "rustc_ast", "rustc_data_structures", "rustc_errors", @@ -4187,6 +4191,7 @@ dependencies = [ name = "rustc_passes" version = "0.0.0" dependencies = [ + "rustc_abi", "rustc_ast", "rustc_ast_pretty", "rustc_attr", @@ -4213,6 +4218,7 @@ name = "rustc_pattern_analysis" version = "0.0.0" dependencies = [ "rustc-hash 2.0.0", + "rustc_abi", "rustc_apfloat", "rustc_arena", "rustc_data_structures", @@ -4352,6 +4358,7 @@ dependencies = [ "bitflags 2.6.0", "getopts", "libc", + "rustc_abi", "rustc_ast", "rustc_data_structures", "rustc_errors", @@ -4415,6 +4422,7 @@ version = "0.0.0" dependencies = [ "punycode", "rustc-demangle", + "rustc_abi", "rustc_data_structures", "rustc_errors", "rustc_hir", diff --git a/compiler/rustc_errors/Cargo.toml b/compiler/rustc_errors/Cargo.toml index 00eaf4d5a862..41ebe4ae2673 100644 --- a/compiler/rustc_errors/Cargo.toml +++ b/compiler/rustc_errors/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # tidy-alphabetical-start annotate-snippets = "0.11" derive_setters = "0.1.6" +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index 19529f06ef1d..09a608dda7ba 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -5,12 +5,12 @@ use std::num::ParseIntError; use std::path::{Path, PathBuf}; use std::process::ExitStatus; +use rustc_abi::TargetDataLayoutErrors; use rustc_ast_pretty::pprust; use rustc_macros::Subdiagnostic; use rustc_span::Span; use rustc_span::edition::Edition; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol}; -use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple}; use rustc_type_ir::{ClosureKind, FloatTy}; use {rustc_ast as ast, rustc_hir as hir}; diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index 04ca7f123d3e..3c8887f08bc8 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -10,6 +10,7 @@ doctest = false [dependencies] # tidy-alphabetical-start itertools = "0.12" +rustc_abi = { path = "../rustc_abi" } rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 97f3f1c8ef27..95c902946c3a 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1,6 +1,7 @@ use std::cell::LazyCell; use std::ops::ControlFlow; +use rustc_abi::FieldIdx; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::MultiSpan; use rustc_errors::codes::*; @@ -23,7 +24,6 @@ use rustc_middle::ty::{ TypeVisitableExt, }; use rustc_session::lint::builtin::UNINHABITED_STATIC; -use rustc_target::abi::FieldIdx; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::traits; diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index bbff00cd3b3c..e95669c9d409 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -1,5 +1,6 @@ use std::assert_matches::debug_assert_matches; +use rustc_abi::FieldIdx; use rustc_ast::InlineAsmTemplatePiece; use rustc_data_structures::fx::FxIndexSet; use rustc_hir::{self as hir, LangItem}; @@ -8,7 +9,6 @@ use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintT use rustc_session::lint; use rustc_span::Symbol; use rustc_span::def_id::LocalDefId; -use rustc_target::abi::FieldIdx; use rustc_target::asm::{ InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType, ModifierInfo, }; diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index f2f9c69e49f7..b15243d419ec 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -74,6 +74,7 @@ pub mod wfcheck; use std::num::NonZero; pub use check::{check_abi, check_abi_fn_ptr}; +use rustc_abi::VariantIdx; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::{Diag, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -90,7 +91,6 @@ use rustc_session::parse::feature_err; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{BytePos, DUMMY_SP, Span, Symbol}; -use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _; diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index 79d3482472a8..3b0151b1f944 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -8,6 +8,7 @@ edition = "2021" bitflags = "2.4.1" libloading = "0.8.0" odht = { version = "0.3.1", features = ["nightly"] } +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index a00ca27aacc0..f1844045677e 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -6,6 +6,7 @@ use decoder::{DecodeContext, Metadata}; use def_path_hash_map::DefPathHashMapRef; use encoder::EncodeContext; pub use encoder::{EncodedMetadata, encode_metadata, rendered_const}; +use rustc_abi::{FieldIdx, VariantIdx}; use rustc_ast::expand::StrippedCfgItem; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::svh::Svh; @@ -37,7 +38,6 @@ use rustc_span::edition::Edition; use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextData}; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span}; -use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use table::TableBuilder; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; diff --git a/compiler/rustc_mir_dataflow/Cargo.toml b/compiler/rustc_mir_dataflow/Cargo.toml index 7199db677c46..62a69b3464f0 100644 --- a/compiler/rustc_mir_dataflow/Cargo.toml +++ b/compiler/rustc_mir_dataflow/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # tidy-alphabetical-start polonius-engine = "0.13.0" regex = "1" +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs index bb53eaf6cbd1..e5cddd0e5e4b 100644 --- a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs +++ b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs @@ -1,5 +1,5 @@ +use rustc_abi::VariantIdx; use rustc_middle::mir::{self, Body, Location, Terminator, TerminatorKind}; -use rustc_target::abi::VariantIdx; use tracing::debug; use super::move_paths::{InitKind, LookupResult, MoveData, MovePathIndex}; diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 7f2a07e2f5e0..9a1f000d39d8 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -1,5 +1,6 @@ use std::{fmt, iter}; +use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use rustc_hir::lang_items::LangItem; use rustc_index::Idx; use rustc_middle::mir::patch::MirPatch; @@ -10,7 +11,6 @@ use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; use rustc_span::DUMMY_SP; use rustc_span::source_map::Spanned; -use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use tracing::{debug, instrument}; /// The value of an inserted drop flag. diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index d0f62bd82d17..f7d4a082779b 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -36,6 +36,7 @@ use std::assert_matches::assert_matches; use std::fmt::{Debug, Formatter}; use std::ops::Range; +use rustc_abi::{FieldIdx, VariantIdx}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry}; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -46,7 +47,6 @@ use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_target::abi::{FieldIdx, VariantIdx}; use tracing::debug; use crate::fmt::DebugWithContext; diff --git a/compiler/rustc_passes/Cargo.toml b/compiler/rustc_passes/Cargo.toml index b45a8dae277e..ed5991459ac1 100644 --- a/compiler/rustc_passes/Cargo.toml +++ b/compiler/rustc_passes/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index af17fbf7e4df..b1db66fa52d4 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -7,6 +7,7 @@ use std::mem; use hir::ItemKind; use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; +use rustc_abi::FieldIdx; use rustc_data_structures::unord::UnordSet; use rustc_errors::MultiSpan; use rustc_hir as hir; @@ -22,7 +23,6 @@ use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_session::lint::builtin::DEAD_CODE; use rustc_span::symbol::{Symbol, sym}; -use rustc_target::abi::FieldIdx; use crate::errors::{ ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment, diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 93729a7f6df8..0b6cf82ca8b4 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -1,3 +1,4 @@ +use rustc_abi::{HasDataLayout, TargetDataLayout}; use rustc_ast::Attribute; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -7,7 +8,6 @@ use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt}; use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_target::abi::{HasDataLayout, TargetDataLayout}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::TyCtxtInferExt; use rustc_trait_selection::traits; diff --git a/compiler/rustc_pattern_analysis/Cargo.toml b/compiler/rustc_pattern_analysis/Cargo.toml index 34fb1bdf6fa7..f98e4243375f 100644 --- a/compiler/rustc_pattern_analysis/Cargo.toml +++ b/compiler/rustc_pattern_analysis/Cargo.toml @@ -6,6 +6,8 @@ edition = "2021" [dependencies] # tidy-alphabetical-start rustc-hash = "2.0.0" + +rustc_abi = { path = "../rustc_abi", optional = true } rustc_apfloat = "0.2.0" rustc_arena = { path = "../rustc_arena", optional = true } rustc_data_structures = { path = "../rustc_data_structures", optional = true } @@ -29,6 +31,7 @@ tracing-tree = "0.3.0" [features] default = ["rustc"] rustc = [ + "dep:rustc_abi", "dep:rustc_arena", "dep:rustc_data_structures", "dep:rustc_errors", diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 0e132b27fb4c..9ea5023064c1 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -1,6 +1,7 @@ use std::fmt; use std::iter::once; +use rustc_abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx}; use rustc_arena::DroplessArena; use rustc_hir::HirId; use rustc_hir::def_id::DefId; @@ -15,7 +16,6 @@ use rustc_middle::ty::{ use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; -use rustc_target::abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx}; use crate::constructor::Constructor::*; use crate::constructor::{ diff --git a/compiler/rustc_pattern_analysis/src/rustc/print.rs b/compiler/rustc_pattern_analysis/src/rustc/print.rs index 17e389df17ed..7649f72f8681 100644 --- a/compiler/rustc_pattern_analysis/src/rustc/print.rs +++ b/compiler/rustc_pattern_analysis/src/rustc/print.rs @@ -11,10 +11,10 @@ use std::fmt; +use rustc_abi::{FieldIdx, VariantIdx}; use rustc_middle::bug; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt}; use rustc_span::sym; -use rustc_target::abi::{FieldIdx, VariantIdx}; #[derive(Clone, Debug)] pub(crate) struct FieldPat { diff --git a/compiler/rustc_session/Cargo.toml b/compiler/rustc_session/Cargo.toml index 75cc8f18a545..e9983699609d 100644 --- a/compiler/rustc_session/Cargo.toml +++ b/compiler/rustc_session/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # tidy-alphabetical-start bitflags = "2.4.1" getopts = "0.2" +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_session/src/code_stats.rs b/compiler/rustc_session/src/code_stats.rs index 7a32c0c26555..f3c21992784c 100644 --- a/compiler/rustc_session/src/code_stats.rs +++ b/compiler/rustc_session/src/code_stats.rs @@ -1,10 +1,10 @@ use std::cmp; +use rustc_abi::{Align, Size}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lock; use rustc_span::Symbol; use rustc_span::def_id::DefId; -use rustc_target::abi::{Align, Size}; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct VariantInfo { diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index ccc01728958b..31ef2bda4f1e 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -23,12 +23,12 @@ use std::hash::Hash; use std::iter; +use rustc_abi::Align; use rustc_ast::ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_lint_defs::BuiltinLintDiag; use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS; use rustc_span::symbol::{Symbol, sym}; -use rustc_target::abi::Align; use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTriple}; use crate::Session; diff --git a/compiler/rustc_symbol_mangling/Cargo.toml b/compiler/rustc_symbol_mangling/Cargo.toml index 65aa9e40c8ba..644e710d1db8 100644 --- a/compiler/rustc_symbol_mangling/Cargo.toml +++ b/compiler/rustc_symbol_mangling/Cargo.toml @@ -7,6 +7,8 @@ edition = "2021" # tidy-alphabetical-start punycode = "0.4.0" rustc-demangle = "0.1.21" + +rustc_abi = { path = "../rustc_abi" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_hir = { path = "../rustc_hir" } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index d092fa8f0820..868345c75945 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -2,6 +2,7 @@ use std::fmt::Write; use std::iter; use std::ops::Range; +use rustc_abi::Integer; use rustc_data_structures::base_n::ToBaseN; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; @@ -17,7 +18,6 @@ use rustc_middle::ty::{ TyCtxt, TypeVisitable, TypeVisitableExt, UintTy, }; use rustc_span::symbol::kw; -use rustc_target::abi::Integer; use rustc_target::spec::abi::Abi; pub(super) fn mangle<'tcx>( From 6fc7ce43d2f2cd2fef1b75c9c59f13f312e0d9d8 Mon Sep 17 00:00:00 2001 From: asquared31415 <34665709+asquared31415@users.noreply.github.com> Date: Sat, 12 Oct 2024 05:37:56 +0000 Subject: [PATCH 320/366] Error on alignments greater than `isize::MAX` Co-authored-by: Jieyou Xu --- compiler/rustc_passes/messages.ftl | 4 ++ compiler/rustc_passes/src/check_attr.rs | 44 ++++++++++++++++++- compiler/rustc_passes/src/errors.rs | 9 ++++ .../repr_align_greater_usize.msp430.stderr | 19 ++++++++ tests/ui/repr/repr_align_greater_usize.rs | 25 +++++++++++ 5 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 tests/ui/repr/repr_align_greater_usize.msp430.stderr create mode 100644 tests/ui/repr/repr_align_greater_usize.rs diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index f8ef423a9b00..e5e70ba20338 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -622,6 +622,10 @@ passes_remove_fields = passes_repr_align_function = `repr(align)` attributes on functions are unstable +passes_repr_align_greater_than_target_max = + alignment must not be greater than `isize::MAX` bytes + .note = `isize::MAX` is {$size} for the current target + passes_repr_conflicting = conflicting representation hints diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index acde27c6728c..8c4592cbb369 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -34,6 +34,7 @@ use rustc_session::lint::builtin::{ use rustc_session::parse::feature_err; use rustc_span::symbol::{Symbol, kw, sym}; use rustc_span::{BytePos, DUMMY_SP, Span}; +use rustc_target::abi::Size; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs}; @@ -1785,7 +1786,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | Target::Union | Target::Enum | Target::Fn - | Target::Method(_) => continue, + | Target::Method(_) => {} _ => { self.dcx().emit_err( errors::AttrApplication::StructEnumFunctionMethodUnion { @@ -1795,6 +1796,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { ); } } + + self.check_align_value(hint); } sym::packed => { if target != Target::Struct && target != Target::Union { @@ -1892,6 +1895,45 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } + fn check_align_value(&self, item: &MetaItemInner) { + match item.singleton_lit_list() { + Some(( + _, + MetaItemLit { + kind: ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed), .. + }, + )) => { + let val = literal.get() as u64; + if val > 2_u64.pow(29) { + // for values greater than 2^29, a different error will be emitted, make sure that happens + self.dcx().span_delayed_bug( + item.span(), + "alignment greater than 2^29 should be errored on elsewhere", + ); + } else { + // only do this check when <= 2^29 to prevent duplicate errors: + // alignment greater than 2^29 not supported + // alignment is too large for the current target + + let max = + Size::from_bits(self.tcx.sess.target.pointer_width).signed_int_max() as u64; + if val > max { + self.dcx().emit_err(errors::InvalidReprAlignForTarget { + span: item.span(), + size: max, + }); + } + } + } + + // if the attribute is malformed, singleton_lit_list may not be of the expected type or may be None + // but an error will have already been emitted, so this code should just skip such attributes + Some((_, _)) | None => { + self.dcx().span_delayed_bug(item.span(), "malformed repr(align(N))"); + } + } + } + fn check_used(&self, attrs: &[Attribute], target: Target, target_span: Span) { let mut used_linker_span = None; let mut used_compiler_span = None; diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index b5f1eac1cba2..8bd767c1243d 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -567,6 +567,15 @@ pub(crate) struct ReprConflicting { pub hint_spans: Vec, } +#[derive(Diagnostic)] +#[diag(passes_repr_align_greater_than_target_max, code = E0589)] +#[note] +pub(crate) struct InvalidReprAlignForTarget { + #[primary_span] + pub span: Span, + pub size: u64, +} + #[derive(LintDiagnostic)] #[diag(passes_repr_conflicting, code = E0566)] pub(crate) struct ReprConflictingLint; diff --git a/tests/ui/repr/repr_align_greater_usize.msp430.stderr b/tests/ui/repr/repr_align_greater_usize.msp430.stderr new file mode 100644 index 000000000000..7c85249c0099 --- /dev/null +++ b/tests/ui/repr/repr_align_greater_usize.msp430.stderr @@ -0,0 +1,19 @@ +error[E0589]: alignment must not be greater than `isize::MAX` bytes + --> $DIR/repr_align_greater_usize.rs:21:8 + | +LL | #[repr(align(32768))] + | ^^^^^^^^^^^^ + | + = note: `isize::MAX` is 32767 for the current target + +error[E0589]: alignment must not be greater than `isize::MAX` bytes + --> $DIR/repr_align_greater_usize.rs:24:8 + | +LL | #[repr(align(65536))] + | ^^^^^^^^^^^^ + | + = note: `isize::MAX` is 32767 for the current target + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0589`. diff --git a/tests/ui/repr/repr_align_greater_usize.rs b/tests/ui/repr/repr_align_greater_usize.rs new file mode 100644 index 000000000000..b47320b6d9b6 --- /dev/null +++ b/tests/ui/repr/repr_align_greater_usize.rs @@ -0,0 +1,25 @@ +//@ revisions: msp430 aarch32 +//@[msp430] needs-llvm-components: msp430 +//@[msp430] compile-flags: --target=msp430-none-elf +//@[aarch32] build-pass +//@[aarch32] needs-llvm-components: arm +//@[aarch32] compile-flags: --target=thumbv7m-none-eabi + +// We should fail to compute alignment for types aligned higher than usize::MAX. +// We can't handle alignments that require all 32 bits, so this only affects 16-bit. + +#![feature(lang_items, no_core)] +#![no_core] +#![crate_type = "lib"] + +#[lang = "sized"] +trait Sized {} + +#[repr(align(16384))] +struct Kitten; + +#[repr(align(32768))] //[msp430]~ ERROR alignment must not be greater than `isize::MAX` +struct Cat; + +#[repr(align(65536))] //[msp430]~ ERROR alignment must not be greater than `isize::MAX` +struct BigCat; From e1781297f3d471b40843ba398085eae0a38974b5 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 27 Oct 2024 22:31:09 -0700 Subject: [PATCH 321/366] compiler: Rename LayoutS to LayoutData The last {UninternedType}S is in captivity. The galaxy is at peace. --- compiler/rustc_abi/src/layout.rs | 42 +++++++++---------- compiler/rustc_abi/src/layout/ty.rs | 10 ++--- compiler/rustc_abi/src/lib.rs | 14 +++---- compiler/rustc_middle/src/arena.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 6 +-- compiler/rustc_middle/src/ty/layout.rs | 6 +-- .../rustc_smir/src/rustc_smir/convert/abi.rs | 2 +- compiler/rustc_ty_utils/src/layout.rs | 32 +++++++------- 8 files changed, 57 insertions(+), 57 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 0340d1bd6bcd..141a15b99a3d 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -7,7 +7,7 @@ use tracing::debug; use crate::{ Abi, AbiAndPrefAlign, Align, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer, - LayoutS, Niche, NonZeroUsize, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding, + LayoutData, Niche, NonZeroUsize, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding, Variants, WrappingRange, }; @@ -26,7 +26,7 @@ fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice) -> bool where FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug, + F: Deref> + fmt::Debug, { let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited()); // We cannot ignore alignment; that might lead us to entirely discard a variant and @@ -89,7 +89,7 @@ impl LayoutCalculatorError { } type LayoutCalculatorResult = - Result, LayoutCalculatorError>; + Result, LayoutCalculatorError>; #[derive(Clone, Copy, Debug)] pub struct LayoutCalculator { @@ -105,7 +105,7 @@ impl LayoutCalculator { &self, a: Scalar, b: Scalar, - ) -> LayoutS { + ) -> LayoutData { let dl = self.cx.data_layout(); let b_align = b.align(dl); let align = a.align(dl).max(b_align).max(dl.aggregate_align); @@ -119,7 +119,7 @@ impl LayoutCalculator { .chain(Niche::from_scalar(dl, Size::ZERO, a)) .max_by_key(|niche| niche.available(dl)); - LayoutS { + LayoutData { variants: Variants::Single { index: VariantIdx::new(0) }, fields: FieldsShape::Arbitrary { offsets: [Size::ZERO, b_offset].into(), @@ -138,7 +138,7 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug + Copy, + F: Deref> + fmt::Debug + Copy, >( &self, fields: &IndexSlice, @@ -211,9 +211,9 @@ impl LayoutCalculator { pub fn layout_of_never_type( &self, - ) -> LayoutS { + ) -> LayoutData { let dl = self.cx.data_layout(); - LayoutS { + LayoutData { variants: Variants::Single { index: VariantIdx::new(0) }, fields: FieldsShape::Primitive, abi: Abi::Uninhabited, @@ -229,7 +229,7 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug + Copy, + F: Deref> + fmt::Debug + Copy, >( &self, repr: &ReprOptions, @@ -292,7 +292,7 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug + Copy, + F: Deref> + fmt::Debug + Copy, >( &self, repr: &ReprOptions, @@ -384,7 +384,7 @@ impl LayoutCalculator { return Err(LayoutCalculatorError::EmptyUnion); }; - Ok(LayoutS { + Ok(LayoutData { variants: Variants::Single { index: only_variant_idx }, fields: FieldsShape::Union(union_field_count), abi, @@ -401,7 +401,7 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug + Copy, + F: Deref> + fmt::Debug + Copy, >( &self, repr: &ReprOptions, @@ -501,7 +501,7 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug + Copy, + F: Deref> + fmt::Debug + Copy, >( &self, repr: &ReprOptions, @@ -516,8 +516,8 @@ impl LayoutCalculator { // overall LayoutS. Store the overall LayoutS // and the variant LayoutSs here until then. struct TmpLayout { - layout: LayoutS, - variants: IndexVec>, + layout: LayoutData, + variants: IndexVec>, } let dl = self.cx.data_layout(); @@ -649,7 +649,7 @@ impl LayoutCalculator { Abi::Aggregate { sized: true } }; - let layout = LayoutS { + let layout = LayoutData { variants: Variants::Multiple { tag: niche_scalar, tag_encoding: TagEncoding::Niche { @@ -958,7 +958,7 @@ impl LayoutCalculator { let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag); - let tagged_layout = LayoutS { + let tagged_layout = LayoutData { variants: Variants::Multiple { tag, tag_encoding: TagEncoding::Direct, @@ -1013,7 +1013,7 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug + Copy, + F: Deref> + fmt::Debug + Copy, >( &self, fields: &IndexSlice, @@ -1341,7 +1341,7 @@ impl LayoutCalculator { unadjusted_abi_align }; - Ok(LayoutS { + Ok(LayoutData { variants: Variants::Single { index: VariantIdx::new(0) }, fields: FieldsShape::Arbitrary { offsets, memory_index }, abi, @@ -1357,10 +1357,10 @@ impl LayoutCalculator { 'a, FieldIdx: Idx, VariantIdx: Idx, - F: Deref> + fmt::Debug, + F: Deref> + fmt::Debug, >( &self, - layout: &LayoutS, + layout: &LayoutData, fields: &IndexSlice, ) -> String { let dl = self.cx.data_layout(); diff --git a/compiler/rustc_abi/src/layout/ty.rs b/compiler/rustc_abi/src/layout/ty.rs index c6812c4d4c07..e029e1426b21 100644 --- a/compiler/rustc_abi/src/layout/ty.rs +++ b/compiler/rustc_abi/src/layout/ty.rs @@ -58,7 +58,7 @@ rustc_index::newtype_index! { } #[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)] #[rustc_pass_by_value] -pub struct Layout<'a>(pub Interned<'a, LayoutS>); +pub struct Layout<'a>(pub Interned<'a, LayoutData>); impl<'a> fmt::Debug for Layout<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -68,8 +68,8 @@ impl<'a> fmt::Debug for Layout<'a> { } impl<'a> Deref for Layout<'a> { - type Target = &'a LayoutS; - fn deref(&self) -> &&'a LayoutS { + type Target = &'a LayoutData; + fn deref(&self) -> &&'a LayoutData { &self.0.0 } } @@ -142,8 +142,8 @@ impl<'a, Ty: fmt::Display> fmt::Debug for TyAndLayout<'a, Ty> { } impl<'a, Ty> Deref for TyAndLayout<'a, Ty> { - type Target = &'a LayoutS; - fn deref(&self) -> &&'a LayoutS { + type Target = &'a LayoutData; + fn deref(&self) -> &&'a LayoutData { &self.layout.0.0 } } diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 8e90130da4c0..b54efa4bb48b 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1485,7 +1485,7 @@ pub enum Variants { tag: Scalar, tag_encoding: TagEncoding, tag_field: usize, - variants: IndexVec>, + variants: IndexVec>, }, } @@ -1603,7 +1603,7 @@ impl Niche { // NOTE: This struct is generic over the FieldIdx and VariantIdx for rust-analyzer usage. #[derive(PartialEq, Eq, Hash, Clone)] #[cfg_attr(feature = "nightly", derive(HashStable_Generic))] -pub struct LayoutS { +pub struct LayoutData { /// Says where the fields are located within the layout. pub fields: FieldsShape, @@ -1643,7 +1643,7 @@ pub struct LayoutS { pub unadjusted_abi_align: Align, } -impl LayoutS { +impl LayoutData { /// Returns `true` if this is an aggregate type (including a ScalarPair!) pub fn is_aggregate(&self) -> bool { match self.abi { @@ -1656,7 +1656,7 @@ impl LayoutS { let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar); let size = scalar.size(cx); let align = scalar.align(cx); - LayoutS { + LayoutData { variants: Variants::Single { index: VariantIdx::new(0) }, fields: FieldsShape::Primitive, abi: Abi::Scalar(scalar), @@ -1669,7 +1669,7 @@ impl LayoutS { } } -impl fmt::Debug for LayoutS +impl fmt::Debug for LayoutData where FieldsShape: fmt::Debug, Variants: fmt::Debug, @@ -1678,7 +1678,7 @@ where // This is how `Layout` used to print before it become // `Interned`. We print it like this to avoid having to update // expected output in a lot of tests. - let LayoutS { + let LayoutData { size, align, abi, @@ -1723,7 +1723,7 @@ pub struct PointeeInfo { pub safe: Option, } -impl LayoutS { +impl LayoutData { /// Returns `true` if the layout corresponds to an unsized type. #[inline] pub fn is_unsized(&self) -> bool { diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 52fe9956b477..7e77923fcdf6 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -8,7 +8,7 @@ macro_rules! arena_types { ($macro:path) => ( $macro!([ - [] layout: rustc_target::abi::LayoutS, + [] layout: rustc_abi::LayoutData, [] fn_abi: rustc_target::abi::call::FnAbi<'tcx, rustc_middle::ty::Ty<'tcx>>, // AdtDef are interned and compared by address [decode] adt_def: rustc_middle::ty::AdtDefData, diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index a6a0a6dc222c..5ae9c589ec4a 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -12,7 +12,7 @@ use std::marker::PhantomData; use std::ops::{Bound, Deref}; use std::{fmt, iter, mem}; -use rustc_abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx}; +use rustc_abi::{FieldIdx, Layout, LayoutData, TargetDataLayout, VariantIdx}; use rustc_ast::{self as ast, attr}; use rustc_data_structures::defer; use rustc_data_structures::fingerprint::Fingerprint; @@ -766,7 +766,7 @@ pub struct CtxtInterners<'tcx> { pat: InternedSet<'tcx, PatternKind<'tcx>>, const_allocation: InternedSet<'tcx, Allocation>, bound_variable_kinds: InternedSet<'tcx, List>, - layout: InternedSet<'tcx, LayoutS>, + layout: InternedSet<'tcx, LayoutData>, adt_def: InternedSet<'tcx, AdtDefData>, external_constraints: InternedSet<'tcx, ExternalConstraintsData>>, predefined_opaques_in_body: InternedSet<'tcx, PredefinedOpaquesData>>, @@ -2469,7 +2469,7 @@ direct_interners! { region: pub(crate) intern_region(RegionKind<'tcx>): Region -> Region<'tcx>, pat: pub mk_pat(PatternKind<'tcx>): Pattern -> Pattern<'tcx>, const_allocation: pub mk_const_alloc(Allocation): ConstAllocation -> ConstAllocation<'tcx>, - layout: pub mk_layout(LayoutS): Layout -> Layout<'tcx>, + layout: pub mk_layout(LayoutData): Layout -> Layout<'tcx>, adt_def: pub mk_adt_def_from_data(AdtDefData): AdtDef -> AdtDef<'tcx>, external_constraints: pub mk_external_constraints(ExternalConstraintsData>): ExternalConstraints -> ExternalConstraints<'tcx>, diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 7e65df6b27ce..990fc37a1f33 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -4,7 +4,7 @@ use std::{cmp, fmt}; use rustc_abi::Primitive::{self, Float, Int, Pointer}; use rustc_abi::{ - Abi, AddressSpace, Align, FieldsShape, HasDataLayout, Integer, LayoutCalculator, LayoutS, + Abi, AddressSpace, Align, FieldsShape, HasDataLayout, Integer, LayoutCalculator, LayoutData, PointeeInfo, PointerKind, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout, Variants, }; use rustc_error_messages::DiagMessage; @@ -751,7 +751,7 @@ where ty::Adt(def, _) => def.variant(variant_index).fields.len(), _ => bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty), }; - tcx.mk_layout(LayoutS { + tcx.mk_layout(LayoutData { variants: Variants::Single { index: variant_index }, fields: match NonZero::new(fields) { Some(fields) => FieldsShape::Union(fields), @@ -788,7 +788,7 @@ where let tcx = cx.tcx(); let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> { TyAndLayout { - layout: tcx.mk_layout(LayoutS::scalar(cx, tag)), + layout: tcx.mk_layout(LayoutData::scalar(cx, tag)), ty: tag.primitive().to_ty(tcx), } }; diff --git a/compiler/rustc_smir/src/rustc_smir/convert/abi.rs b/compiler/rustc_smir/src/rustc_smir/convert/abi.rs index 06f01aebf9b6..dbfcde56f6ec 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/abi.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/abi.rs @@ -50,7 +50,7 @@ impl<'tcx> Stable<'tcx> for rustc_target::abi::Layout<'tcx> { } impl<'tcx> Stable<'tcx> - for rustc_abi::LayoutS + for rustc_abi::LayoutData { type T = LayoutShape; diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index e755e90aa65d..94b80e2694d8 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -6,7 +6,7 @@ use rustc_abi::Integer::{I8, I32}; use rustc_abi::Primitive::{self, Float, Int, Pointer}; use rustc_abi::{ Abi, AbiAndPrefAlign, AddressSpace, Align, FieldsShape, HasDataLayout, LayoutCalculatorError, - LayoutS, Niche, ReprOptions, Scalar, Size, StructKind, TagEncoding, Variants, WrappingRange, + LayoutData, Niche, ReprOptions, Scalar, Size, StructKind, TagEncoding, Variants, WrappingRange, }; use rustc_index::bit_set::BitSet; use rustc_index::{IndexSlice, IndexVec}; @@ -131,7 +131,7 @@ fn univariant_uninterned<'tcx>( fields: &IndexSlice>, repr: &ReprOptions, kind: StructKind, -) -> Result, &'tcx LayoutError<'tcx>> { +) -> Result, &'tcx LayoutError<'tcx>> { let pack = repr.pack; if pack.is_some() && repr.align.is_some() { cx.tcx().dcx().bug("struct cannot be packed and aligned"); @@ -159,7 +159,7 @@ fn layout_of_uncached<'tcx>( assert!(size.bits() <= 128); Scalar::Initialized { value, valid_range: WrappingRange::full(size) } }; - let scalar = |value: Primitive| tcx.mk_layout(LayoutS::scalar(cx, scalar_unit(value))); + let scalar = |value: Primitive| tcx.mk_layout(LayoutData::scalar(cx, scalar_unit(value))); let univariant = |fields: &IndexSlice>, repr: &ReprOptions, kind| { @@ -170,7 +170,7 @@ fn layout_of_uncached<'tcx>( Ok(match *ty.kind() { ty::Pat(ty, pat) => { let layout = cx.layout_of(ty)?.layout; - let mut layout = LayoutS::clone(&layout.0); + let mut layout = LayoutData::clone(&layout.0); match *pat { ty::PatternKind::Range { start, end, include_end } => { if let Abi::Scalar(scalar) | Abi::ScalarPair(scalar, _) = &mut layout.abi { @@ -206,11 +206,11 @@ fn layout_of_uncached<'tcx>( } // Basic scalars. - ty::Bool => tcx.mk_layout(LayoutS::scalar(cx, Scalar::Initialized { + ty::Bool => tcx.mk_layout(LayoutData::scalar(cx, Scalar::Initialized { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 }, })), - ty::Char => tcx.mk_layout(LayoutS::scalar(cx, Scalar::Initialized { + ty::Char => tcx.mk_layout(LayoutData::scalar(cx, Scalar::Initialized { value: Int(I32, false), valid_range: WrappingRange { start: 0, end: 0x10FFFF }, })), @@ -220,7 +220,7 @@ fn layout_of_uncached<'tcx>( ty::FnPtr(..) => { let mut ptr = scalar_unit(Pointer(dl.instruction_address_space)); ptr.valid_range_mut().start = 1; - tcx.mk_layout(LayoutS::scalar(cx, ptr)) + tcx.mk_layout(LayoutData::scalar(cx, ptr)) } // The never type. @@ -235,7 +235,7 @@ fn layout_of_uncached<'tcx>( let pointee = tcx.normalize_erasing_regions(param_env, pointee); if pointee.is_sized(tcx, param_env) { - return Ok(tcx.mk_layout(LayoutS::scalar(cx, data_ptr))); + return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr))); } let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type() @@ -272,7 +272,7 @@ fn layout_of_uncached<'tcx>( let metadata_layout = cx.layout_of(metadata_ty)?; // If the metadata is a 1-zst, then the pointer is thin. if metadata_layout.is_1zst() { - return Ok(tcx.mk_layout(LayoutS::scalar(cx, data_ptr))); + return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr))); } let Abi::Scalar(metadata) = metadata_layout.abi else { @@ -285,7 +285,7 @@ fn layout_of_uncached<'tcx>( match unsized_part.kind() { ty::Foreign(..) => { - return Ok(tcx.mk_layout(LayoutS::scalar(cx, data_ptr))); + return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr))); } ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)), ty::Dynamic(..) => { @@ -337,7 +337,7 @@ fn layout_of_uncached<'tcx>( let largest_niche = if count != 0 { element.largest_niche } else { None }; - tcx.mk_layout(LayoutS { + tcx.mk_layout(LayoutData { variants: Variants::Single { index: FIRST_VARIANT }, fields: FieldsShape::Array { stride: element.size, count }, abi, @@ -350,7 +350,7 @@ fn layout_of_uncached<'tcx>( } ty::Slice(element) => { let element = cx.layout_of(element)?; - tcx.mk_layout(LayoutS { + tcx.mk_layout(LayoutData { variants: Variants::Single { index: FIRST_VARIANT }, fields: FieldsShape::Array { stride: element.size, count: 0 }, abi: Abi::Aggregate { sized: false }, @@ -361,7 +361,7 @@ fn layout_of_uncached<'tcx>( unadjusted_abi_align: element.align.abi, }) } - ty::Str => tcx.mk_layout(LayoutS { + ty::Str => tcx.mk_layout(LayoutData { variants: Variants::Single { index: FIRST_VARIANT }, fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 }, abi: Abi::Aggregate { sized: false }, @@ -532,7 +532,7 @@ fn layout_of_uncached<'tcx>( FieldsShape::Array { stride: e_ly.size, count: e_len } }; - tcx.mk_layout(LayoutS { + tcx.mk_layout(LayoutData { variants: Variants::Single { index: FIRST_VARIANT }, fields, abi, @@ -835,7 +835,7 @@ fn coroutine_layout<'tcx>( }; let tag_layout = TyAndLayout { ty: discr_int.to_ty(tcx, /* signed = */ false), - layout: tcx.mk_layout(LayoutS::scalar(cx, tag)), + layout: tcx.mk_layout(LayoutData::scalar(cx, tag)), }; let promoted_layouts = ineligible_locals.iter().map(|local| { @@ -991,7 +991,7 @@ fn coroutine_layout<'tcx>( Abi::Aggregate { sized: true } }; - let layout = tcx.mk_layout(LayoutS { + let layout = tcx.mk_layout(LayoutData { variants: Variants::Multiple { tag, tag_encoding: TagEncoding::Direct, From 9015c6decae38c5192290e15b8deda1c76c8260a Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 27 Oct 2024 22:32:40 -0700 Subject: [PATCH 322/366] cg_clif: Rename LayoutS to LayoutData --- compiler/rustc_codegen_cranelift/src/abi/comments.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_cranelift/src/abi/comments.rs b/compiler/rustc_codegen_cranelift/src/abi/comments.rs index a318cae1722b..daea789ee3eb 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/comments.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/comments.rs @@ -79,7 +79,7 @@ pub(super) fn add_local_place_comments<'tcx>( return; } let TyAndLayout { ty, layout } = place.layout(); - let rustc_target::abi::LayoutS { size, align, .. } = layout.0.0; + let rustc_abi::LayoutData { size, align, .. } = layout.0.0; let (kind, extra) = place.debug_comment(); From 2a9239a1056a48f98a247ead469173dd806e0050 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 27 Oct 2024 22:32:58 -0700 Subject: [PATCH 323/366] rust-analyzer: Rename LayoutS to LayoutData --- src/tools/rust-analyzer/crates/hir-ty/src/layout.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs b/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs index 80831440720c..9f4cc98993e2 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/layout.rs @@ -6,7 +6,7 @@ use base_db::ra_salsa::Cycle; use chalk_ir::{AdtId, FloatTy, IntTy, TyKind, UintTy}; use hir_def::{ layout::{ - Abi, FieldsShape, Float, Integer, LayoutCalculator, LayoutCalculatorError, LayoutS, + Abi, FieldsShape, Float, Integer, LayoutCalculator, LayoutCalculatorError, LayoutData, Primitive, ReprOptions, Scalar, Size, StructKind, TargetDataLayout, WrappingRange, }, LocalFieldId, StructId, @@ -66,7 +66,7 @@ impl rustc_index::Idx for RustcFieldIdx { } } -pub type Layout = LayoutS; +pub type Layout = LayoutData; pub type TagEncoding = hir_def::layout::TagEncoding; pub type Variants = hir_def::layout::Variants; From dfafbc41d8d5befc21f1ee1c009e94053be158e5 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 28 Oct 2024 16:48:46 +1100 Subject: [PATCH 324/366] Known-bug test for `keyword_idents` lint not propagating to other files --- .../keyword-idents/auxiliary/multi_file_submod.rs | 10 ++++++++++ tests/ui/lint/keyword-idents/multi-file.rs | 14 ++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/ui/lint/keyword-idents/auxiliary/multi_file_submod.rs create mode 100644 tests/ui/lint/keyword-idents/multi-file.rs diff --git a/tests/ui/lint/keyword-idents/auxiliary/multi_file_submod.rs b/tests/ui/lint/keyword-idents/auxiliary/multi_file_submod.rs new file mode 100644 index 000000000000..08d6733d3e28 --- /dev/null +++ b/tests/ui/lint/keyword-idents/auxiliary/multi_file_submod.rs @@ -0,0 +1,10 @@ +// Submodule file used by test `../multi-file.rs`. + +// Keywords reserved from Rust 2018: +fn async() {} +fn await() {} +fn try() {} +fn dyn() {} + +// Keywords reserved from Rust 2024: +fn gen() {} diff --git a/tests/ui/lint/keyword-idents/multi-file.rs b/tests/ui/lint/keyword-idents/multi-file.rs new file mode 100644 index 000000000000..703e13f9ef6b --- /dev/null +++ b/tests/ui/lint/keyword-idents/multi-file.rs @@ -0,0 +1,14 @@ +#![deny(keyword_idents)] // Should affect the submodule, but doesn't. +//@ edition: 2015 +//@ known-bug: #132218 +//@ check-pass (known bug; should be check-fail) + +// Because `keyword_idents_2018` and `keyword_idents_2024` are pre-expansion +// lints, configuring them via lint attributes doesn't propagate to submodules +// in other files. +// + +#[path = "./auxiliary/multi_file_submod.rs"] +mod multi_file_submod; + +fn main() {} From cb08e087221ba0263a338e959264520a8ed8080e Mon Sep 17 00:00:00 2001 From: Adwin White Date: Thu, 12 Sep 2024 11:32:39 +0800 Subject: [PATCH 325/366] Lower AST node id only once --- compiler/rustc_ast_lowering/src/block.rs | 14 ++- compiler/rustc_ast_lowering/src/delegation.rs | 5 +- compiler/rustc_ast_lowering/src/expr.rs | 113 +++++++++++------- compiler/rustc_ast_lowering/src/item.rs | 14 ++- compiler/rustc_ast_lowering/src/lib.rs | 67 +++++------ compiler/rustc_ast_lowering/src/pat.rs | 58 ++++++--- tests/ui/thir-print/thir-tree-match.stdout | 46 +++---- 7 files changed, 185 insertions(+), 132 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/block.rs b/compiler/rustc_ast_lowering/src/block.rs index 9d2b5690c23d..8e02cbfd2ca8 100644 --- a/compiler/rustc_ast_lowering/src/block.rs +++ b/compiler/rustc_ast_lowering/src/block.rs @@ -10,17 +10,27 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { b: &Block, targeted_by_break: bool, ) -> &'hir hir::Block<'hir> { - self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break)) + let hir_id = self.lower_node_id(b.id); + self.arena.alloc(self.lower_block_noalloc(hir_id, b, targeted_by_break)) + } + + pub(super) fn lower_block_with_hir_id( + &mut self, + b: &Block, + hir_id: hir::HirId, + targeted_by_break: bool, + ) -> &'hir hir::Block<'hir> { + self.arena.alloc(self.lower_block_noalloc(hir_id, b, targeted_by_break)) } pub(super) fn lower_block_noalloc( &mut self, + hir_id: hir::HirId, b: &Block, targeted_by_break: bool, ) -> hir::Block<'hir> { let (stmts, expr) = self.lower_stmts(&b.stmts); let rules = self.lower_block_check_mode(&b.rules); - let hir_id = self.lower_node_id(b.id); hir::Block { hir_id, stmts, expr, rules, span: self.lower_span(b.span), targeted_by_break } } diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 3b85f1737bdd..37eea707929e 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -259,10 +259,11 @@ impl<'hir> LoweringContext<'_, 'hir> { self_param_id: pat_node_id, }; self_resolver.visit_block(block); + // Target expr needs to lower `self` path. + this.ident_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id); this.lower_target_expr(&block) } else { - let pat_hir_id = this.lower_node_id(pat_node_id); - this.generate_arg(pat_hir_id, span) + this.generate_arg(param.pat.hir_id, span) }; args.push(arg); } diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index a1a16d0ca263..3df945a18e80 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -70,8 +70,8 @@ impl<'hir> LoweringContext<'_, 'hir> { _ => (), } - let hir_id = self.lower_node_id(e.id); - self.lower_attrs(hir_id, &e.attrs); + let expr_hir_id = self.lower_node_id(e.id); + self.lower_attrs(expr_hir_id, &e.attrs); let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), @@ -175,18 +175,25 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::If(cond, then, else_opt) => { self.lower_expr_if(cond, then, else_opt.as_deref()) } - ExprKind::While(cond, body, opt_label) => self.with_loop_scope(e.id, |this| { - let span = this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None); - this.lower_expr_while_in_loop_scope(span, cond, body, *opt_label) - }), - ExprKind::Loop(body, opt_label, span) => self.with_loop_scope(e.id, |this| { - hir::ExprKind::Loop( - this.lower_block(body, false), - this.lower_label(*opt_label), - hir::LoopSource::Loop, - this.lower_span(*span), - ) - }), + ExprKind::While(cond, body, opt_label) => { + self.with_loop_scope(expr_hir_id, |this| { + let span = + this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None); + let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id); + this.lower_expr_while_in_loop_scope(span, cond, body, opt_label) + }) + } + ExprKind::Loop(body, opt_label, span) => { + self.with_loop_scope(expr_hir_id, |this| { + let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id); + hir::ExprKind::Loop( + this.lower_block(body, false), + opt_label, + hir::LoopSource::Loop, + this.lower_span(*span), + ) + }) + } ExprKind::TryBlock(body) => self.lower_expr_try_block(body), ExprKind::Match(expr, arms, kind) => hir::ExprKind::Match( self.lower_expr(expr), @@ -212,7 +219,7 @@ impl<'hir> LoweringContext<'_, 'hir> { binder, *capture_clause, e.id, - hir_id, + expr_hir_id, *coroutine_kind, fn_decl, body, @@ -223,7 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> { binder, *capture_clause, e.id, - hir_id, + expr_hir_id, *constness, *movability, fn_decl, @@ -250,8 +257,14 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } ExprKind::Block(blk, opt_label) => { - let opt_label = self.lower_label(*opt_label); - hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label) + // Different from loops, label of block resolves to block id rather than + // expr node id. + let block_hir_id = self.lower_node_id(blk.id); + let opt_label = self.lower_label(*opt_label, blk.id, block_hir_id); + hir::ExprKind::Block( + self.lower_block_with_hir_id(blk, block_hir_id, opt_label.is_some()), + opt_label, + ) } ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span), ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp( @@ -354,7 +367,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), }; - hir::Expr { hir_id, kind, span: self.lower_span(e.span) } + hir::Expr { hir_id: expr_hir_id, kind, span: self.lower_span(e.span) } }) } @@ -504,7 +517,6 @@ impl<'hir> LoweringContext<'_, 'hir> { let if_expr = self.expr(span, if_kind); let block = self.block_expr(self.arena.alloc(if_expr)); let span = self.lower_span(span.with_hi(cond.span.hi())); - let opt_label = self.lower_label(opt_label); hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span) } @@ -512,8 +524,9 @@ impl<'hir> LoweringContext<'_, 'hir> { /// `try { ; }` into `{ ; ::std::ops::Try::from_output(()) }` /// and save the block id to use it as a break target for desugaring of the `?` operator. fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> { - self.with_catch_scope(body.id, |this| { - let mut block = this.lower_block_noalloc(body, true); + let body_hir_id = self.lower_node_id(body.id); + self.with_catch_scope(body_hir_id, |this| { + let mut block = this.lower_block_noalloc(body_hir_id, body, true); // Final expression of the block (if present) or `()` with span at the end of block let (try_span, tail_expr) = if let Some(expr) = block.expr.take() { @@ -869,7 +882,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid); let ready_field = self.single_pat_field(gen_future_span, x_pat); let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field); - let break_x = self.with_loop_scope(loop_node_id, move |this| { + let break_x = self.with_loop_scope(loop_hir_id, move |this| { let expr_break = hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr)); this.arena.alloc(this.expr(gen_future_span, expr_break)) @@ -1101,8 +1114,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::CoroutineSource::Closure, ); - let hir_id = this.lower_node_id(coroutine_kind.closure_id()); - this.maybe_forward_track_caller(body.span, closure_hir_id, hir_id); + this.maybe_forward_track_caller(body.span, closure_hir_id, expr.hir_id); (parameters, expr) }); @@ -1465,8 +1477,16 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } - fn lower_label(&self, opt_label: Option`, the trait `Sized` is not implemented for `A`, which is required by `Bar: Sized` + = help: within `Bar`, the trait `Sized` is not implemented for `A` note: required because it appears within the type `Bar` --> $DIR/extern-types-unsized.rs:14:8 | @@ -65,7 +65,7 @@ error[E0277]: the size for values of type `A` cannot be known at compilation tim LL | assert_sized::>>(); | ^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `Bar>`, the trait `Sized` is not implemented for `A`, which is required by `Bar>: Sized` + = help: within `Bar>`, the trait `Sized` is not implemented for `A` note: required because it appears within the type `Bar` --> $DIR/extern-types-unsized.rs:14:8 | diff --git a/tests/ui/feature-gates/feature-gate-offset-of-slice.stderr b/tests/ui/feature-gates/feature-gate-offset-of-slice.stderr index 5cf34a897f4d..ae8d50344d59 100644 --- a/tests/ui/feature-gates/feature-gate-offset-of-slice.stderr +++ b/tests/ui/feature-gates/feature-gate-offset-of-slice.stderr @@ -13,7 +13,7 @@ error[E0277]: the size for values of type `[i32]` cannot be known at compilation LL | offset_of!(T, y); | ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `S`, the trait `Sized` is not implemented for `[i32]`, which is required by `S: Sized` + = help: within `S`, the trait `Sized` is not implemented for `[i32]` note: required because it appears within the type `S` --> $DIR/feature-gate-offset-of-slice.rs:3:8 | diff --git a/tests/ui/feature-gates/feature-gate-trivial_bounds.stderr b/tests/ui/feature-gates/feature-gate-trivial_bounds.stderr index 0ee2d93fb26a..7d9c5b816516 100644 --- a/tests/ui/feature-gates/feature-gate-trivial_bounds.stderr +++ b/tests/ui/feature-gates/feature-gate-trivial_bounds.stderr @@ -120,7 +120,7 @@ error[E0277]: the size for values of type `(dyn A + 'static)` cannot be known at LL | fn unsized_local() where Dst: Sized { | ^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `Dst<(dyn A + 'static)>`, the trait `Sized` is not implemented for `(dyn A + 'static)`, which is required by `Dst<(dyn A + 'static)>: Sized` + = help: within `Dst<(dyn A + 'static)>`, the trait `Sized` is not implemented for `(dyn A + 'static)` note: required because it appears within the type `Dst<(dyn A + 'static)>` --> $DIR/feature-gate-trivial_bounds.rs:48:8 | diff --git a/tests/ui/fmt/ifmt-unimpl.stderr b/tests/ui/fmt/ifmt-unimpl.stderr index f83e7c877288..b8d4425a4a71 100644 --- a/tests/ui/fmt/ifmt-unimpl.stderr +++ b/tests/ui/fmt/ifmt-unimpl.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `str: UpperHex` is not satisfied --> $DIR/ifmt-unimpl.rs:2:21 | LL | format!("{:X}", "3"); - | ---- ^^^ the trait `UpperHex` is not implemented for `str`, which is required by `&str: UpperHex` + | ---- ^^^ the trait `UpperHex` is not implemented for `str` | | | required by a bound introduced by this call | diff --git a/tests/ui/for/for-c-in-str.stderr b/tests/ui/for/for-c-in-str.stderr index 2544df646299..475cf8c88749 100644 --- a/tests/ui/for/for-c-in-str.stderr +++ b/tests/ui/for/for-c-in-str.stderr @@ -4,7 +4,7 @@ error[E0277]: `&str` is not an iterator LL | for c in "asdf" { | ^^^^^^ `&str` is not an iterator; try calling `.chars()` or `.bytes()` | - = help: the trait `Iterator` is not implemented for `&str`, which is required by `&str: IntoIterator` + = help: the trait `Iterator` is not implemented for `&str` = note: required for `&str` to implement `IntoIterator` error: aborting due to 1 previous error diff --git a/tests/ui/for/for-loop-bogosity.stderr b/tests/ui/for/for-loop-bogosity.stderr index 143e4a4efd1f..194a2fa08cea 100644 --- a/tests/ui/for/for-loop-bogosity.stderr +++ b/tests/ui/for/for-loop-bogosity.stderr @@ -4,7 +4,7 @@ error[E0277]: `MyStruct` is not an iterator LL | for x in bogus { | ^^^^^ `MyStruct` is not an iterator | - = help: the trait `Iterator` is not implemented for `MyStruct`, which is required by `MyStruct: IntoIterator` + = help: the trait `Iterator` is not implemented for `MyStruct` = note: required for `MyStruct` to implement `IntoIterator` error: aborting due to 1 previous error diff --git a/tests/ui/function-pointer/unsized-ret.stderr b/tests/ui/function-pointer/unsized-ret.stderr index 81d603f4b20e..66116273ff4d 100644 --- a/tests/ui/function-pointer/unsized-ret.stderr +++ b/tests/ui/function-pointer/unsized-ret.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t LL | foo:: str, _>(None, ()); | ^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `fn() -> str`, the trait `Sized` is not implemented for `str`, which is required by `fn() -> str: Fn<_>` + = help: within `fn() -> str`, the trait `Sized` is not implemented for `str` = note: required because it appears within the type `fn() -> str` note: required by a bound in `foo` --> $DIR/unsized-ret.rs:5:11 @@ -18,7 +18,7 @@ error[E0277]: the size for values of type `(dyn std::fmt::Display + 'a)` cannot LL | foo:: fn(&'a ()) -> (dyn std::fmt::Display + 'a), _>(None, (&(),)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `for<'a> fn(&'a ()) -> (dyn std::fmt::Display + 'a)`, the trait `for<'a> Sized` is not implemented for `(dyn std::fmt::Display + 'a)`, which is required by `for<'a> fn(&'a ()) -> (dyn std::fmt::Display + 'a): Fn<_>` + = help: within `for<'a> fn(&'a ()) -> (dyn std::fmt::Display + 'a)`, the trait `for<'a> Sized` is not implemented for `(dyn std::fmt::Display + 'a)` = note: required because it appears within the type `for<'a> fn(&'a ()) -> (dyn std::fmt::Display + 'a)` note: required by a bound in `foo` --> $DIR/unsized-ret.rs:5:11 diff --git a/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.current.stderr b/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.current.stderr index c5c4f2c4d231..8779bab593a2 100644 --- a/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.current.stderr +++ b/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.current.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `::Bar<()>: Eq` is not satisfied --> $DIR/assume-gat-normalization-for-nested-goals.rs:9:30 | LL | type Bar: Baz = i32; - | ^^^ the trait `Eq` is not implemented for `::Bar<()>`, which is required by `i32: Baz` + | ^^^ the trait `Eq` is not implemented for `::Bar<()>` | note: required for `i32` to implement `Baz` --> $DIR/assume-gat-normalization-for-nested-goals.rs:16:23 diff --git a/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.next.stderr b/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.next.stderr index c5c4f2c4d231..8779bab593a2 100644 --- a/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.next.stderr +++ b/tests/ui/generic-associated-types/assume-gat-normalization-for-nested-goals.next.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `::Bar<()>: Eq` is not satisfied --> $DIR/assume-gat-normalization-for-nested-goals.rs:9:30 | LL | type Bar: Baz = i32; - | ^^^ the trait `Eq` is not implemented for `::Bar<()>`, which is required by `i32: Baz` + | ^^^ the trait `Eq` is not implemented for `::Bar<()>` | note: required for `i32` to implement `Baz` --> $DIR/assume-gat-normalization-for-nested-goals.rs:16:23 diff --git a/tests/ui/generic-associated-types/impl_bounds.stderr b/tests/ui/generic-associated-types/impl_bounds.stderr index c3b119e21443..261070d1db4b 100644 --- a/tests/ui/generic-associated-types/impl_bounds.stderr +++ b/tests/ui/generic-associated-types/impl_bounds.stderr @@ -25,7 +25,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/impl_bounds.rs:18:33 | LL | type C = String where Self: Copy; - | ^^^^ the trait `Copy` is not implemented for `T`, which is required by `Fooy: Copy` + | ^^^^ the trait `Copy` is not implemented for `T` | note: required for `Fooy` to implement `Copy` --> $DIR/impl_bounds.rs:10:10 @@ -50,7 +50,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/impl_bounds.rs:20:24 | LL | fn d() where Self: Copy {} - | ^^^^ the trait `Copy` is not implemented for `T`, which is required by `Fooy: Copy` + | ^^^^ the trait `Copy` is not implemented for `T` | note: required for `Fooy` to implement `Copy` --> $DIR/impl_bounds.rs:10:10 diff --git a/tests/ui/generic-associated-types/issue-101020.stderr b/tests/ui/generic-associated-types/issue-101020.stderr index 7faab4e52746..9c3753c2d180 100644 --- a/tests/ui/generic-associated-types/issue-101020.stderr +++ b/tests/ui/generic-associated-types/issue-101020.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `for<'a> &'a mut (): Foo<&'a mut ()>` is not satis --> $DIR/issue-101020.rs:31:22 | LL | (&mut EmptyIter).consume(()); - | ^^^^^^^ the trait `for<'a> Foo<&'a mut ()>` is not implemented for `&'a mut ()`, which is required by `for<'a> &'a mut (): FuncInput<'a, &'a mut ()>` + | ^^^^^^^ the trait `for<'a> Foo<&'a mut ()>` is not implemented for `&'a mut ()` | help: this trait has no implementations, consider adding one --> $DIR/issue-101020.rs:28:1 diff --git a/tests/ui/generic-associated-types/issue-74824.current.stderr b/tests/ui/generic-associated-types/issue-74824.current.stderr index b06c7f127ac0..231136612a05 100644 --- a/tests/ui/generic-associated-types/issue-74824.current.stderr +++ b/tests/ui/generic-associated-types/issue-74824.current.stderr @@ -14,7 +14,7 @@ error[E0277]: the trait bound `T: Clone` is not satisfied --> $DIR/issue-74824.rs:10:26 | LL | type Copy: Copy = Box; - | ^^^^^^ the trait `Clone` is not implemented for `T`, which is required by `::Copy: Copy` + | ^^^^^^ the trait `Clone` is not implemented for `T` | = note: required for `Box` to implement `Clone` = note: required for `::Copy` to implement `Copy` diff --git a/tests/ui/generic-associated-types/issue-74824.next.stderr b/tests/ui/generic-associated-types/issue-74824.next.stderr index b06c7f127ac0..231136612a05 100644 --- a/tests/ui/generic-associated-types/issue-74824.next.stderr +++ b/tests/ui/generic-associated-types/issue-74824.next.stderr @@ -14,7 +14,7 @@ error[E0277]: the trait bound `T: Clone` is not satisfied --> $DIR/issue-74824.rs:10:26 | LL | type Copy: Copy = Box; - | ^^^^^^ the trait `Clone` is not implemented for `T`, which is required by `::Copy: Copy` + | ^^^^^^ the trait `Clone` is not implemented for `T` | = note: required for `Box` to implement `Clone` = note: required for `::Copy` to implement `Copy` diff --git a/tests/ui/higher-ranked/trait-bounds/normalize-under-binder/issue-89118.stderr b/tests/ui/higher-ranked/trait-bounds/normalize-under-binder/issue-89118.stderr index 761fd9045a13..7fe803550bdd 100644 --- a/tests/ui/higher-ranked/trait-bounds/normalize-under-binder/issue-89118.stderr +++ b/tests/ui/higher-ranked/trait-bounds/normalize-under-binder/issue-89118.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `for<'a> &'a (): BufferMut` is not satisfied --> $DIR/issue-89118.rs:19:8 | LL | C: StackContext, - | ^^^^^^^^^^^^ the trait `for<'a> BufferMut` is not implemented for `&'a ()`, which is required by `for<'a> Ctx<()>: BufferUdpStateContext<&'a ()>` + | ^^^^^^^^^^^^ the trait `for<'a> BufferMut` is not implemented for `&'a ()` | help: this trait has no implementations, consider adding one --> $DIR/issue-89118.rs:1:1 @@ -29,7 +29,7 @@ error[E0277]: the trait bound `for<'a> &'a (): BufferMut` is not satisfied --> $DIR/issue-89118.rs:29:9 | LL | impl EthernetWorker {} - | ^^^^^^^^^^^^^^^^^ the trait `for<'a> BufferMut` is not implemented for `&'a ()`, which is required by `for<'a> Ctx<()>: BufferUdpStateContext<&'a ()>` + | ^^^^^^^^^^^^^^^^^ the trait `for<'a> BufferMut` is not implemented for `&'a ()` | help: this trait has no implementations, consider adding one --> $DIR/issue-89118.rs:1:1 @@ -56,7 +56,7 @@ error[E0277]: the trait bound `for<'a> &'a (): BufferMut` is not satisfied --> $DIR/issue-89118.rs:22:20 | LL | type Handler = Ctx; - | ^^^^^^^^^^^^^^^^^^ the trait `for<'a> BufferMut` is not implemented for `&'a ()`, which is required by `for<'a> Ctx<()>: BufferUdpStateContext<&'a ()>` + | ^^^^^^^^^^^^^^^^^^ the trait `for<'a> BufferMut` is not implemented for `&'a ()` | help: this trait has no implementations, consider adding one --> $DIR/issue-89118.rs:1:1 diff --git a/tests/ui/impl-trait/auto-trait-leak2.stderr b/tests/ui/impl-trait/auto-trait-leak2.stderr index 1fcde0372fc9..52fa28145d66 100644 --- a/tests/ui/impl-trait/auto-trait-leak2.stderr +++ b/tests/ui/impl-trait/auto-trait-leak2.stderr @@ -9,7 +9,7 @@ LL | send(before()); | | | required by a bound introduced by this call | - = help: within `impl Fn(i32)`, the trait `Send` is not implemented for `Rc>`, which is required by `impl Fn(i32): Send` + = help: within `impl Fn(i32)`, the trait `Send` is not implemented for `Rc>` note: required because it's used within this closure --> $DIR/auto-trait-leak2.rs:10:5 | @@ -37,7 +37,7 @@ LL | send(after()); LL | fn after() -> impl Fn(i32) { | ------------ within this `impl Fn(i32)` | - = help: within `impl Fn(i32)`, the trait `Send` is not implemented for `Rc>`, which is required by `impl Fn(i32): Send` + = help: within `impl Fn(i32)`, the trait `Send` is not implemented for `Rc>` note: required because it's used within this closure --> $DIR/auto-trait-leak2.rs:38:5 | diff --git a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg index e09b96e5ff2c..a18fc11a1e3c 100644 --- a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg +++ b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg @@ -29,7 +29,7 @@ LL | fn foo() -> impl Foo<i32> { - | ^^^^^^^^^^^^^ the trait `Bar<i32>` is not implemented for `Struct`, which is required by `Struct: Foo<i32>` + | ^^^^^^^^^^^^^ the trait `Bar<i32>` is not implemented for `Struct` | diff --git a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr index 9c5466595645..8716088ccbd2 100644 --- a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr +++ b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr @@ -16,7 +16,7 @@ LL | fn fuz() -> (usize, Trait) { (42, Struct) } | | | doesn't have a size known at compile-time | - = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)`, which is required by `(usize, (dyn Trait + 'static)): Sized` + = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` = note: required because it appears within the type `(usize, (dyn Trait + 'static))` = note: the return type of a function must have a statically known size @@ -38,7 +38,7 @@ LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } | | | doesn't have a size known at compile-time | - = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)`, which is required by `(usize, (dyn Trait + 'static)): Sized` + = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` = note: required because it appears within the type `(usize, (dyn Trait + 'static))` = note: the return type of a function must have a statically known size diff --git a/tests/ui/impl-trait/in-trait/false-positive-predicate-entailment-error.current.stderr b/tests/ui/impl-trait/in-trait/false-positive-predicate-entailment-error.current.stderr index 058517f0014e..38c7a9ea16e6 100644 --- a/tests/ui/impl-trait/in-trait/false-positive-predicate-entailment-error.current.stderr +++ b/tests/ui/impl-trait/in-trait/false-positive-predicate-entailment-error.current.stderr @@ -8,7 +8,7 @@ LL | | ... | LL | | where LL | | F: Callback, - | |_______________________________________^ the trait `MyFn` is not implemented for `F`, which is required by `F: Callback` + | |_______________________________________^ the trait `MyFn` is not implemented for `F` | note: required for `F` to implement `Callback` --> $DIR/false-positive-predicate-entailment-error.rs:14:21 @@ -26,7 +26,7 @@ error[E0277]: the trait bound `F: MyFn` is not satisfied --> $DIR/false-positive-predicate-entailment-error.rs:36:30 | LL | fn autobatch(self) -> impl Trait - | ^^^^^^^^^^ the trait `MyFn` is not implemented for `F`, which is required by `F: Callback` + | ^^^^^^^^^^ the trait `MyFn` is not implemented for `F` | note: required for `F` to implement `Callback` --> $DIR/false-positive-predicate-entailment-error.rs:14:21 @@ -58,7 +58,7 @@ LL | | ... | LL | | where LL | | F: Callback, - | |_______________________________________^ the trait `MyFn` is not implemented for `F`, which is required by `F: Callback` + | |_______________________________________^ the trait `MyFn` is not implemented for `F` | note: required for `F` to implement `Callback` --> $DIR/false-positive-predicate-entailment-error.rs:14:21 @@ -77,7 +77,7 @@ error[E0277]: the trait bound `F: MyFn` is not satisfied --> $DIR/false-positive-predicate-entailment-error.rs:36:30 | LL | fn autobatch(self) -> impl Trait - | ^^^^^^^^^^ the trait `MyFn` is not implemented for `F`, which is required by `F: Callback` + | ^^^^^^^^^^ the trait `MyFn` is not implemented for `F` | note: required for `F` to implement `Callback` --> $DIR/false-positive-predicate-entailment-error.rs:14:21 @@ -91,7 +91,7 @@ error[E0277]: the trait bound `F: Callback` is not satisfied --> $DIR/false-positive-predicate-entailment-error.rs:27:12 | LL | F: Callback; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `MyFn` is not implemented for `F`, which is required by `F: Callback` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `MyFn` is not implemented for `F` | note: required for `F` to implement `Callback` --> $DIR/false-positive-predicate-entailment-error.rs:14:21 @@ -111,7 +111,7 @@ LL | | ... | LL | | where LL | | F: Callback, - | |_______________________________________^ the trait `MyFn` is not implemented for `F`, which is required by `F: Callback` + | |_______________________________________^ the trait `MyFn` is not implemented for `F` | note: required for `F` to implement `Callback` --> $DIR/false-positive-predicate-entailment-error.rs:14:21 diff --git a/tests/ui/impl-trait/issue-55872-1.stderr b/tests/ui/impl-trait/issue-55872-1.stderr index 0c86824e6221..8912cce1b4b5 100644 --- a/tests/ui/impl-trait/issue-55872-1.stderr +++ b/tests/ui/impl-trait/issue-55872-1.stderr @@ -11,7 +11,7 @@ error[E0277]: the trait bound `S: Copy` is not satisfied in `(S, T)` --> $DIR/issue-55872-1.rs:12:29 | LL | fn foo() -> Self::E { - | ^^^^^^^ within `(S, T)`, the trait `Copy` is not implemented for `S`, which is required by `(S, T): Copy` + | ^^^^^^^ within `(S, T)`, the trait `Copy` is not implemented for `S` | = note: required because it appears within the type `(S, T)` help: consider further restricting this bound @@ -23,7 +23,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied in `(S, T)` --> $DIR/issue-55872-1.rs:12:29 | LL | fn foo() -> Self::E { - | ^^^^^^^ within `(S, T)`, the trait `Copy` is not implemented for `T`, which is required by `(S, T): Copy` + | ^^^^^^^ within `(S, T)`, the trait `Copy` is not implemented for `T` | = note: required because it appears within the type `(S, T)` help: consider further restricting this bound diff --git a/tests/ui/impl-trait/nested_impl_trait.stderr b/tests/ui/impl-trait/nested_impl_trait.stderr index 83d1347aff43..31c3e0c90136 100644 --- a/tests/ui/impl-trait/nested_impl_trait.stderr +++ b/tests/ui/impl-trait/nested_impl_trait.stderr @@ -46,7 +46,7 @@ error[E0277]: the trait bound `impl Debug: From>` is not satisfie --> $DIR/nested_impl_trait.rs:6:46 | LL | fn bad_in_ret_position(x: impl Into) -> impl Into { x } - | ^^^^^^^^^^^^^^^^^^^^^ the trait `From>` is not implemented for `impl Debug`, which is required by `impl Into: Into` + | ^^^^^^^^^^^^^^^^^^^^^ the trait `From>` is not implemented for `impl Debug` | = help: the trait `Into` is implemented for `T` = note: required for `impl Into` to implement `Into` @@ -55,7 +55,7 @@ error[E0277]: the trait bound `impl Debug: From>` is not satisfie --> $DIR/nested_impl_trait.rs:19:34 | LL | fn bad(x: impl Into) -> impl Into { x } - | ^^^^^^^^^^^^^^^^^^^^^ the trait `From>` is not implemented for `impl Debug`, which is required by `impl Into: Into` + | ^^^^^^^^^^^^^^^^^^^^^ the trait `From>` is not implemented for `impl Debug` | = help: the trait `Into` is implemented for `T` = note: required for `impl Into` to implement `Into` diff --git a/tests/ui/indexing/index-help.stderr b/tests/ui/indexing/index-help.stderr index 1291bf2a4611..4ec28ddf8717 100644 --- a/tests/ui/indexing/index-help.stderr +++ b/tests/ui/indexing/index-help.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `[{integer}]` cannot be indexed by `i32` LL | x[0i32]; | ^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[{integer}]>` is not implemented for `i32`, which is required by `Vec<{integer}>: Index<_>` + = help: the trait `SliceIndex<[{integer}]>` is not implemented for `i32` = help: the trait `SliceIndex<[{integer}]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `i32` = note: required for `Vec<{integer}>` to implement `Index` diff --git a/tests/ui/indexing/indexing-requires-a-uint.stderr b/tests/ui/indexing/indexing-requires-a-uint.stderr index 38e7881dcc67..3041c2c99a10 100644 --- a/tests/ui/indexing/indexing-requires-a-uint.stderr +++ b/tests/ui/indexing/indexing-requires-a-uint.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `[{integer}]` cannot be indexed by `u8` LL | [0][0u8]; | ^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[{integer}]>` is not implemented for `u8`, which is required by `[{integer}; 1]: Index<_>` + = help: the trait `SliceIndex<[{integer}]>` is not implemented for `u8` = help: the trait `SliceIndex<[{integer}]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `u8` = note: required for `[{integer}]` to implement `Index` diff --git a/tests/ui/indexing/point-at-index-for-obligation-failure.stderr b/tests/ui/indexing/point-at-index-for-obligation-failure.stderr index df4d7cc0683d..4cced22789f7 100644 --- a/tests/ui/indexing/point-at-index-for-obligation-failure.stderr +++ b/tests/ui/indexing/point-at-index-for-obligation-failure.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `String: Borrow<&str>` is not satisfied --> $DIR/point-at-index-for-obligation-failure.rs:5:9 | LL | &s - | ^^ the trait `Borrow<&str>` is not implemented for `String`, which is required by `HashMap: Index<&_>` + | ^^ the trait `Borrow<&str>` is not implemented for `String` | = help: the trait `Borrow` is implemented for `String` = help: for that trait implementation, expected `str`, found `&str` diff --git a/tests/ui/integral-indexing.stderr b/tests/ui/integral-indexing.stderr index ad2c3af424be..97e658617cf0 100644 --- a/tests/ui/integral-indexing.stderr +++ b/tests/ui/integral-indexing.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `[isize]` cannot be indexed by `u8` LL | v[3u8]; | ^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[isize]>` is not implemented for `u8`, which is required by `Vec: Index<_>` + = help: the trait `SliceIndex<[isize]>` is not implemented for `u8` = help: the trait `SliceIndex<[isize]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `u8` = note: required for `Vec` to implement `Index` @@ -15,7 +15,7 @@ error[E0277]: the type `[isize]` cannot be indexed by `i8` LL | v[3i8]; | ^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[isize]>` is not implemented for `i8`, which is required by `Vec: Index<_>` + = help: the trait `SliceIndex<[isize]>` is not implemented for `i8` = help: the trait `SliceIndex<[isize]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `i8` = note: required for `Vec` to implement `Index` @@ -26,7 +26,7 @@ error[E0277]: the type `[isize]` cannot be indexed by `u32` LL | v[3u32]; | ^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[isize]>` is not implemented for `u32`, which is required by `Vec: Index<_>` + = help: the trait `SliceIndex<[isize]>` is not implemented for `u32` = help: the trait `SliceIndex<[isize]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `u32` = note: required for `Vec` to implement `Index` @@ -37,7 +37,7 @@ error[E0277]: the type `[isize]` cannot be indexed by `i32` LL | v[3i32]; | ^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[isize]>` is not implemented for `i32`, which is required by `Vec: Index<_>` + = help: the trait `SliceIndex<[isize]>` is not implemented for `i32` = help: the trait `SliceIndex<[isize]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `i32` = note: required for `Vec` to implement `Index` @@ -48,7 +48,7 @@ error[E0277]: the type `[u8]` cannot be indexed by `u8` LL | s.as_bytes()[3u8]; | ^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[u8]>` is not implemented for `u8`, which is required by `[u8]: Index<_>` + = help: the trait `SliceIndex<[u8]>` is not implemented for `u8` = help: the trait `SliceIndex<[u8]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `u8` = note: required for `[u8]` to implement `Index` @@ -59,7 +59,7 @@ error[E0277]: the type `[u8]` cannot be indexed by `i8` LL | s.as_bytes()[3i8]; | ^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[u8]>` is not implemented for `i8`, which is required by `[u8]: Index<_>` + = help: the trait `SliceIndex<[u8]>` is not implemented for `i8` = help: the trait `SliceIndex<[u8]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `i8` = note: required for `[u8]` to implement `Index` @@ -70,7 +70,7 @@ error[E0277]: the type `[u8]` cannot be indexed by `u32` LL | s.as_bytes()[3u32]; | ^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[u8]>` is not implemented for `u32`, which is required by `[u8]: Index<_>` + = help: the trait `SliceIndex<[u8]>` is not implemented for `u32` = help: the trait `SliceIndex<[u8]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `u32` = note: required for `[u8]` to implement `Index` @@ -81,7 +81,7 @@ error[E0277]: the type `[u8]` cannot be indexed by `i32` LL | s.as_bytes()[3i32]; | ^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[u8]>` is not implemented for `i32`, which is required by `[u8]: Index<_>` + = help: the trait `SliceIndex<[u8]>` is not implemented for `i32` = help: the trait `SliceIndex<[u8]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `i32` = note: required for `[u8]` to implement `Index` diff --git a/tests/ui/interior-mutability/interior-mutability.stderr b/tests/ui/interior-mutability/interior-mutability.stderr index 29b250c1b07c..cfc64445bf3b 100644 --- a/tests/ui/interior-mutability/interior-mutability.stderr +++ b/tests/ui/interior-mutability/interior-mutability.stderr @@ -6,7 +6,7 @@ LL | catch_unwind(|| { x.set(23); }); | | | required by a bound introduced by this call | - = help: within `Cell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `{closure@$DIR/interior-mutability.rs:5:18: 5:20}: UnwindSafe` + = help: within `Cell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `Cell` --> $SRC_DIR/core/src/cell.rs:LL:COL = note: required for `&Cell` to implement `UnwindSafe` diff --git a/tests/ui/issues/issue-21763.stderr b/tests/ui/issues/issue-21763.stderr index aa4938a0c0b3..135b705eeeff 100644 --- a/tests/ui/issues/issue-21763.stderr +++ b/tests/ui/issues/issue-21763.stderr @@ -4,7 +4,7 @@ error[E0277]: `Rc<()>` cannot be sent between threads safely LL | foo::, Rc<()>>>(); | ^^^^^^^^^^^^^^^^^^^^^^^ `Rc<()>` cannot be sent between threads safely | - = help: within `(Rc<()>, Rc<()>)`, the trait `Send` is not implemented for `Rc<()>`, which is required by `HashMap, Rc<()>>: Send` + = help: within `(Rc<()>, Rc<()>)`, the trait `Send` is not implemented for `Rc<()>` = note: required because it appears within the type `(Rc<()>, Rc<()>)` = note: required for `hashbrown::raw::RawTable<(Rc<()>, Rc<()>)>` to implement `Send` note: required because it appears within the type `hashbrown::map::HashMap, Rc<()>, RandomState>` diff --git a/tests/ui/issues/issue-22872.stderr b/tests/ui/issues/issue-22872.stderr index 03e5393da488..6ff710b11332 100644 --- a/tests/ui/issues/issue-22872.stderr +++ b/tests/ui/issues/issue-22872.stderr @@ -4,7 +4,7 @@ error[E0277]: `

>::Item` is not an iterator LL | let _: Box Wrap<'b>> = Box::new(Wrapper(process)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ `

>::Item` is not an iterator | - = help: the trait `Iterator` is not implemented for `

>::Item`, which is required by `for<'b> Wrapper

: Wrap<'b>` + = help: the trait `Iterator` is not implemented for `

>::Item` note: required for `Wrapper

` to implement `for<'b> Wrap<'b>` --> $DIR/issue-22872.rs:7:13 | diff --git a/tests/ui/issues/issue-22874.stderr b/tests/ui/issues/issue-22874.stderr index 29ddf9756ff8..7d5b601ed494 100644 --- a/tests/ui/issues/issue-22874.stderr +++ b/tests/ui/issues/issue-22874.stderr @@ -13,7 +13,7 @@ error[E0277]: the size for values of type `[String]` cannot be known at compilat LL | &table.rows[0] | ^^^^^^^^^^ doesn't have a size known at compile-time | - = help: the trait `Sized` is not implemented for `[String]`, which is required by `[_]: Index<_>` + = help: the trait `Sized` is not implemented for `[String]` = note: required for `[[String]]` to implement `Index<_>` error: aborting due to 2 previous errors diff --git a/tests/ui/issues/issue-40827.stderr b/tests/ui/issues/issue-40827.stderr index 44ae90cbc0ff..7f5c578ae4ff 100644 --- a/tests/ui/issues/issue-40827.stderr +++ b/tests/ui/issues/issue-40827.stderr @@ -6,7 +6,7 @@ LL | f(Foo(Arc::new(Bar::B(None)))); | | | required by a bound introduced by this call | - = help: within `Bar`, the trait `Sync` is not implemented for `Rc`, which is required by `Foo: Send` + = help: within `Bar`, the trait `Sync` is not implemented for `Rc` note: required because it appears within the type `Bar` --> $DIR/issue-40827.rs:6:6 | @@ -32,7 +32,7 @@ LL | f(Foo(Arc::new(Bar::B(None)))); | | | required by a bound introduced by this call | - = help: within `Bar`, the trait `Send` is not implemented for `Rc`, which is required by `Foo: Send` + = help: within `Bar`, the trait `Send` is not implemented for `Rc` note: required because it appears within the type `Bar` --> $DIR/issue-40827.rs:6:6 | diff --git a/tests/ui/issues/issue-7364.stderr b/tests/ui/issues/issue-7364.stderr index d5b6dde1f10e..65ec1d750537 100644 --- a/tests/ui/issues/issue-7364.stderr +++ b/tests/ui/issues/issue-7364.stderr @@ -4,7 +4,7 @@ error[E0277]: `RefCell` cannot be shared between threads safely LL | static boxed: Box> = Box::new(RefCell::new(0)); | ^^^^^^^^^^^^^^^^^^^ `RefCell` cannot be shared between threads safely | - = help: the trait `Sync` is not implemented for `RefCell`, which is required by `Box>: Sync` + = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `Unique>` to implement `Sync` note: required because it appears within the type `Box>` diff --git a/tests/ui/iterators/float_iterator_hint.stderr b/tests/ui/iterators/float_iterator_hint.stderr index 29319b9400f0..c3cb00c3c684 100644 --- a/tests/ui/iterators/float_iterator_hint.stderr +++ b/tests/ui/iterators/float_iterator_hint.stderr @@ -4,7 +4,7 @@ error[E0277]: `{float}` is not an iterator LL | for i in 0.2 { | ^^^ `{float}` is not an iterator | - = help: the trait `Iterator` is not implemented for `{float}`, which is required by `{float}: IntoIterator` + = help: the trait `Iterator` is not implemented for `{float}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `{float}` to implement `IntoIterator` diff --git a/tests/ui/iterators/integral.stderr b/tests/ui/iterators/integral.stderr index 74bbe28d6b71..c142fec8da0f 100644 --- a/tests/ui/iterators/integral.stderr +++ b/tests/ui/iterators/integral.stderr @@ -4,7 +4,7 @@ error[E0277]: `{integer}` is not an iterator LL | for _ in 42 {} | ^^ `{integer}` is not an iterator | - = help: the trait `Iterator` is not implemented for `{integer}`, which is required by `{integer}: IntoIterator` + = help: the trait `Iterator` is not implemented for `{integer}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `{integer}` to implement `IntoIterator` @@ -14,7 +14,7 @@ error[E0277]: `u8` is not an iterator LL | for _ in 42 as u8 {} | ^^^^^^^^ `u8` is not an iterator | - = help: the trait `Iterator` is not implemented for `u8`, which is required by `u8: IntoIterator` + = help: the trait `Iterator` is not implemented for `u8` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `u8` to implement `IntoIterator` @@ -24,7 +24,7 @@ error[E0277]: `i8` is not an iterator LL | for _ in 42 as i8 {} | ^^^^^^^^ `i8` is not an iterator | - = help: the trait `Iterator` is not implemented for `i8`, which is required by `i8: IntoIterator` + = help: the trait `Iterator` is not implemented for `i8` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `i8` to implement `IntoIterator` @@ -34,7 +34,7 @@ error[E0277]: `u16` is not an iterator LL | for _ in 42 as u16 {} | ^^^^^^^^^ `u16` is not an iterator | - = help: the trait `Iterator` is not implemented for `u16`, which is required by `u16: IntoIterator` + = help: the trait `Iterator` is not implemented for `u16` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `u16` to implement `IntoIterator` @@ -44,7 +44,7 @@ error[E0277]: `i16` is not an iterator LL | for _ in 42 as i16 {} | ^^^^^^^^^ `i16` is not an iterator | - = help: the trait `Iterator` is not implemented for `i16`, which is required by `i16: IntoIterator` + = help: the trait `Iterator` is not implemented for `i16` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `i16` to implement `IntoIterator` @@ -54,7 +54,7 @@ error[E0277]: `u32` is not an iterator LL | for _ in 42 as u32 {} | ^^^^^^^^^ `u32` is not an iterator | - = help: the trait `Iterator` is not implemented for `u32`, which is required by `u32: IntoIterator` + = help: the trait `Iterator` is not implemented for `u32` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `u32` to implement `IntoIterator` @@ -64,7 +64,7 @@ error[E0277]: `i32` is not an iterator LL | for _ in 42 as i32 {} | ^^^^^^^^^ `i32` is not an iterator | - = help: the trait `Iterator` is not implemented for `i32`, which is required by `i32: IntoIterator` + = help: the trait `Iterator` is not implemented for `i32` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `i32` to implement `IntoIterator` @@ -74,7 +74,7 @@ error[E0277]: `u64` is not an iterator LL | for _ in 42 as u64 {} | ^^^^^^^^^ `u64` is not an iterator | - = help: the trait `Iterator` is not implemented for `u64`, which is required by `u64: IntoIterator` + = help: the trait `Iterator` is not implemented for `u64` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `u64` to implement `IntoIterator` @@ -84,7 +84,7 @@ error[E0277]: `i64` is not an iterator LL | for _ in 42 as i64 {} | ^^^^^^^^^ `i64` is not an iterator | - = help: the trait `Iterator` is not implemented for `i64`, which is required by `i64: IntoIterator` + = help: the trait `Iterator` is not implemented for `i64` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `i64` to implement `IntoIterator` @@ -94,7 +94,7 @@ error[E0277]: `usize` is not an iterator LL | for _ in 42 as usize {} | ^^^^^^^^^^^ `usize` is not an iterator | - = help: the trait `Iterator` is not implemented for `usize`, which is required by `usize: IntoIterator` + = help: the trait `Iterator` is not implemented for `usize` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `usize` to implement `IntoIterator` @@ -104,7 +104,7 @@ error[E0277]: `isize` is not an iterator LL | for _ in 42 as isize {} | ^^^^^^^^^^^ `isize` is not an iterator | - = help: the trait `Iterator` is not implemented for `isize`, which is required by `isize: IntoIterator` + = help: the trait `Iterator` is not implemented for `isize` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `isize` to implement `IntoIterator` @@ -114,7 +114,7 @@ error[E0277]: `{float}` is not an iterator LL | for _ in 42.0 {} | ^^^^ `{float}` is not an iterator | - = help: the trait `Iterator` is not implemented for `{float}`, which is required by `{float}: IntoIterator` + = help: the trait `Iterator` is not implemented for `{float}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `{float}` to implement `IntoIterator` diff --git a/tests/ui/iterators/issue-28098.stderr b/tests/ui/iterators/issue-28098.stderr index 3cb1b2f72700..a724f03ad4af 100644 --- a/tests/ui/iterators/issue-28098.stderr +++ b/tests/ui/iterators/issue-28098.stderr @@ -14,7 +14,7 @@ error[E0277]: `bool` is not an iterator LL | for _ in false {} | ^^^^^ `bool` is not an iterator | - = help: the trait `Iterator` is not implemented for `bool`, which is required by `bool: IntoIterator` + = help: the trait `Iterator` is not implemented for `bool` = note: required for `bool` to implement `IntoIterator` error[E0277]: `()` is not an iterator @@ -61,7 +61,7 @@ error[E0277]: `bool` is not an iterator LL | for _ in false {} | ^^^^^ `bool` is not an iterator | - = help: the trait `Iterator` is not implemented for `bool`, which is required by `bool: IntoIterator` + = help: the trait `Iterator` is not implemented for `bool` = note: required for `bool` to implement `IntoIterator` error[E0277]: `()` is not an iterator diff --git a/tests/ui/iterators/ranges.stderr b/tests/ui/iterators/ranges.stderr index a5d43ecbb633..b9fbcd5304b1 100644 --- a/tests/ui/iterators/ranges.stderr +++ b/tests/ui/iterators/ranges.stderr @@ -4,7 +4,7 @@ error[E0277]: `RangeTo<{integer}>` is not an iterator LL | for _ in ..10 {} | ^^^^ if you meant to iterate until a value, add a starting value | - = help: the trait `Iterator` is not implemented for `RangeTo<{integer}>`, which is required by `RangeTo<{integer}>: IntoIterator` + = help: the trait `Iterator` is not implemented for `RangeTo<{integer}>` = note: `..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a bounded `Range`: `0..end` = note: required for `RangeTo<{integer}>` to implement `IntoIterator` @@ -14,7 +14,7 @@ error[E0277]: `RangeToInclusive<{integer}>` is not an iterator LL | for _ in ..=10 {} | ^^^^^ if you meant to iterate until a value (including it), add a starting value | - = help: the trait `Iterator` is not implemented for `RangeToInclusive<{integer}>`, which is required by `RangeToInclusive<{integer}>: IntoIterator` + = help: the trait `Iterator` is not implemented for `RangeToInclusive<{integer}>` = note: `..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant to have a bounded `RangeInclusive`: `0..=end` = note: required for `RangeToInclusive<{integer}>` to implement `IntoIterator` diff --git a/tests/ui/iterators/string.stderr b/tests/ui/iterators/string.stderr index 29f560677c07..ddfe0169b848 100644 --- a/tests/ui/iterators/string.stderr +++ b/tests/ui/iterators/string.stderr @@ -4,7 +4,7 @@ error[E0277]: `String` is not an iterator LL | for _ in "".to_owned() {} | ^^^^^^^^^^^^^ `String` is not an iterator; try calling `.chars()` or `.bytes()` | - = help: the trait `Iterator` is not implemented for `String`, which is required by `String: IntoIterator` + = help: the trait `Iterator` is not implemented for `String` = note: required for `String` to implement `IntoIterator` error[E0277]: `&str` is not an iterator @@ -13,7 +13,7 @@ error[E0277]: `&str` is not an iterator LL | for _ in "" {} | ^^ `&str` is not an iterator; try calling `.chars()` or `.bytes()` | - = help: the trait `Iterator` is not implemented for `&str`, which is required by `&str: IntoIterator` + = help: the trait `Iterator` is not implemented for `&str` = note: required for `&str` to implement `IntoIterator` error: aborting due to 2 previous errors diff --git a/tests/ui/kindck/kindck-impl-type-params-2.stderr b/tests/ui/kindck/kindck-impl-type-params-2.stderr index a7d169d3ac4a..38dc94f9104d 100644 --- a/tests/ui/kindck/kindck-impl-type-params-2.stderr +++ b/tests/ui/kindck/kindck-impl-type-params-2.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Box<{integer}>: Foo` is not satisfied --> $DIR/kindck-impl-type-params-2.rs:13:16 | LL | take_param(&x); - | ---------- ^^ the trait `Copy` is not implemented for `Box<{integer}>`, which is required by `Box<{integer}>: Foo` + | ---------- ^^ the trait `Copy` is not implemented for `Box<{integer}>` | | | required by a bound introduced by this call | diff --git a/tests/ui/kindck/kindck-impl-type-params.stderr b/tests/ui/kindck/kindck-impl-type-params.stderr index 5892596dc6ad..da9a8e5532c3 100644 --- a/tests/ui/kindck/kindck-impl-type-params.stderr +++ b/tests/ui/kindck/kindck-impl-type-params.stderr @@ -21,7 +21,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/kindck-impl-type-params.rs:16:13 | LL | let a = &t as &dyn Gettable; - | ^^ the trait `Copy` is not implemented for `T`, which is required by `S: Gettable` + | ^^ the trait `Copy` is not implemented for `T` | note: required for `S` to implement `Gettable` --> $DIR/kindck-impl-type-params.rs:12:32 @@ -59,7 +59,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/kindck-impl-type-params.rs:23:31 | LL | let a: &dyn Gettable = &t; - | ^^ the trait `Copy` is not implemented for `T`, which is required by `S: Gettable` + | ^^ the trait `Copy` is not implemented for `T` | note: required for `S` to implement `Gettable` --> $DIR/kindck-impl-type-params.rs:12:32 @@ -78,7 +78,7 @@ error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/kindck-impl-type-params.rs:36:13 | LL | let a = t as Box>; - | ^ the trait `Copy` is not implemented for `String`, which is required by `S: Gettable` + | ^ the trait `Copy` is not implemented for `String` | = help: the trait `Gettable` is implemented for `S` note: required for `S` to implement `Gettable` @@ -94,7 +94,7 @@ error[E0277]: the trait bound `Foo: Copy` is not satisfied --> $DIR/kindck-impl-type-params.rs:44:37 | LL | let a: Box> = t; - | ^ the trait `Copy` is not implemented for `Foo`, which is required by `S: Gettable` + | ^ the trait `Copy` is not implemented for `Foo` | = help: the trait `Gettable` is implemented for `S` note: required for `S` to implement `Gettable` diff --git a/tests/ui/kindck/kindck-inherited-copy-bound.curr.stderr b/tests/ui/kindck/kindck-inherited-copy-bound.curr.stderr index e797ca01f4bc..c392879db3eb 100644 --- a/tests/ui/kindck/kindck-inherited-copy-bound.curr.stderr +++ b/tests/ui/kindck/kindck-inherited-copy-bound.curr.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Box<{integer}>: Foo` is not satisfied --> $DIR/kindck-inherited-copy-bound.rs:21:16 | LL | take_param(&x); - | ---------- ^^ the trait `Copy` is not implemented for `Box<{integer}>`, which is required by `Box<{integer}>: Foo` + | ---------- ^^ the trait `Copy` is not implemented for `Box<{integer}>` | | | required by a bound introduced by this call | diff --git a/tests/ui/kindck/kindck-inherited-copy-bound.dyn_compatible_for_dispatch.stderr b/tests/ui/kindck/kindck-inherited-copy-bound.dyn_compatible_for_dispatch.stderr index b4424f4750e6..34dcad13af30 100644 --- a/tests/ui/kindck/kindck-inherited-copy-bound.dyn_compatible_for_dispatch.stderr +++ b/tests/ui/kindck/kindck-inherited-copy-bound.dyn_compatible_for_dispatch.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Box<{integer}>: Foo` is not satisfied --> $DIR/kindck-inherited-copy-bound.rs:21:16 | LL | take_param(&x); - | ---------- ^^ the trait `Copy` is not implemented for `Box<{integer}>`, which is required by `Box<{integer}>: Foo` + | ---------- ^^ the trait `Copy` is not implemented for `Box<{integer}>` | | | required by a bound introduced by this call | diff --git a/tests/ui/kindck/kindck-nonsendable-1.stderr b/tests/ui/kindck/kindck-nonsendable-1.stderr index 8cc931bc48ed..8bb784d1d496 100644 --- a/tests/ui/kindck/kindck-nonsendable-1.stderr +++ b/tests/ui/kindck/kindck-nonsendable-1.stderr @@ -8,7 +8,7 @@ LL | bar(move|| foo(x)); | | within this `{closure@$DIR/kindck-nonsendable-1.rs:9:9: 9:15}` | required by a bound introduced by this call | - = help: within `{closure@$DIR/kindck-nonsendable-1.rs:9:9: 9:15}`, the trait `Send` is not implemented for `Rc`, which is required by `{closure@$DIR/kindck-nonsendable-1.rs:9:9: 9:15}: Send` + = help: within `{closure@$DIR/kindck-nonsendable-1.rs:9:9: 9:15}`, the trait `Send` is not implemented for `Rc` note: required because it's used within this closure --> $DIR/kindck-nonsendable-1.rs:9:9 | diff --git a/tests/ui/kindck/kindck-send-object.stderr b/tests/ui/kindck/kindck-send-object.stderr index 7d0c711abc4c..0e2ff1730c8d 100644 --- a/tests/ui/kindck/kindck-send-object.stderr +++ b/tests/ui/kindck/kindck-send-object.stderr @@ -4,7 +4,7 @@ error[E0277]: `&'static (dyn Dummy + 'static)` cannot be sent between threads sa LL | assert_send::<&'static (dyn Dummy + 'static)>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&'static (dyn Dummy + 'static)` cannot be sent between threads safely | - = help: the trait `Sync` is not implemented for `(dyn Dummy + 'static)`, which is required by `&'static (dyn Dummy + 'static): Send` + = help: the trait `Sync` is not implemented for `(dyn Dummy + 'static)` = note: required for `&'static (dyn Dummy + 'static)` to implement `Send` note: required by a bound in `assert_send` --> $DIR/kindck-send-object.rs:5:18 @@ -18,7 +18,7 @@ error[E0277]: `dyn Dummy` cannot be sent between threads safely LL | assert_send::>(); | ^^^^^^^^^^^^^^ `dyn Dummy` cannot be sent between threads safely | - = help: the trait `Send` is not implemented for `dyn Dummy`, which is required by `Box: Send` + = help: the trait `Send` is not implemented for `dyn Dummy` = note: required for `Unique` to implement `Send` note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL diff --git a/tests/ui/kindck/kindck-send-object1.stderr b/tests/ui/kindck/kindck-send-object1.stderr index 7f39dab2086a..e3ff2eb9ff4c 100644 --- a/tests/ui/kindck/kindck-send-object1.stderr +++ b/tests/ui/kindck/kindck-send-object1.stderr @@ -4,7 +4,7 @@ error[E0277]: `&'a (dyn Dummy + 'a)` cannot be sent between threads safely LL | assert_send::<&'a dyn Dummy>(); | ^^^^^^^^^^^^^ `&'a (dyn Dummy + 'a)` cannot be sent between threads safely | - = help: the trait `Sync` is not implemented for `(dyn Dummy + 'a)`, which is required by `&'a (dyn Dummy + 'a): Send` + = help: the trait `Sync` is not implemented for `(dyn Dummy + 'a)` = note: required for `&'a (dyn Dummy + 'a)` to implement `Send` note: required by a bound in `assert_send` --> $DIR/kindck-send-object1.rs:5:18 @@ -18,7 +18,7 @@ error[E0277]: `(dyn Dummy + 'a)` cannot be sent between threads safely LL | assert_send::>(); | ^^^^^^^^^^^^^^^^^^^ `(dyn Dummy + 'a)` cannot be sent between threads safely | - = help: the trait `Send` is not implemented for `(dyn Dummy + 'a)`, which is required by `Box<(dyn Dummy + 'a)>: Send` + = help: the trait `Send` is not implemented for `(dyn Dummy + 'a)` = note: required for `Unique<(dyn Dummy + 'a)>` to implement `Send` note: required because it appears within the type `Box<(dyn Dummy + 'a)>` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL diff --git a/tests/ui/kindck/kindck-send-object2.stderr b/tests/ui/kindck/kindck-send-object2.stderr index a481a132ccef..8898bf5b3fab 100644 --- a/tests/ui/kindck/kindck-send-object2.stderr +++ b/tests/ui/kindck/kindck-send-object2.stderr @@ -4,7 +4,7 @@ error[E0277]: `&'static (dyn Dummy + 'static)` cannot be sent between threads sa LL | assert_send::<&'static dyn Dummy>(); | ^^^^^^^^^^^^^^^^^^ `&'static (dyn Dummy + 'static)` cannot be sent between threads safely | - = help: the trait `Sync` is not implemented for `(dyn Dummy + 'static)`, which is required by `&'static (dyn Dummy + 'static): Send` + = help: the trait `Sync` is not implemented for `(dyn Dummy + 'static)` = note: required for `&'static (dyn Dummy + 'static)` to implement `Send` note: required by a bound in `assert_send` --> $DIR/kindck-send-object2.rs:3:18 @@ -18,7 +18,7 @@ error[E0277]: `dyn Dummy` cannot be sent between threads safely LL | assert_send::>(); | ^^^^^^^^^^^^^^ `dyn Dummy` cannot be sent between threads safely | - = help: the trait `Send` is not implemented for `dyn Dummy`, which is required by `Box: Send` + = help: the trait `Send` is not implemented for `dyn Dummy` = note: required for `Unique` to implement `Send` note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL diff --git a/tests/ui/kindck/kindck-send-owned.stderr b/tests/ui/kindck/kindck-send-owned.stderr index 4bc0212089b1..860a9391bbb0 100644 --- a/tests/ui/kindck/kindck-send-owned.stderr +++ b/tests/ui/kindck/kindck-send-owned.stderr @@ -4,7 +4,7 @@ error[E0277]: `*mut u8` cannot be sent between threads safely LL | assert_send::>(); | ^^^^^^^^^^^^ `*mut u8` cannot be sent between threads safely | - = help: the trait `Send` is not implemented for `*mut u8`, which is required by `Box<*mut u8>: Send` + = help: the trait `Send` is not implemented for `*mut u8` = note: required for `Unique<*mut u8>` to implement `Send` note: required because it appears within the type `Box<*mut u8>` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL diff --git a/tests/ui/modules/issue-107649.stderr b/tests/ui/modules/issue-107649.stderr index d5405c6576a8..0d203c1aacba 100644 --- a/tests/ui/modules/issue-107649.stderr +++ b/tests/ui/modules/issue-107649.stderr @@ -4,7 +4,7 @@ error[E0277]: `Dummy` doesn't implement `Debug` 105 | dbg!(lib::Dummy); | ^^^^^^^^^^^^^^^^ `Dummy` cannot be formatted using `{:?}` | - = help: the trait `Debug` is not implemented for `Dummy`, which is required by `&Dummy: Debug` + = help: the trait `Debug` is not implemented for `Dummy` = note: add `#[derive(Debug)]` to `Dummy` or manually `impl Debug for Dummy` = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Dummy` with `#[derive(Debug)]` diff --git a/tests/ui/mut/mutable-enum-indirect.stderr b/tests/ui/mut/mutable-enum-indirect.stderr index d7af327df5a3..0b7783b3318b 100644 --- a/tests/ui/mut/mutable-enum-indirect.stderr +++ b/tests/ui/mut/mutable-enum-indirect.stderr @@ -6,7 +6,7 @@ LL | bar(&x); | | | required by a bound introduced by this call | - = help: within `&Foo`, the trait `Sync` is not implemented for `NoSync`, which is required by `&Foo: Sync` + = help: within `&Foo`, the trait `Sync` is not implemented for `NoSync` note: required because it appears within the type `Foo` --> $DIR/mutable-enum-indirect.rs:11:6 | diff --git a/tests/ui/no-send-res-ports.stderr b/tests/ui/no-send-res-ports.stderr index c71d8ecba371..9c30261e5cb7 100644 --- a/tests/ui/no-send-res-ports.stderr +++ b/tests/ui/no-send-res-ports.stderr @@ -13,7 +13,7 @@ LL | | println!("{:?}", y); LL | | }); | |_____^ `Rc<()>` cannot be sent between threads safely | - = help: within `{closure@$DIR/no-send-res-ports.rs:25:19: 25:25}`, the trait `Send` is not implemented for `Rc<()>`, which is required by `{closure@$DIR/no-send-res-ports.rs:25:19: 25:25}: Send` + = help: within `{closure@$DIR/no-send-res-ports.rs:25:19: 25:25}`, the trait `Send` is not implemented for `Rc<()>` note: required because it appears within the type `Port<()>` --> $DIR/no-send-res-ports.rs:5:8 | diff --git a/tests/ui/no_send-enum.stderr b/tests/ui/no_send-enum.stderr index e24f79c7dd6a..3b66c7db545e 100644 --- a/tests/ui/no_send-enum.stderr +++ b/tests/ui/no_send-enum.stderr @@ -6,7 +6,7 @@ LL | bar(x); | | | required by a bound introduced by this call | - = help: within `Foo`, the trait `Send` is not implemented for `NoSend`, which is required by `Foo: Send` + = help: within `Foo`, the trait `Send` is not implemented for `NoSend` note: required because it appears within the type `Foo` --> $DIR/no_send-enum.rs:8:6 | diff --git a/tests/ui/no_share-enum.stderr b/tests/ui/no_share-enum.stderr index 5b6c8bf0b4fd..89939216d5b1 100644 --- a/tests/ui/no_share-enum.stderr +++ b/tests/ui/no_share-enum.stderr @@ -6,7 +6,7 @@ LL | bar(x); | | | required by a bound introduced by this call | - = help: within `Foo`, the trait `Sync` is not implemented for `NoSync`, which is required by `Foo: Sync` + = help: within `Foo`, the trait `Sync` is not implemented for `NoSync` note: required because it appears within the type `Foo` --> $DIR/no_share-enum.rs:8:6 | diff --git a/tests/ui/not-clone-closure.stderr b/tests/ui/not-clone-closure.stderr index 9b557b155829..783c165eeb21 100644 --- a/tests/ui/not-clone-closure.stderr +++ b/tests/ui/not-clone-closure.stderr @@ -5,7 +5,7 @@ LL | let hello = move || { | ------- within this `{closure@$DIR/not-clone-closure.rs:7:17: 7:24}` ... LL | let hello = hello.clone(); - | ^^^^^ within `{closure@$DIR/not-clone-closure.rs:7:17: 7:24}`, the trait `Clone` is not implemented for `S`, which is required by `{closure@$DIR/not-clone-closure.rs:7:17: 7:24}: Clone` + | ^^^^^ within `{closure@$DIR/not-clone-closure.rs:7:17: 7:24}`, the trait `Clone` is not implemented for `S` | note: required because it's used within this closure --> $DIR/not-clone-closure.rs:7:17 diff --git a/tests/ui/not-panic/not-panic-safe-2.stderr b/tests/ui/not-panic/not-panic-safe-2.stderr index 8c4cf9c98ed6..0c399f15a25b 100644 --- a/tests/ui/not-panic/not-panic-safe-2.stderr +++ b/tests/ui/not-panic/not-panic-safe-2.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a r LL | assert::>>(); | ^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `Rc>: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `RefCell` --> $SRC_DIR/core/src/cell.rs:LL:COL = note: required for `Rc>` to implement `UnwindSafe` @@ -20,7 +20,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a LL | assert::>>(); | ^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `Rc>: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `Cell` --> $SRC_DIR/core/src/cell.rs:LL:COL note: required because it appears within the type `RefCell` diff --git a/tests/ui/not-panic/not-panic-safe-3.stderr b/tests/ui/not-panic/not-panic-safe-3.stderr index 2373ada63f66..53028d6a3371 100644 --- a/tests/ui/not-panic/not-panic-safe-3.stderr +++ b/tests/ui/not-panic/not-panic-safe-3.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a r LL | assert::>>(); | ^^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `Arc>: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `RefCell` --> $SRC_DIR/core/src/cell.rs:LL:COL = note: required for `Arc>` to implement `UnwindSafe` @@ -20,7 +20,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a LL | assert::>>(); | ^^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `Arc>: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `Cell` --> $SRC_DIR/core/src/cell.rs:LL:COL note: required because it appears within the type `RefCell` diff --git a/tests/ui/not-panic/not-panic-safe-4.stderr b/tests/ui/not-panic/not-panic-safe-4.stderr index d77cac8f272d..b1361cfd87ef 100644 --- a/tests/ui/not-panic/not-panic-safe-4.stderr +++ b/tests/ui/not-panic/not-panic-safe-4.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a r LL | assert::<&RefCell>(); | ^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `&RefCell: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `RefCell` --> $SRC_DIR/core/src/cell.rs:LL:COL = note: required for `&RefCell` to implement `UnwindSafe` @@ -25,7 +25,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a LL | assert::<&RefCell>(); | ^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `&RefCell: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `Cell` --> $SRC_DIR/core/src/cell.rs:LL:COL note: required because it appears within the type `RefCell` diff --git a/tests/ui/not-panic/not-panic-safe-5.stderr b/tests/ui/not-panic/not-panic-safe-5.stderr index 0de9a2cc0cd9..fbbd81d6d4c5 100644 --- a/tests/ui/not-panic/not-panic-safe-5.stderr +++ b/tests/ui/not-panic/not-panic-safe-5.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a r LL | assert::<*const UnsafeCell>(); | ^^^^^^^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `*const UnsafeCell: UnwindSafe` + = help: the trait `RefUnwindSafe` is not implemented for `UnsafeCell` = note: required for `*const UnsafeCell` to implement `UnwindSafe` note: required by a bound in `assert` --> $DIR/not-panic-safe-5.rs:6:14 diff --git a/tests/ui/not-panic/not-panic-safe-6.stderr b/tests/ui/not-panic/not-panic-safe-6.stderr index 7714a577f8a2..47f28257409e 100644 --- a/tests/ui/not-panic/not-panic-safe-6.stderr +++ b/tests/ui/not-panic/not-panic-safe-6.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a r LL | assert::<*mut RefCell>(); | ^^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `*mut RefCell: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `RefCell` --> $SRC_DIR/core/src/cell.rs:LL:COL = note: required for `*mut RefCell` to implement `UnwindSafe` @@ -20,7 +20,7 @@ error[E0277]: the type `UnsafeCell` may contain interior mutability and a LL | assert::<*mut RefCell>(); | ^^^^^^^^^^^^^^^^^ `UnsafeCell` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | - = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell`, which is required by `*mut RefCell: UnwindSafe` + = help: within `RefCell`, the trait `RefUnwindSafe` is not implemented for `UnsafeCell` note: required because it appears within the type `Cell` --> $SRC_DIR/core/src/cell.rs:LL:COL note: required because it appears within the type `RefCell` diff --git a/tests/ui/offset-of/offset-of-dst-field.stderr b/tests/ui/offset-of/offset-of-dst-field.stderr index bcfe796897e0..714bf7a0266c 100644 --- a/tests/ui/offset-of/offset-of-dst-field.stderr +++ b/tests/ui/offset-of/offset-of-dst-field.stderr @@ -58,7 +58,7 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation LL | offset_of!(Delta, z); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `Alpha`, the trait `Sized` is not implemented for `[u8]`, which is required by `Alpha: Sized` + = help: within `Alpha`, the trait `Sized` is not implemented for `[u8]` note: required because it appears within the type `Alpha` --> $DIR/offset-of-dst-field.rs:5:8 | diff --git a/tests/ui/on-unimplemented/slice-index.stderr b/tests/ui/on-unimplemented/slice-index.stderr index 0f8d105abef1..d53ecb9db0cd 100644 --- a/tests/ui/on-unimplemented/slice-index.stderr +++ b/tests/ui/on-unimplemented/slice-index.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `[i32]` cannot be indexed by `i32` LL | x[1i32]; | ^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[i32]>` is not implemented for `i32`, which is required by `[i32]: Index<_>` + = help: the trait `SliceIndex<[i32]>` is not implemented for `i32` = help: the trait `SliceIndex<[i32]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `i32` = note: required for `[i32]` to implement `Index` @@ -15,7 +15,7 @@ error[E0277]: the type `[i32]` cannot be indexed by `RangeTo` LL | x[..1i32]; | ^^^^^^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[i32]>` is not implemented for `RangeTo`, which is required by `[i32]: Index<_>` + = help: the trait `SliceIndex<[i32]>` is not implemented for `RangeTo` = help: the following other types implement trait `SliceIndex`: `RangeTo` implements `SliceIndex<[T]>` `RangeTo` implements `SliceIndex` diff --git a/tests/ui/parser/struct-literal-in-for.stderr b/tests/ui/parser/struct-literal-in-for.stderr index d2ef2ad7b5ad..1c91eba68e39 100644 --- a/tests/ui/parser/struct-literal-in-for.stderr +++ b/tests/ui/parser/struct-literal-in-for.stderr @@ -23,7 +23,7 @@ LL | | x: 3 LL | | }.hi() { | |__________^ `bool` is not an iterator | - = help: the trait `Iterator` is not implemented for `bool`, which is required by `bool: IntoIterator` + = help: the trait `Iterator` is not implemented for `bool` = note: required for `bool` to implement `IntoIterator` error: aborting due to 2 previous errors diff --git a/tests/ui/range/range-1.stderr b/tests/ui/range/range-1.stderr index f98420557c62..f77601bc43cd 100644 --- a/tests/ui/range/range-1.stderr +++ b/tests/ui/range/range-1.stderr @@ -8,7 +8,7 @@ error[E0277]: the trait bound `bool: Step` is not satisfied --> $DIR/range-1.rs:9:14 | LL | for i in false..true {} - | ^^^^^^^^^^^ the trait `Step` is not implemented for `bool`, which is required by `std::ops::Range: IntoIterator` + | ^^^^^^^^^^^ the trait `Step` is not implemented for `bool` | = help: the following other types implement trait `Step`: Char diff --git a/tests/ui/recursion/recursive-requirements.stderr b/tests/ui/recursion/recursive-requirements.stderr index f5cbed0ce347..bb63f7cd0dce 100644 --- a/tests/ui/recursion/recursive-requirements.stderr +++ b/tests/ui/recursion/recursive-requirements.stderr @@ -4,7 +4,7 @@ error[E0277]: `*const Bar` cannot be shared between threads safely LL | let _: AssertSync = unimplemented!(); | ^^^^^^^^^^^^^^^ `*const Bar` cannot be shared between threads safely | - = help: within `Foo`, the trait `Sync` is not implemented for `*const Bar`, which is required by `Foo: Sync` + = help: within `Foo`, the trait `Sync` is not implemented for `*const Bar` note: required because it appears within the type `Foo` --> $DIR/recursive-requirements.rs:5:12 | @@ -22,7 +22,7 @@ error[E0277]: `*const Foo` cannot be shared between threads safely LL | let _: AssertSync = unimplemented!(); | ^^^^^^^^^^^^^^^ `*const Foo` cannot be shared between threads safely | - = help: within `Foo`, the trait `Sync` is not implemented for `*const Foo`, which is required by `Foo: Sync` + = help: within `Foo`, the trait `Sync` is not implemented for `*const Foo` note: required because it appears within the type `Bar` --> $DIR/recursive-requirements.rs:10:12 | diff --git a/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr b/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr index 4d23922892ea..0a703367d969 100644 --- a/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr +++ b/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr @@ -4,7 +4,7 @@ error[E0277]: the trait bound `f32: Termination` is not satisfied LL | #[test] | ------- in this procedural macro expansion LL | fn can_parse_zero_as_f32() -> Result { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Termination` is not implemented for `f32`, which is required by `Result: Termination` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Termination` is not implemented for `f32` | = note: required for `Result` to implement `Termination` note: required by a bound in `assert_test_result` diff --git a/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr b/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr index eb6abbf80451..7ec018a95cc7 100644 --- a/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr +++ b/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr @@ -4,7 +4,7 @@ error[E0277]: `NotDebug` doesn't implement `Debug` LL | let _: NotDebug = dbg!(NotDebug); | ^^^^^^^^^^^^^^ `NotDebug` cannot be formatted using `{:?}` | - = help: the trait `Debug` is not implemented for `NotDebug`, which is required by `&NotDebug: Debug` + = help: the trait `Debug` is not implemented for `NotDebug` = note: add `#[derive(Debug)]` to `NotDebug` or manually `impl Debug for NotDebug` = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `NotDebug` with `#[derive(Debug)]` diff --git a/tests/ui/specialization/min_specialization/issue-79224.stderr b/tests/ui/specialization/min_specialization/issue-79224.stderr index db88be88a812..268fc3a95916 100644 --- a/tests/ui/specialization/min_specialization/issue-79224.stderr +++ b/tests/ui/specialization/min_specialization/issue-79224.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `B: Clone` is not satisfied --> $DIR/issue-79224.rs:18:29 | LL | impl Display for Cow<'_, B> { - | ^^^^^^^^^^ the trait `Clone` is not implemented for `B`, which is required by `B: ToOwned` + | ^^^^^^^^^^ the trait `Clone` is not implemented for `B` | = note: required for `B` to implement `ToOwned` help: consider further restricting this bound @@ -14,7 +14,7 @@ error[E0277]: the trait bound `B: Clone` is not satisfied --> $DIR/issue-79224.rs:20:5 | LL | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `B`, which is required by `B: ToOwned` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `B` | = note: required for `B` to implement `ToOwned` help: consider further restricting this bound @@ -26,7 +26,7 @@ error[E0277]: the trait bound `B: Clone` is not satisfied --> $DIR/issue-79224.rs:20:13 | LL | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - | ^^^^ the trait `Clone` is not implemented for `B`, which is required by `B: ToOwned` + | ^^^^ the trait `Clone` is not implemented for `B` | = note: required for `B` to implement `ToOwned` help: consider further restricting this bound @@ -44,7 +44,7 @@ LL | | LL | | LL | | write!(f, "foo") LL | | } - | |_____^ the trait `Clone` is not implemented for `B`, which is required by `B: ToOwned` + | |_____^ the trait `Clone` is not implemented for `B` | = note: required for `B` to implement `ToOwned` help: consider further restricting this bound diff --git a/tests/ui/statics/unsized_type2.stderr b/tests/ui/statics/unsized_type2.stderr index 4e47b37afdca..b18a99fab72c 100644 --- a/tests/ui/statics/unsized_type2.stderr +++ b/tests/ui/statics/unsized_type2.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t LL | pub static WITH_ERROR: Foo = Foo { version: 0 }; | ^^^ doesn't have a size known at compile-time | - = help: within `Foo`, the trait `Sized` is not implemented for `str`, which is required by `Foo: Sized` + = help: within `Foo`, the trait `Sized` is not implemented for `str` note: required because it appears within the type `Foo` --> $DIR/unsized_type2.rs:5:12 | @@ -17,7 +17,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t LL | pub static WITH_ERROR: Foo = Foo { version: 0 }; | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `Foo`, the trait `Sized` is not implemented for `str`, which is required by `Foo: Sized` + = help: within `Foo`, the trait `Sized` is not implemented for `str` note: required because it appears within the type `Foo` --> $DIR/unsized_type2.rs:5:12 | diff --git a/tests/ui/statics/unsizing-wfcheck-issue-127299.stderr b/tests/ui/statics/unsizing-wfcheck-issue-127299.stderr index 59e09e48523d..35dd570e91fb 100644 --- a/tests/ui/statics/unsizing-wfcheck-issue-127299.stderr +++ b/tests/ui/statics/unsizing-wfcheck-issue-127299.stderr @@ -26,7 +26,7 @@ error[E0277]: `(dyn Qux + 'static)` cannot be shared between threads safely LL | static FOO: &Lint = &Lint { desc: "desc" }; | ^^^^^ `(dyn Qux + 'static)` cannot be shared between threads safely | - = help: within `&'static Lint`, the trait `Sync` is not implemented for `(dyn Qux + 'static)`, which is required by `&'static Lint: Sync` + = help: within `&'static Lint`, the trait `Sync` is not implemented for `(dyn Qux + 'static)` = note: required because it appears within the type `&'static (dyn Qux + 'static)` note: required because it appears within the type `Lint` --> $DIR/unsizing-wfcheck-issue-127299.rs:7:12 diff --git a/tests/ui/str/str-idx.stderr b/tests/ui/str/str-idx.stderr index 84806cbea0de..e8bbb8058faf 100644 --- a/tests/ui/str/str-idx.stderr +++ b/tests/ui/str/str-idx.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `str` cannot be indexed by `{integer}` LL | let _: u8 = s[4]; | ^ string indices are ranges of `usize` | - = help: the trait `SliceIndex` is not implemented for `{integer}`, which is required by `str: Index<_>` + = help: the trait `SliceIndex` is not implemented for `{integer}` = note: you can use `.chars().nth()` or `.bytes().nth()` for more information, see chapter 8 in The Book: = help: the trait `SliceIndex<[_]>` is implemented for `usize` @@ -49,7 +49,7 @@ error[E0277]: the type `str` cannot be indexed by `char` LL | let _: u8 = s['c']; | ^^^ string indices are ranges of `usize` | - = help: the trait `SliceIndex` is not implemented for `char`, which is required by `str: Index<_>` + = help: the trait `SliceIndex` is not implemented for `char` = note: required for `str` to implement `Index` error: aborting due to 4 previous errors diff --git a/tests/ui/str/str-mut-idx.stderr b/tests/ui/str/str-mut-idx.stderr index 679f783126ff..9390d689252f 100644 --- a/tests/ui/str/str-mut-idx.stderr +++ b/tests/ui/str/str-mut-idx.stderr @@ -30,7 +30,7 @@ error[E0277]: the type `str` cannot be indexed by `usize` LL | s[1usize] = bot(); | ^^^^^^ string indices are ranges of `usize` | - = help: the trait `SliceIndex` is not implemented for `usize`, which is required by `str: Index<_>` + = help: the trait `SliceIndex` is not implemented for `usize` = help: the trait `SliceIndex<[_]>` is implemented for `usize` = help: for that trait implementation, expected `[_]`, found `str` = note: required for `str` to implement `Index` @@ -73,7 +73,7 @@ error[E0277]: the type `str` cannot be indexed by `char` LL | s['c']; | ^^^ string indices are ranges of `usize` | - = help: the trait `SliceIndex` is not implemented for `char`, which is required by `str: Index<_>` + = help: the trait `SliceIndex` is not implemented for `char` = note: required for `str` to implement `Index` error: aborting due to 6 previous errors diff --git a/tests/ui/suggestions/derive-clone-for-eq.stderr b/tests/ui/suggestions/derive-clone-for-eq.stderr index 6fae6e1316df..680890e880ca 100644 --- a/tests/ui/suggestions/derive-clone-for-eq.stderr +++ b/tests/ui/suggestions/derive-clone-for-eq.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `T: Clone` is not satisfied --> $DIR/derive-clone-for-eq.rs:4:17 | LL | #[derive(Clone, Eq)] - | ^^ the trait `Clone` is not implemented for `T`, which is required by `Struct: PartialEq` + | ^^ the trait `Clone` is not implemented for `T` | note: required for `Struct` to implement `PartialEq` --> $DIR/derive-clone-for-eq.rs:7:19 diff --git a/tests/ui/suggestions/derive-macro-missing-bounds.stderr b/tests/ui/suggestions/derive-macro-missing-bounds.stderr index 5da85a9d0619..bffcb1af487e 100644 --- a/tests/ui/suggestions/derive-macro-missing-bounds.stderr +++ b/tests/ui/suggestions/derive-macro-missing-bounds.stderr @@ -6,7 +6,7 @@ LL | #[derive(Debug)] LL | struct Outer(Inner); | ^^^^^^^^ `a::Inner` cannot be formatted using `{:?}` | - = help: the trait `Debug` is not implemented for `a::Inner`, which is required by `&a::Inner: Debug` + = help: the trait `Debug` is not implemented for `a::Inner` = note: add `#[derive(Debug)]` to `a::Inner` or manually `impl Debug for a::Inner` = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `a::Inner` with `#[derive(Debug)]` @@ -25,7 +25,7 @@ error[E0277]: the trait bound `T: c::Trait` is not satisfied LL | #[derive(Debug)] | ----- in this derive macro expansion LL | struct Outer(Inner); - | ^^^^^^^^ the trait `c::Trait` is not implemented for `T`, which is required by `&c::Inner: Debug` + | ^^^^^^^^ the trait `c::Trait` is not implemented for `T` | note: required for `c::Inner` to implement `Debug` --> $DIR/derive-macro-missing-bounds.rs:34:28 @@ -49,7 +49,7 @@ error[E0277]: the trait bound `T: d::Trait` is not satisfied LL | #[derive(Debug)] | ----- in this derive macro expansion LL | struct Outer(Inner); - | ^^^^^^^^ the trait `d::Trait` is not implemented for `T`, which is required by `&d::Inner: Debug` + | ^^^^^^^^ the trait `d::Trait` is not implemented for `T` | note: required for `d::Inner` to implement `Debug` --> $DIR/derive-macro-missing-bounds.rs:49:13 @@ -71,7 +71,7 @@ error[E0277]: the trait bound `T: e::Trait` is not satisfied LL | #[derive(Debug)] | ----- in this derive macro expansion LL | struct Outer(Inner); - | ^^^^^^^^ the trait `e::Trait` is not implemented for `T`, which is required by `&e::Inner: Debug` + | ^^^^^^^^ the trait `e::Trait` is not implemented for `T` | note: required for `e::Inner` to implement `Debug` --> $DIR/derive-macro-missing-bounds.rs:64:13 @@ -93,7 +93,7 @@ error[E0277]: the trait bound `T: f::Trait` is not satisfied LL | #[derive(Debug)] | ----- in this derive macro expansion LL | struct Outer(Inner); - | ^^^^^^^^ the trait `f::Trait` is not implemented for `T`, which is required by `&f::Inner: Debug` + | ^^^^^^^^ the trait `f::Trait` is not implemented for `T` | note: required for `f::Inner` to implement `Debug` --> $DIR/derive-macro-missing-bounds.rs:79:20 diff --git a/tests/ui/suggestions/into-str.stderr b/tests/ui/suggestions/into-str.stderr index ac6e531fee2b..d02d31860829 100644 --- a/tests/ui/suggestions/into-str.stderr +++ b/tests/ui/suggestions/into-str.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `&str: From` is not satisfied --> $DIR/into-str.rs:4:9 | LL | foo(String::new()); - | --- ^^^^^^^^^^^^^ the trait `From` is not implemented for `&str`, which is required by `String: Into<&str>` + | --- ^^^^^^^^^^^^^ the trait `From` is not implemented for `&str` | | | required by a bound introduced by this call | diff --git a/tests/ui/suggestions/issue-71394-no-from-impl.stderr b/tests/ui/suggestions/issue-71394-no-from-impl.stderr index 79f5dcf4b730..31f8f1d455ab 100644 --- a/tests/ui/suggestions/issue-71394-no-from-impl.stderr +++ b/tests/ui/suggestions/issue-71394-no-from-impl.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `&[i8]: From<&[u8]>` is not satisfied --> $DIR/issue-71394-no-from-impl.rs:8:25 | LL | let _: &[i8] = data.into(); - | ^^^^ the trait `From<&[u8]>` is not implemented for `&[i8]`, which is required by `&[u8]: Into<_>` + | ^^^^ the trait `From<&[u8]>` is not implemented for `&[i8]` | = help: the following other types implement trait `From`: `[T; 10]` implements `From<(T, T, T, T, T, T, T, T, T, T)>` diff --git a/tests/ui/suggestions/issue-88696.stderr b/tests/ui/suggestions/issue-88696.stderr index a8bc970e055b..b4f0793c225f 100644 --- a/tests/ui/suggestions/issue-88696.stderr +++ b/tests/ui/suggestions/issue-88696.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Result: From>` is not --> $DIR/issue-88696.rs:9:9 | LL | a().into() - | ^^^^ the trait `From>` is not implemented for `Result`, which is required by `Result: Into<_>` + | ^^^^ the trait `From>` is not implemented for `Result` | = note: required for `Result` to implement `Into>` diff --git a/tests/ui/suggestions/issue-96223.stderr b/tests/ui/suggestions/issue-96223.stderr index 4a77b240f3e5..a54a4e7b3be4 100644 --- a/tests/ui/suggestions/issue-96223.stderr +++ b/tests/ui/suggestions/issue-96223.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `for<'de> EmptyBis<'de>: Foo<'_>` is not satisfied --> $DIR/issue-96223.rs:49:17 | LL | icey_bounds(&p); - | ----------- ^^ the trait `for<'de> Foo<'_>` is not implemented for `EmptyBis<'de>`, which is required by `Empty: Dummy` + | ----------- ^^ the trait `for<'de> Foo<'_>` is not implemented for `EmptyBis<'de>` | | | required by a bound introduced by this call | diff --git a/tests/ui/suggestions/issue-96555.stderr b/tests/ui/suggestions/issue-96555.stderr index f77681ae80fa..1a1e069f09eb 100644 --- a/tests/ui/suggestions/issue-96555.stderr +++ b/tests/ui/suggestions/issue-96555.stderr @@ -6,7 +6,7 @@ LL | m::f1().await; | | | this call returns `()` | - = help: the trait `Future` is not implemented for `()`, which is required by `(): IntoFuture` + = help: the trait `Future` is not implemented for `()` = note: () must be a future or must implement `IntoFuture` to be awaited = note: required for `()` to implement `IntoFuture` help: remove the `.await` @@ -27,7 +27,7 @@ LL | m::f2().await; | | | this call returns `()` | - = help: the trait `Future` is not implemented for `()`, which is required by `(): IntoFuture` + = help: the trait `Future` is not implemented for `()` = note: () must be a future or must implement `IntoFuture` to be awaited = note: required for `()` to implement `IntoFuture` help: remove the `.await` @@ -48,7 +48,7 @@ LL | m::f3().await; | | | this call returns `()` | - = help: the trait `Future` is not implemented for `()`, which is required by `(): IntoFuture` + = help: the trait `Future` is not implemented for `()` = note: () must be a future or must implement `IntoFuture` to be awaited = note: required for `()` to implement `IntoFuture` help: remove the `.await` diff --git a/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr b/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr index db16fff826fa..d65ad109241a 100644 --- a/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr +++ b/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr @@ -21,7 +21,7 @@ LL | #[derive(Debug, Copy, Clone)] | ----- in this derive macro expansion LL | pub struct AABB { LL | pub loc: Vector2, - | ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K`, which is required by `Vector2: Debug` + | ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K` | note: required for `Vector2` to implement `Debug` --> $DIR/missing-bound-in-derive-copy-impl-2.rs:4:10 @@ -64,7 +64,7 @@ LL | #[derive(Debug, Copy, Clone)] | ----- in this derive macro expansion ... LL | pub size: Vector2, - | ^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K`, which is required by `Vector2: Clone` + | ^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K` | note: required for `Vector2` to implement `Clone` --> $DIR/missing-bound-in-derive-copy-impl-2.rs:4:23 diff --git a/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr b/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr index cf383b5c8ff0..316c2fa0fc96 100644 --- a/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr +++ b/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr @@ -57,7 +57,7 @@ LL | #[derive(Debug, Copy, Clone)] | ----- in this derive macro expansion LL | pub struct AABB { LL | pub loc: Vector2, - | ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K`, which is required by `Vector2: Debug` + | ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K` | note: required for `Vector2` to implement `Debug` --> $DIR/missing-bound-in-derive-copy-impl.rs:3:10 @@ -130,7 +130,7 @@ LL | #[derive(Debug, Copy, Clone)] | ----- in this derive macro expansion ... LL | pub size: Vector2, - | ^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K`, which is required by `Vector2: Clone` + | ^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `K` | note: required for `Vector2` to implement `Clone` --> $DIR/missing-bound-in-derive-copy-impl.rs:3:23 diff --git a/tests/ui/suggestions/path-by-value.stderr b/tests/ui/suggestions/path-by-value.stderr index 62feafe534d4..d870e21043c7 100644 --- a/tests/ui/suggestions/path-by-value.stderr +++ b/tests/ui/suggestions/path-by-value.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation LL | fn f(p: Path) { } | ^^^^ doesn't have a size known at compile-time | - = help: within `Path`, the trait `Sized` is not implemented for `[u8]`, which is required by `Path: Sized` + = help: within `Path`, the trait `Sized` is not implemented for `[u8]` note: required because it appears within the type `Path` --> $SRC_DIR/std/src/path.rs:LL:COL = help: unsized fn params are gated as an unstable feature diff --git a/tests/ui/suggestions/path-display.stderr b/tests/ui/suggestions/path-display.stderr index f9159c450301..46d0b35825bc 100644 --- a/tests/ui/suggestions/path-display.stderr +++ b/tests/ui/suggestions/path-display.stderr @@ -4,7 +4,7 @@ error[E0277]: `Path` doesn't implement `std::fmt::Display` LL | println!("{}", path); | ^^^^ `Path` cannot be formatted with the default formatter; call `.display()` on it | - = help: the trait `std::fmt::Display` is not implemented for `Path`, which is required by `&Path: std::fmt::Display` + = help: the trait `std::fmt::Display` is not implemented for `Path` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead = note: call `.display()` or `.to_string_lossy()` to safely print paths, as they may contain non-Unicode data = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/suggestions/suggest-dereferencing-index.stderr b/tests/ui/suggestions/suggest-dereferencing-index.stderr index 86487cdcc444..2316acbe9da2 100644 --- a/tests/ui/suggestions/suggest-dereferencing-index.stderr +++ b/tests/ui/suggestions/suggest-dereferencing-index.stderr @@ -4,7 +4,7 @@ error[E0277]: the type `[{integer}]` cannot be indexed by `&usize` LL | let one_item_please: i32 = [1, 2, 3][i]; | ^ slice indices are of type `usize` or ranges of `usize` | - = help: the trait `SliceIndex<[{integer}]>` is not implemented for `&usize`, which is required by `[{integer}; 3]: Index<_>` + = help: the trait `SliceIndex<[{integer}]>` is not implemented for `&usize` = help: the trait `SliceIndex<[{integer}]>` is implemented for `usize` = help: for that trait implementation, expected `usize`, found `&usize` = note: required for `[{integer}]` to implement `Index<&usize>` diff --git a/tests/ui/suggestions/suggest-pin-macro.stderr b/tests/ui/suggestions/suggest-pin-macro.stderr index 68f4099a976d..a761a454ad5a 100644 --- a/tests/ui/suggestions/suggest-pin-macro.stderr +++ b/tests/ui/suggestions/suggest-pin-macro.stderr @@ -2,7 +2,7 @@ error[E0277]: `PhantomPinned` cannot be unpinned --> $DIR/suggest-pin-macro.rs:22:17 | LL | dummy(test1.get_mut()); - | ^^^^^^^ within `Test`, the trait `Unpin` is not implemented for `PhantomPinned`, which is required by `Test: Unpin` + | ^^^^^^^ within `Test`, the trait `Unpin` is not implemented for `PhantomPinned` | = note: consider using the `pin!` macro consider using `Box::pin` if you need to access the pinned value outside of the current scope diff --git a/tests/ui/suggestions/suggest-remove-refs-1.stderr b/tests/ui/suggestions/suggest-remove-refs-1.stderr index 171184bf77d3..523f78dffcc6 100644 --- a/tests/ui/suggestions/suggest-remove-refs-1.stderr +++ b/tests/ui/suggestions/suggest-remove-refs-1.stderr @@ -4,7 +4,7 @@ error[E0277]: `&Enumerate>` is not an iterator LL | for (i, _) in &v.iter().enumerate() { | ^^^^^^^^^^^^^^^^^^^^^ `&Enumerate>` is not an iterator | - = help: the trait `Iterator` is not implemented for `&Enumerate>`, which is required by `&Enumerate>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&Enumerate>` = note: required for `&Enumerate>` to implement `IntoIterator` help: consider removing the leading `&`-reference | diff --git a/tests/ui/suggestions/suggest-remove-refs-2.stderr b/tests/ui/suggestions/suggest-remove-refs-2.stderr index 4e1994523dc2..bbe3261e1486 100644 --- a/tests/ui/suggestions/suggest-remove-refs-2.stderr +++ b/tests/ui/suggestions/suggest-remove-refs-2.stderr @@ -4,7 +4,7 @@ error[E0277]: `&&&&&Enumerate>` is not an iterat LL | for (i, _) in & & & & &v.iter().enumerate() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&&&&&Enumerate>` is not an iterator | - = help: the trait `Iterator` is not implemented for `&&&&&Enumerate>`, which is required by `&&&&&Enumerate>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&&&&&Enumerate>` = note: required for `&&&&&Enumerate>` to implement `IntoIterator` help: consider removing 5 leading `&`-references | diff --git a/tests/ui/suggestions/suggest-remove-refs-3.stderr b/tests/ui/suggestions/suggest-remove-refs-3.stderr index 1d180f9d8be2..a3e142563ff8 100644 --- a/tests/ui/suggestions/suggest-remove-refs-3.stderr +++ b/tests/ui/suggestions/suggest-remove-refs-3.stderr @@ -8,7 +8,7 @@ LL | | .iter() LL | | .enumerate() { | |____________________^ `&&&&&Enumerate>` is not an iterator | - = help: the trait `Iterator` is not implemented for `&&&&&Enumerate>`, which is required by `&&&&&Enumerate>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&&&&&Enumerate>` = note: required for `&&&&&Enumerate>` to implement `IntoIterator` help: consider removing 5 leading `&`-references | diff --git a/tests/ui/suggestions/suggest-remove-refs-4.stderr b/tests/ui/suggestions/suggest-remove-refs-4.stderr index 7ab34c4af511..ed9fc2dd2568 100644 --- a/tests/ui/suggestions/suggest-remove-refs-4.stderr +++ b/tests/ui/suggestions/suggest-remove-refs-4.stderr @@ -4,7 +4,7 @@ error[E0277]: `&&std::slice::Iter<'_, {integer}>` is not an iterator LL | for _i in &foo {} | ^^^^ `&&std::slice::Iter<'_, {integer}>` is not an iterator | - = help: the trait `Iterator` is not implemented for `&&std::slice::Iter<'_, {integer}>`, which is required by `&&std::slice::Iter<'_, {integer}>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&&std::slice::Iter<'_, {integer}>` = note: required for `&&std::slice::Iter<'_, {integer}>` to implement `IntoIterator` help: consider removing 2 leading `&`-references | diff --git a/tests/ui/suggestions/suggest-remove-refs-5.stderr b/tests/ui/suggestions/suggest-remove-refs-5.stderr index b132c56473ee..ae83012c70e5 100644 --- a/tests/ui/suggestions/suggest-remove-refs-5.stderr +++ b/tests/ui/suggestions/suggest-remove-refs-5.stderr @@ -4,7 +4,7 @@ error[E0277]: `&mut &mut &mut &mut Vec` is not an iterator LL | for _ in &mut &mut v {} | ^^^^^^^^^^^ `&mut &mut &mut &mut Vec` is not an iterator | - = help: the trait `Iterator` is not implemented for `Vec`, which is required by `&mut &mut &mut &mut Vec: IntoIterator` + = help: the trait `Iterator` is not implemented for `Vec` = note: required for `&mut Vec` to implement `Iterator` = note: 3 redundant requirements hidden = note: required for `&mut &mut &mut &mut Vec` to implement `Iterator` @@ -21,7 +21,7 @@ error[E0277]: `&mut &mut &mut [u8; 1]` is not an iterator LL | for _ in &mut v {} | ^^^^^^ `&mut &mut &mut [u8; 1]` is not an iterator | - = help: the trait `Iterator` is not implemented for `[u8; 1]`, which is required by `&mut &mut &mut [u8; 1]: IntoIterator` + = help: the trait `Iterator` is not implemented for `[u8; 1]` = note: required for `&mut [u8; 1]` to implement `Iterator` = note: 2 redundant requirements hidden = note: required for `&mut &mut &mut [u8; 1]` to implement `Iterator` diff --git a/tests/ui/sync/mutexguard-sync.stderr b/tests/ui/sync/mutexguard-sync.stderr index 6b686741d1f8..1501a793d5e8 100644 --- a/tests/ui/sync/mutexguard-sync.stderr +++ b/tests/ui/sync/mutexguard-sync.stderr @@ -6,7 +6,7 @@ LL | test_sync(guard); | | | required by a bound introduced by this call | - = help: the trait `Sync` is not implemented for `Cell`, which is required by `MutexGuard<'_, Cell>: Sync` + = help: the trait `Sync` is not implemented for `Cell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `MutexGuard<'_, Cell>` to implement `Sync` note: required by a bound in `test_sync` diff --git a/tests/ui/sync/reentrantlockguard-sync.stderr b/tests/ui/sync/reentrantlockguard-sync.stderr index ed2e3e2f1124..6bedf8f9f2e0 100644 --- a/tests/ui/sync/reentrantlockguard-sync.stderr +++ b/tests/ui/sync/reentrantlockguard-sync.stderr @@ -6,7 +6,7 @@ LL | test_sync(guard); | | | required by a bound introduced by this call | - = help: the trait `Sync` is not implemented for `Cell`, which is required by `ReentrantLockGuard<'_, Cell>: Sync` + = help: the trait `Sync` is not implemented for `Cell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead = note: required for `ReentrantLockGuard<'_, Cell>` to implement `Sync` note: required by a bound in `test_sync` diff --git a/tests/ui/trait-bounds/super-assoc-mismatch.stderr b/tests/ui/trait-bounds/super-assoc-mismatch.stderr index f2c5eb47e598..780535283a3a 100644 --- a/tests/ui/trait-bounds/super-assoc-mismatch.stderr +++ b/tests/ui/trait-bounds/super-assoc-mismatch.stderr @@ -53,7 +53,7 @@ error[E0277]: the trait bound `(): Sub` is not satisfied --> $DIR/super-assoc-mismatch.rs:29:21 | LL | type Assoc = (); - | ^^ the trait `Sub` is not implemented for `()`, which is required by `::Assoc: Sub` + | ^^ the trait `Sub` is not implemented for `()` | help: this trait has no implementations, consider adding one --> $DIR/super-assoc-mismatch.rs:7:1 @@ -87,7 +87,7 @@ error[E0277]: the trait bound `(): SubGeneric` is not satisfied --> $DIR/super-assoc-mismatch.rs:55:22 | LL | type Assoc1 = (); - | ^^ the trait `SubGeneric` is not implemented for `()`, which is required by `::Assoc1<()>: SubGeneric<::Assoc2>` + | ^^ the trait `SubGeneric` is not implemented for `()` | help: this trait has no implementations, consider adding one --> $DIR/super-assoc-mismatch.rs:43:1 diff --git a/tests/ui/traits/alias/cross-crate.stderr b/tests/ui/traits/alias/cross-crate.stderr index 52eb7e44f44f..8ed05b4758d8 100644 --- a/tests/ui/traits/alias/cross-crate.stderr +++ b/tests/ui/traits/alias/cross-crate.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Rc: SendSync` is not satisfied --> $DIR/cross-crate.rs:14:17 | LL | use_alias::>(); - | ^^^^^^^ the trait `Send` is not implemented for `Rc`, which is required by `Rc: SendSync` + | ^^^^^^^ the trait `Send` is not implemented for `Rc` | = note: required for `Rc` to implement `SendSync` note: required by a bound in `use_alias` @@ -15,7 +15,7 @@ error[E0277]: the trait bound `Rc: SendSync` is not satisfied --> $DIR/cross-crate.rs:14:17 | LL | use_alias::>(); - | ^^^^^^^ the trait `Sync` is not implemented for `Rc`, which is required by `Rc: SendSync` + | ^^^^^^^ the trait `Sync` is not implemented for `Rc` | = note: required for `Rc` to implement `SendSync` note: required by a bound in `use_alias` diff --git a/tests/ui/traits/alias/issue-108072-unmet-trait-alias-bound.stderr b/tests/ui/traits/alias/issue-108072-unmet-trait-alias-bound.stderr index c73c2f680329..27e23adb92ae 100644 --- a/tests/ui/traits/alias/issue-108072-unmet-trait-alias-bound.stderr +++ b/tests/ui/traits/alias/issue-108072-unmet-trait-alias-bound.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `(): IteratorAlias` is not satisfied --> $DIR/issue-108072-unmet-trait-alias-bound.rs:10:7 | LL | f(()) - | - ^^ the trait `Iterator` is not implemented for `()`, which is required by `(): IteratorAlias` + | - ^^ the trait `Iterator` is not implemented for `()` | | | required by a bound introduced by this call | diff --git a/tests/ui/traits/bound/assoc-fn-bound-root-obligation.rs b/tests/ui/traits/bound/assoc-fn-bound-root-obligation.rs index dc2de5bb715b..667d283bea3e 100644 --- a/tests/ui/traits/bound/assoc-fn-bound-root-obligation.rs +++ b/tests/ui/traits/bound/assoc-fn-bound-root-obligation.rs @@ -2,7 +2,7 @@ fn strip_lf(s: &str) -> &str { s.strip_suffix(b'\n').unwrap_or(s) //~^ ERROR the trait bound `u8: Pattern` is not satisfied //~| NOTE required by a bound introduced by this call - //~| NOTE the trait `FnMut(char)` is not implemented for `u8`, which is required by `u8: Pattern` + //~| NOTE the trait `FnMut(char)` is not implemented for `u8` //~| HELP the following other types implement trait `Pattern`: //~| NOTE required for `u8` to implement `Pattern` //~| NOTE required by a bound in `core::str::::strip_suffix` diff --git a/tests/ui/traits/bound/assoc-fn-bound-root-obligation.stderr b/tests/ui/traits/bound/assoc-fn-bound-root-obligation.stderr index 8351d15fdf3b..1cd62d2cbdba 100644 --- a/tests/ui/traits/bound/assoc-fn-bound-root-obligation.stderr +++ b/tests/ui/traits/bound/assoc-fn-bound-root-obligation.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `u8: Pattern` is not satisfied --> $DIR/assoc-fn-bound-root-obligation.rs:2:20 | LL | s.strip_suffix(b'\n').unwrap_or(s) - | ------------ ^^^^^ the trait `FnMut(char)` is not implemented for `u8`, which is required by `u8: Pattern` + | ------------ ^^^^^ the trait `FnMut(char)` is not implemented for `u8` | | | required by a bound introduced by this call | diff --git a/tests/ui/traits/const-traits/effects/span-bug-issue-121418.stderr b/tests/ui/traits/const-traits/effects/span-bug-issue-121418.stderr index 313ba4fc9565..97663232fcf7 100644 --- a/tests/ui/traits/const-traits/effects/span-bug-issue-121418.stderr +++ b/tests/ui/traits/const-traits/effects/span-bug-issue-121418.stderr @@ -34,7 +34,7 @@ error[E0277]: the size for values of type `(dyn T + 'static)` cannot be known at LL | pub const fn new() -> std::sync::Mutex {} | ^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `Mutex<(dyn T + 'static)>`, the trait `Sized` is not implemented for `(dyn T + 'static)`, which is required by `Mutex<(dyn T + 'static)>: Sized` + = help: within `Mutex<(dyn T + 'static)>`, the trait `Sized` is not implemented for `(dyn T + 'static)` note: required because it appears within the type `Mutex<(dyn T + 'static)>` --> $SRC_DIR/std/src/sync/mutex.rs:LL:COL = note: the return type of a function must have a statically known size diff --git a/tests/ui/traits/copy-impl-cannot-normalize.stderr b/tests/ui/traits/copy-impl-cannot-normalize.stderr index a98bb47f54fc..3bdb8b70172c 100644 --- a/tests/ui/traits/copy-impl-cannot-normalize.stderr +++ b/tests/ui/traits/copy-impl-cannot-normalize.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `T: TraitFoo` is not satisfied --> $DIR/copy-impl-cannot-normalize.rs:22:18 | LL | impl Copy for Foo {} - | ^^^^^^ the trait `TraitFoo` is not implemented for `T`, which is required by `Foo: Clone` + | ^^^^^^ the trait `TraitFoo` is not implemented for `T` | note: required for `Foo` to implement `Clone` --> $DIR/copy-impl-cannot-normalize.rs:12:9 diff --git a/tests/ui/traits/dont-autoderef-ty-with-escaping-var.stderr b/tests/ui/traits/dont-autoderef-ty-with-escaping-var.stderr index fecb05cade75..a5d0e6ab0956 100644 --- a/tests/ui/traits/dont-autoderef-ty-with-escaping-var.stderr +++ b/tests/ui/traits/dont-autoderef-ty-with-escaping-var.stderr @@ -8,7 +8,7 @@ error[E0277]: the trait bound `for<'a> &'a mut Vec<&'a u32>: Foo<'static, i32>` --> $DIR/dont-autoderef-ty-with-escaping-var.rs:17:6 | LL | >::ref_foo(unknown); - | ^^^ the trait `for<'a> Foo<'static, i32>` is not implemented for `&'a mut Vec<&'a u32>`, which is required by `i32: RefFoo` + | ^^^ the trait `for<'a> Foo<'static, i32>` is not implemented for `&'a mut Vec<&'a u32>` | help: this trait has no implementations, consider adding one --> $DIR/dont-autoderef-ty-with-escaping-var.rs:3:1 diff --git a/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr b/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr index 17fced307ed1..07edc4ede761 100644 --- a/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr +++ b/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr @@ -10,7 +10,7 @@ error[E0277]: the trait bound `NoClone: Magic` is not satisfied --> $DIR/supertrait-auto-trait.rs:16:23 | LL | let (a, b) = copy(NoClone); - | ---- ^^^^^^^ the trait `Copy` is not implemented for `NoClone`, which is required by `NoClone: Magic` + | ---- ^^^^^^^ the trait `Copy` is not implemented for `NoClone` | | | required by a bound introduced by this call | diff --git a/tests/ui/traits/issue-43784-supertrait.stderr b/tests/ui/traits/issue-43784-supertrait.stderr index 4c565c3fa1db..2bf365745a6b 100644 --- a/tests/ui/traits/issue-43784-supertrait.stderr +++ b/tests/ui/traits/issue-43784-supertrait.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/issue-43784-supertrait.rs:8:22 | LL | impl Complete for T {} - | ^ the trait `Copy` is not implemented for `T`, which is required by `T: Partial` + | ^ the trait `Copy` is not implemented for `T` | note: required for `T` to implement `Partial` --> $DIR/issue-43784-supertrait.rs:1:11 diff --git a/tests/ui/traits/issue-7013.stderr b/tests/ui/traits/issue-7013.stderr index 5067c7d7dd7d..174936631728 100644 --- a/tests/ui/traits/issue-7013.stderr +++ b/tests/ui/traits/issue-7013.stderr @@ -4,7 +4,7 @@ error[E0277]: `Rc>` cannot be sent between threads safely LL | let a = A {v: Box::new(B{v: None}) as Box}; | ^^^^^^^^^^^^^^^^^^^^ `Rc>` cannot be sent between threads safely | - = help: within `B`, the trait `Send` is not implemented for `Rc>`, which is required by `B: Send` + = help: within `B`, the trait `Send` is not implemented for `Rc>` note: required because it appears within the type `Option>>` --> $SRC_DIR/core/src/option.rs:LL:COL note: required because it appears within the type `B` diff --git a/tests/ui/traits/issue-71036.stderr b/tests/ui/traits/issue-71036.stderr index 35d543eb0177..2452731f19f1 100644 --- a/tests/ui/traits/issue-71036.stderr +++ b/tests/ui/traits/issue-71036.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `&'a T: Unsize<&'a U>` is not satisfied --> $DIR/issue-71036.rs:11:1 | LL | impl<'a, T: ?Sized + Unsize, U: ?Sized> DispatchFromDyn> for Foo<'a, T> {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Unsize<&'a U>` is not implemented for `&'a T`, which is required by `&'a &'a T: DispatchFromDyn<&'a &'a U>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Unsize<&'a U>` is not implemented for `&'a T` | = note: all implementations of `Unsize` are provided automatically by the compiler, see for more information = note: required for `&'a &'a T` to implement `DispatchFromDyn<&'a &'a U>` diff --git a/tests/ui/traits/issue-71136.stderr b/tests/ui/traits/issue-71136.stderr index d37ad8ae34d0..2c03c6bf08ed 100644 --- a/tests/ui/traits/issue-71136.stderr +++ b/tests/ui/traits/issue-71136.stderr @@ -5,7 +5,7 @@ LL | #[derive(Clone)] | ----- in this derive macro expansion LL | struct FooHolster { LL | the_foos: Vec, - | ^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Foo`, which is required by `Vec: Clone` + | ^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Foo` | = note: required for `Vec` to implement `Clone` = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/traits/issue-91594.stderr b/tests/ui/traits/issue-91594.stderr index 726ee5b61461..13568179e81f 100644 --- a/tests/ui/traits/issue-91594.stderr +++ b/tests/ui/traits/issue-91594.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Foo: HasComponent<()>` is not satisfied --> $DIR/issue-91594.rs:10:19 | LL | impl HasComponent<>::Interface> for Foo {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HasComponent<()>` is not implemented for `Foo`, which is required by `Foo: Component` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HasComponent<()>` is not implemented for `Foo` | = help: the trait `HasComponent<>::Interface>` is implemented for `Foo` note: required for `Foo` to implement `Component` diff --git a/tests/ui/traits/issue-97576.stderr b/tests/ui/traits/issue-97576.stderr index bee254461f1b..2c6cfd83b957 100644 --- a/tests/ui/traits/issue-97576.stderr +++ b/tests/ui/traits/issue-97576.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `String: From` is not satisfied --> $DIR/issue-97576.rs:8:22 | LL | bar: bar.into(), - | ^^^^ the trait `From` is not implemented for `String`, which is required by `impl ToString: Into<_>` + | ^^^^ the trait `From` is not implemented for `String` | = note: required for `impl ToString` to implement `Into` diff --git a/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr b/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr index 2a3833beb26b..8f5b937e586a 100644 --- a/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr +++ b/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr @@ -49,7 +49,7 @@ LL | is_send((8, TestType)); | | | required by a bound introduced by this call | - = help: within `({integer}, dummy1c::TestType)`, the trait `Send` is not implemented for `dummy1c::TestType`, which is required by `({integer}, dummy1c::TestType): Send` + = help: within `({integer}, dummy1c::TestType)`, the trait `Send` is not implemented for `dummy1c::TestType` = note: required because it appears within the type `({integer}, dummy1c::TestType)` note: required by a bound in `is_send` --> $DIR/negated-auto-traits-error.rs:16:15 @@ -87,7 +87,7 @@ LL | is_send(Box::new(Outer2(TestType))); | | | required by a bound introduced by this call | - = help: within `Outer2`, the trait `Send` is not implemented for `dummy3::TestType`, which is required by `Box>: Send` + = help: within `Outer2`, the trait `Send` is not implemented for `dummy3::TestType` note: required because it appears within the type `Outer2` --> $DIR/negated-auto-traits-error.rs:12:8 | @@ -110,7 +110,7 @@ LL | is_sync(Outer2(TestType)); | | | required by a bound introduced by this call | - = help: the trait `Send` is not implemented for `main::TestType`, which is required by `Outer2: Sync` + = help: the trait `Send` is not implemented for `main::TestType` note: required for `Outer2` to implement `Sync` --> $DIR/negated-auto-traits-error.rs:14:22 | diff --git a/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr b/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr index c2029a5a1c86..55f52181ec95 100644 --- a/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr +++ b/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr @@ -4,7 +4,7 @@ error: future cannot be sent between threads safely LL | is_send(foo()); | ^^^^^ future returned by `foo` is not `Send` | - = help: the trait `Sync` is not implemented for `NotSync`, which is required by `impl Future: Send` + = help: the trait `Sync` is not implemented for `NotSync` note: future is not `Send` as this value is used across an await --> $DIR/auto-with-drop_tracking_mir.rs:16:11 | diff --git a/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr b/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr index b487ceef1d42..bb39d1107777 100644 --- a/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr +++ b/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t LL | foo:: str, _>(None, ()); | ^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `fn() -> str`, the trait `Sized` is not implemented for `str`, which is required by `fn() -> str: Fn<_>` + = help: within `fn() -> str`, the trait `Sized` is not implemented for `str` = note: required because it appears within the type `fn() -> str` note: required by a bound in `foo` --> $DIR/builtin-fn-must-return-sized.rs:10:11 diff --git a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.with.stderr b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.with.stderr index a81229e5e355..9114bcadac0c 100644 --- a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.with.stderr +++ b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.with.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `A: Trait<_, _, _>` is not satisfied --> $DIR/incompleteness-unstable-result.rs:65:19 | LL | impls_trait::, _, _, _>(); - | ^^^^ the trait `Trait<_, _, _>` is not implemented for `A`, which is required by `A: Trait<_, _, _>` + | ^^^^ the trait `Trait<_, _, _>` is not implemented for `A` | = help: the trait `Trait` is implemented for `A` note: required for `A` to implement `Trait<_, _, _>` diff --git a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.without.stderr b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.without.stderr index a81229e5e355..9114bcadac0c 100644 --- a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.without.stderr +++ b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.without.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `A: Trait<_, _, _>` is not satisfied --> $DIR/incompleteness-unstable-result.rs:65:19 | LL | impls_trait::, _, _, _>(); - | ^^^^ the trait `Trait<_, _, _>` is not implemented for `A`, which is required by `A: Trait<_, _, _>` + | ^^^^ the trait `Trait<_, _, _>` is not implemented for `A` | = help: the trait `Trait` is implemented for `A` note: required for `A` to implement `Trait<_, _, _>` diff --git a/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr b/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr index 9a18a58debd2..a841618ec6f5 100644 --- a/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr +++ b/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `(): Foo` is not satisfied --> $DIR/point-at-failing-nested.rs:22:17 | LL | needs_foo::<()>(); - | ^^ the trait `Bar` is not implemented for `()`, which is required by `(): Foo` + | ^^ the trait `Bar` is not implemented for `()` | help: this trait has no implementations, consider adding one --> $DIR/point-at-failing-nested.rs:4:1 diff --git a/tests/ui/traits/next-solver/diagnostics/where-clause-doesnt-apply.stderr b/tests/ui/traits/next-solver/diagnostics/where-clause-doesnt-apply.stderr index ab1d4a56c023..29703679a861 100644 --- a/tests/ui/traits/next-solver/diagnostics/where-clause-doesnt-apply.stderr +++ b/tests/ui/traits/next-solver/diagnostics/where-clause-doesnt-apply.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `(): Foo` is not satisfied --> $DIR/where-clause-doesnt-apply.rs:18:15 | LL | needs_foo(()); - | --------- ^^ the trait `Bar` is not implemented for `()`, which is required by `(): Foo` + | --------- ^^ the trait `Bar` is not implemented for `()` | | | required by a bound introduced by this call | diff --git a/tests/ui/traits/next-solver/dyn-incompatibility.stderr b/tests/ui/traits/next-solver/dyn-incompatibility.stderr index 7f2c0646ef50..a720797efc4b 100644 --- a/tests/ui/traits/next-solver/dyn-incompatibility.stderr +++ b/tests/ui/traits/next-solver/dyn-incompatibility.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied in `dyn Setup --> $DIR/dyn-incompatibility.rs:12:12 | LL | copy::>(t) - | ^^^^^^^^^^^^^^^^^ within `dyn Setup`, the trait `Copy` is not implemented for `T`, which is required by `dyn Setup: Setup` + | ^^^^^^^^^^^^^^^^^ within `dyn Setup`, the trait `Copy` is not implemented for `T` | = note: required because it appears within the type `dyn Setup` note: required by a bound in `copy` @@ -35,7 +35,7 @@ error[E0277]: the trait bound `T: Copy` is not satisfied in `dyn Setup --> $DIR/dyn-incompatibility.rs:12:5 | LL | copy::>(t) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ within `dyn Setup`, the trait `Copy` is not implemented for `T`, which is required by `dyn Setup: Setup` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ within `dyn Setup`, the trait `Copy` is not implemented for `T` | = note: required because it appears within the type `dyn Setup` help: consider restricting type parameter `T` diff --git a/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr b/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr index 65e7dd2ab34b..1f319cc6743b 100644 --- a/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr +++ b/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `T: Clone` is not satisfied --> $DIR/global-cache-and-parallel-frontend.rs:15:17 | LL | #[derive(Clone, Eq)] - | ^^ the trait `Clone` is not implemented for `T`, which is required by `Struct: PartialEq` + | ^^ the trait `Clone` is not implemented for `T` | note: required for `Struct` to implement `PartialEq` --> $DIR/global-cache-and-parallel-frontend.rs:18:19 diff --git a/tests/ui/traits/non_lifetime_binders/bad-sized-cond.stderr b/tests/ui/traits/non_lifetime_binders/bad-sized-cond.stderr index f7d5d6fcee4d..f4deb169516c 100644 --- a/tests/ui/traits/non_lifetime_binders/bad-sized-cond.stderr +++ b/tests/ui/traits/non_lifetime_binders/bad-sized-cond.stderr @@ -29,7 +29,7 @@ error[E0277]: `V` is not an iterator LL | bar(); | ^^^^^ `V` is not an iterator | - = help: the trait `Iterator` is not implemented for `V`, which is required by `V: IntoIterator` + = help: the trait `Iterator` is not implemented for `V` = note: required for `V` to implement `IntoIterator` note: required by a bound in `bar` --> $DIR/bad-sized-cond.rs:12:15 @@ -46,7 +46,7 @@ error[E0277]: the size for values of type `V` cannot be known at compilation tim LL | bar(); | ^^^^^ doesn't have a size known at compile-time | - = help: the trait `Sized` is not implemented for `V`, which is required by `V: IntoIterator` + = help: the trait `Sized` is not implemented for `V` = note: required for `V` to implement `IntoIterator` note: required by a bound in `bar` --> $DIR/bad-sized-cond.rs:12:15 diff --git a/tests/ui/traits/question-mark-result-err-mismatch.stderr b/tests/ui/traits/question-mark-result-err-mismatch.stderr index 0e0ae6d59901..bad325a67204 100644 --- a/tests/ui/traits/question-mark-result-err-mismatch.stderr +++ b/tests/ui/traits/question-mark-result-err-mismatch.stderr @@ -11,7 +11,7 @@ LL | | e; LL | | }) | |__________- this can't be annotated with `?` because it has type `Result<_, ()>` LL | .map(|()| "")?; - | ^ the trait `From<()>` is not implemented for `String`, which is required by `Result: FromResidual>` + | ^ the trait `From<()>` is not implemented for `String` | = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait = note: required for `Result` to implement `FromResidual>` @@ -25,7 +25,7 @@ LL | let x = foo(); | ----- this has type `Result<_, String>` ... LL | .map_err(|_| ())?; - | ---------------^ the trait `From<()>` is not implemented for `String`, which is required by `Result<(), String>: FromResidual>` + | ---------------^ the trait `From<()>` is not implemented for `String` | | | this can't be annotated with `?` because it has type `Result<_, ()>` | @@ -50,7 +50,7 @@ LL | .ok_or_else(|| { LL | | "Couldn't split the test string"; | | - help: remove this semicolon LL | | })?; - | | -^ the trait `From<()>` is not implemented for `String`, which is required by `Result: FromResidual>` + | | -^ the trait `From<()>` is not implemented for `String` | |__________| | this can't be annotated with `?` because it has type `Result<_, ()>` | diff --git a/tests/ui/traits/suggest-dereferences/dont-suggest-unsize-deref.stderr b/tests/ui/traits/suggest-dereferences/dont-suggest-unsize-deref.stderr index 28a0646a86bf..8024ad28d5ae 100644 --- a/tests/ui/traits/suggest-dereferences/dont-suggest-unsize-deref.stderr +++ b/tests/ui/traits/suggest-dereferences/dont-suggest-unsize-deref.stderr @@ -6,7 +6,7 @@ LL | use_iterator(i); | | | required by a bound introduced by this call | - = help: the trait `Iterator` is not implemented for `&dyn IntoIterator`, which is required by `&dyn IntoIterator: IntoIterator` + = help: the trait `Iterator` is not implemented for `&dyn IntoIterator` = note: required for `&dyn IntoIterator` to implement `IntoIterator` note: required by a bound in `use_iterator` --> $DIR/dont-suggest-unsize-deref.rs:3:8 diff --git a/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr b/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr index 85d6cdf779b4..f0957e5cd9f4 100644 --- a/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr +++ b/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr @@ -6,7 +6,7 @@ LL | for (src, dest) in std::iter::zip(fields.iter(), &variant.iter()) { | | | required by a bound introduced by this call | - = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>`, which is required by `&std::slice::Iter<'_, {integer}>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>` = note: required for `&std::slice::Iter<'_, {integer}>` to implement `IntoIterator` note: required by a bound in `std::iter::zip` --> $SRC_DIR/core/src/iter/adapters/zip.rs:LL:COL @@ -22,7 +22,7 @@ error[E0277]: `&std::slice::Iter<'_, {integer}>` is not an iterator LL | for (src, dest) in std::iter::zip(fields.iter(), &variant.iter()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&std::slice::Iter<'_, {integer}>` is not an iterator | - = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>`, which is required by `Zip, &std::slice::Iter<'_, {integer}>>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>` = help: the trait `Iterator` is implemented for `std::slice::Iter<'_, T>` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `Iterator` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `IntoIterator` @@ -35,7 +35,7 @@ LL | for (src, dest) in std::iter::zip(fields.iter(), &variant.iter().clone( | | | required by a bound introduced by this call | - = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>`, which is required by `&std::slice::Iter<'_, {integer}>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>` = note: required for `&std::slice::Iter<'_, {integer}>` to implement `IntoIterator` note: required by a bound in `std::iter::zip` --> $SRC_DIR/core/src/iter/adapters/zip.rs:LL:COL @@ -51,7 +51,7 @@ error[E0277]: `&std::slice::Iter<'_, {integer}>` is not an iterator LL | for (src, dest) in std::iter::zip(fields.iter(), &variant.iter().clone()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&std::slice::Iter<'_, {integer}>` is not an iterator | - = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>`, which is required by `Zip, &std::slice::Iter<'_, {integer}>>: IntoIterator` + = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>` = help: the trait `Iterator` is implemented for `std::slice::Iter<'_, T>` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `Iterator` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `IntoIterator` diff --git a/tests/ui/traits/suggest-dereferences/issue-39029.stderr b/tests/ui/traits/suggest-dereferences/issue-39029.stderr index 0eea6cbcc5a6..fd45fa3cf74d 100644 --- a/tests/ui/traits/suggest-dereferences/issue-39029.stderr +++ b/tests/ui/traits/suggest-dereferences/issue-39029.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `NoToSocketAddrs: ToSocketAddrs` is not satisfied --> $DIR/issue-39029.rs:16:38 | LL | let _errors = TcpListener::bind(&bad); - | ----------------- ^^^ the trait `ToSocketAddrs` is not implemented for `NoToSocketAddrs`, which is required by `&NoToSocketAddrs: ToSocketAddrs` + | ----------------- ^^^ the trait `ToSocketAddrs` is not implemented for `NoToSocketAddrs` | | | required by a bound introduced by this call | diff --git a/tests/ui/traits/suggest-dereferences/root-obligation.stderr b/tests/ui/traits/suggest-dereferences/root-obligation.stderr index 2f5e1c5b5377..dafd3469b6f0 100644 --- a/tests/ui/traits/suggest-dereferences/root-obligation.stderr +++ b/tests/ui/traits/suggest-dereferences/root-obligation.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `&char: Pattern` is not satisfied --> $DIR/root-obligation.rs:6:38 | LL | .filter(|c| "aeiou".contains(c)) - | -------- ^ the trait `Fn(char)` is not implemented for `char`, which is required by `&char: Pattern` + | -------- ^ the trait `Fn(char)` is not implemented for `char` | | | required by a bound introduced by this call | diff --git a/tests/ui/traits/suggest-dereferences/suggest-dereferencing-receiver-argument.stderr b/tests/ui/traits/suggest-dereferences/suggest-dereferencing-receiver-argument.stderr index d1d75625abaa..d6033bc6baa0 100644 --- a/tests/ui/traits/suggest-dereferences/suggest-dereferencing-receiver-argument.stderr +++ b/tests/ui/traits/suggest-dereferences/suggest-dereferencing-receiver-argument.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `TargetStruct: From<&{integer}>` is not satisfied --> $DIR/suggest-dereferencing-receiver-argument.rs:13:30 | LL | let _b: TargetStruct = a.into(); - | ^^^^ the trait `From<&{integer}>` is not implemented for `TargetStruct`, which is required by `&{integer}: Into<_>` + | ^^^^ the trait `From<&{integer}>` is not implemented for `TargetStruct` | = note: required for `&{integer}` to implement `Into` help: consider dereferencing here diff --git a/tests/ui/traits/unsend-future.stderr b/tests/ui/traits/unsend-future.stderr index 4462208cb495..25df34197947 100644 --- a/tests/ui/traits/unsend-future.stderr +++ b/tests/ui/traits/unsend-future.stderr @@ -4,7 +4,7 @@ error: future cannot be sent between threads safely LL | require_handler(handler) | ^^^^^^^ future returned by `handler` is not `Send` | - = help: within `impl Future`, the trait `Send` is not implemented for `*const i32`, which is required by `fn() -> impl Future {handler}: Handler` + = help: within `impl Future`, the trait `Send` is not implemented for `*const i32` note: future is not `Send` as this value is used across an await --> $DIR/unsend-future.rs:15:14 | diff --git a/tests/ui/try-block/try-block-bad-type.stderr b/tests/ui/try-block/try-block-bad-type.stderr index e9e6255cd2a3..d94962e40317 100644 --- a/tests/ui/try-block/try-block-bad-type.stderr +++ b/tests/ui/try-block/try-block-bad-type.stderr @@ -2,7 +2,7 @@ error[E0277]: `?` couldn't convert the error to `TryFromSliceError` --> $DIR/try-block-bad-type.rs:7:16 | LL | Err("")?; - | -------^ the trait `From<&str>` is not implemented for `TryFromSliceError`, which is required by `Result: FromResidual>` + | -------^ the trait `From<&str>` is not implemented for `TryFromSliceError` | | | this can't be annotated with `?` because it has type `Result<_, &str>` | diff --git a/tests/ui/try-trait/bad-interconversion.stderr b/tests/ui/try-trait/bad-interconversion.stderr index 82877baef3e3..fe28912ba007 100644 --- a/tests/ui/try-trait/bad-interconversion.stderr +++ b/tests/ui/try-trait/bad-interconversion.stderr @@ -4,7 +4,7 @@ error[E0277]: `?` couldn't convert the error to `u8` LL | fn result_to_result() -> Result { | --------------- expected `u8` because of this LL | Ok(Err(123_i32)?) - | ------------^ the trait `From` is not implemented for `u8`, which is required by `Result: FromResidual>` + | ------------^ the trait `From` is not implemented for `u8` | | | this can't be annotated with `?` because it has type `Result<_, i32>` | diff --git a/tests/ui/try-trait/issue-32709.stderr b/tests/ui/try-trait/issue-32709.stderr index 9b77f578437c..475bd1ff3ac5 100644 --- a/tests/ui/try-trait/issue-32709.stderr +++ b/tests/ui/try-trait/issue-32709.stderr @@ -4,7 +4,7 @@ error[E0277]: `?` couldn't convert the error to `()` LL | fn a() -> Result { | --------------- expected `()` because of this LL | Err(5)?; - | ------^ the trait `From<{integer}>` is not implemented for `()`, which is required by `Result: FromResidual>` + | ------^ the trait `From<{integer}>` is not implemented for `()` | | | this can't be annotated with `?` because it has type `Result<_, {integer}>` | diff --git a/tests/ui/type-alias-impl-trait/auto-trait-leakage2.stderr b/tests/ui/type-alias-impl-trait/auto-trait-leakage2.stderr index 5c5506fb8532..2ed918eca171 100644 --- a/tests/ui/type-alias-impl-trait/auto-trait-leakage2.stderr +++ b/tests/ui/type-alias-impl-trait/auto-trait-leakage2.stderr @@ -9,7 +9,7 @@ LL | is_send(m::foo()); | | | required by a bound introduced by this call | - = help: within `Foo`, the trait `Send` is not implemented for `Rc`, which is required by `Foo: Send` + = help: within `Foo`, the trait `Send` is not implemented for `Rc` note: required because it appears within the type `Foo` --> $DIR/auto-trait-leakage2.rs:7:16 | diff --git a/tests/ui/type-alias-impl-trait/multiple-def-uses-in-one-fn.stderr b/tests/ui/type-alias-impl-trait/multiple-def-uses-in-one-fn.stderr index a7840e0a5bf2..b5f38074632e 100644 --- a/tests/ui/type-alias-impl-trait/multiple-def-uses-in-one-fn.stderr +++ b/tests/ui/type-alias-impl-trait/multiple-def-uses-in-one-fn.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `&'static B: From<&A>` is not satisfied --> $DIR/multiple-def-uses-in-one-fn.rs:9:45 | LL | fn f(a: &'static A, b: B) -> (X, X) { - | ^^^^^^^^^^^^^^^^^^ the trait `From<&A>` is not implemented for `&'static B`, which is required by `&A: Into<&'static B>` + | ^^^^^^^^^^^^^^^^^^ the trait `From<&A>` is not implemented for `&'static B` | = note: required for `&A` to implement `Into<&'static B>` help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement diff --git a/tests/ui/type-alias-impl-trait/underconstrained_generic.stderr b/tests/ui/type-alias-impl-trait/underconstrained_generic.stderr index 913a35eb9fb0..e4de9245951c 100644 --- a/tests/ui/type-alias-impl-trait/underconstrained_generic.stderr +++ b/tests/ui/type-alias-impl-trait/underconstrained_generic.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `T: Trait` is not satisfied --> $DIR/underconstrained_generic.rs:22:5 | LL | () - | ^^ the trait `Trait` is not implemented for `T`, which is required by `(): ProofForConversion` + | ^^ the trait `Trait` is not implemented for `T` | note: required for `()` to implement `ProofForConversion` --> $DIR/underconstrained_generic.rs:13:16 diff --git a/tests/ui/type/issue-58355.stderr b/tests/ui/type/issue-58355.stderr index cd8e35388024..b6056f0fd65a 100644 --- a/tests/ui/type/issue-58355.stderr +++ b/tests/ui/type/issue-58355.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `dyn ToString` cannot be known at comp LL | x = Some(Box::new(callback)); | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `fn() -> dyn ToString`, the trait `Sized` is not implemented for `dyn ToString`, which is required by `fn() -> dyn ToString: Fn()` + = help: within `fn() -> dyn ToString`, the trait `Sized` is not implemented for `dyn ToString` = note: required because it appears within the type `fn() -> dyn ToString` = note: required for the cast from `Box dyn ToString>` to `Box (dyn ToString + 'static)>` diff --git a/tests/ui/typeck/bad-index-due-to-nested.stderr b/tests/ui/typeck/bad-index-due-to-nested.stderr index 137c7b063966..bd7fd0392c37 100644 --- a/tests/ui/typeck/bad-index-due-to-nested.stderr +++ b/tests/ui/typeck/bad-index-due-to-nested.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `K: Hash` is not satisfied --> $DIR/bad-index-due-to-nested.rs:20:5 | LL | map[k] - | ^^^ the trait `Hash` is not implemented for `K`, which is required by `HashMap<_, _>: Index<&_>` + | ^^^ the trait `Hash` is not implemented for `K` | note: required for `HashMap` to implement `Index<&K>` --> $DIR/bad-index-due-to-nested.rs:7:12 @@ -21,7 +21,7 @@ error[E0277]: the trait bound `V: Copy` is not satisfied --> $DIR/bad-index-due-to-nested.rs:20:5 | LL | map[k] - | ^^^ the trait `Copy` is not implemented for `V`, which is required by `HashMap<_, _>: Index<&_>` + | ^^^ the trait `Copy` is not implemented for `V` | note: required for `HashMap` to implement `Index<&K>` --> $DIR/bad-index-due-to-nested.rs:7:12 diff --git a/tests/ui/typeck/issue-90101.stderr b/tests/ui/typeck/issue-90101.stderr index 796e904a4382..2e140461c1d9 100644 --- a/tests/ui/typeck/issue-90101.stderr +++ b/tests/ui/typeck/issue-90101.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `PathBuf: From>` is not satisfied --> $DIR/issue-90101.rs:6:10 | LL | func(Path::new("hello").to_path_buf().to_string_lossy(), "world") - | ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `From>` is not implemented for `PathBuf`, which is required by `Cow<'_, str>: Into` + | ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `From>` is not implemented for `PathBuf` | | | required by a bound introduced by this call | diff --git a/tests/ui/typeck/suggest-similar-impls-for-root-obligation.stderr b/tests/ui/typeck/suggest-similar-impls-for-root-obligation.stderr index 8410574e3112..ab307aadec9f 100644 --- a/tests/ui/typeck/suggest-similar-impls-for-root-obligation.stderr +++ b/tests/ui/typeck/suggest-similar-impls-for-root-obligation.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `((),): Into` is not satisfied --> $DIR/suggest-similar-impls-for-root-obligation.rs:14:24 | LL | let _: Bar = ((),).into(); - | ^^^^ the trait `Foo<'_>` is not implemented for `((),)`, which is required by `((),): Into<_>` + | ^^^^ the trait `Foo<'_>` is not implemented for `((),)` | = help: the trait `Foo<'_>` is implemented for `()` = help: for that trait implementation, expected `()`, found `((),)` diff --git a/tests/ui/typeck/typeck-default-trait-impl-negation-sync.stderr b/tests/ui/typeck/typeck-default-trait-impl-negation-sync.stderr index f5311b6e8ed7..b9fca1a1b54b 100644 --- a/tests/ui/typeck/typeck-default-trait-impl-negation-sync.stderr +++ b/tests/ui/typeck/typeck-default-trait-impl-negation-sync.stderr @@ -17,7 +17,7 @@ error[E0277]: `UnsafeCell` cannot be shared between threads safely LL | is_sync::(); | ^^^^^^^^^^^^^ `UnsafeCell` cannot be shared between threads safely | - = help: within `MyTypeWUnsafe`, the trait `Sync` is not implemented for `UnsafeCell`, which is required by `MyTypeWUnsafe: Sync` + = help: within `MyTypeWUnsafe`, the trait `Sync` is not implemented for `UnsafeCell` note: required because it appears within the type `MyTypeWUnsafe` --> $DIR/typeck-default-trait-impl-negation-sync.rs:21:8 | @@ -35,7 +35,7 @@ error[E0277]: `Managed` cannot be shared between threads safely LL | is_sync::(); | ^^^^^^^^^^^^^ `Managed` cannot be shared between threads safely | - = help: within `MyTypeManaged`, the trait `Sync` is not implemented for `Managed`, which is required by `MyTypeManaged: Sync` + = help: within `MyTypeManaged`, the trait `Sync` is not implemented for `Managed` note: required because it appears within the type `MyTypeManaged` --> $DIR/typeck-default-trait-impl-negation-sync.rs:25:8 | diff --git a/tests/ui/typeck/typeck-unsafe-always-share.stderr b/tests/ui/typeck/typeck-unsafe-always-share.stderr index 3eb792b82e0f..154e504996bc 100644 --- a/tests/ui/typeck/typeck-unsafe-always-share.stderr +++ b/tests/ui/typeck/typeck-unsafe-always-share.stderr @@ -36,7 +36,7 @@ LL | test(ms); | | | required by a bound introduced by this call | - = help: within `MySync`, the trait `Sync` is not implemented for `UnsafeCell`, which is required by `MySync: Sync` + = help: within `MySync`, the trait `Sync` is not implemented for `UnsafeCell` note: required because it appears within the type `MySync` --> $DIR/typeck-unsafe-always-share.rs:8:8 | diff --git a/tests/ui/union/projection-as-union-type-error-2.stderr b/tests/ui/union/projection-as-union-type-error-2.stderr index 39cdf30d8605..3b073ca1fb4e 100644 --- a/tests/ui/union/projection-as-union-type-error-2.stderr +++ b/tests/ui/union/projection-as-union-type-error-2.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `u8: NotImplemented` is not satisfied --> $DIR/projection-as-union-type-error-2.rs:18:8 | LL | a: ::Identity, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `NotImplemented` is not implemented for `u8`, which is required by `u8: Identity` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `NotImplemented` is not implemented for `u8` | help: this trait has no implementations, consider adding one --> $DIR/projection-as-union-type-error-2.rs:9:1 diff --git a/tests/ui/unsized-locals/issue-50940-with-feature.stderr b/tests/ui/unsized-locals/issue-50940-with-feature.stderr index 4c06566709ed..b39eb2e70bba 100644 --- a/tests/ui/unsized-locals/issue-50940-with-feature.stderr +++ b/tests/ui/unsized-locals/issue-50940-with-feature.stderr @@ -13,7 +13,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t LL | A as fn(str) -> A; | ^ doesn't have a size known at compile-time | - = help: within `A`, the trait `Sized` is not implemented for `str`, which is required by `A: Sized` + = help: within `A`, the trait `Sized` is not implemented for `str` note: required because it appears within the type `A` --> $DIR/issue-50940-with-feature.rs:5:12 | diff --git a/tests/ui/unsized-locals/rust-call.stderr b/tests/ui/unsized-locals/rust-call.stderr index b2e13b553e92..9eb0f3dabcca 100644 --- a/tests/ui/unsized-locals/rust-call.stderr +++ b/tests/ui/unsized-locals/rust-call.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation LL | f(*slice); | ^^^^^^ doesn't have a size known at compile-time | - = help: within `([u8],)`, the trait `Sized` is not implemented for `[u8]`, which is required by `([u8],): Sized` + = help: within `([u8],)`, the trait `Sized` is not implemented for `[u8]` = note: required because it appears within the type `([u8],)` = note: argument required to be sized due to `extern "rust-call"` ABI diff --git a/tests/ui/unsized-locals/unsized-exprs.stderr b/tests/ui/unsized-locals/unsized-exprs.stderr index 6da37749facb..8a2ecf0f6c33 100644 --- a/tests/ui/unsized-locals/unsized-exprs.stderr +++ b/tests/ui/unsized-locals/unsized-exprs.stderr @@ -4,7 +4,7 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation LL | udrop::<(i32, [u8])>((42, *foo())); | ^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `({integer}, [u8])`, the trait `Sized` is not implemented for `[u8]`, which is required by `({integer}, [u8]): Sized` + = help: within `({integer}, [u8])`, the trait `Sized` is not implemented for `[u8]` = note: required because it appears within the type `({integer}, [u8])` = note: tuples must have a statically known size to be initialized @@ -14,7 +14,7 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation LL | udrop::>(A { 0: *foo() }); | ^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `A<[u8]>`, the trait `Sized` is not implemented for `[u8]`, which is required by `A<[u8]>: Sized` + = help: within `A<[u8]>`, the trait `Sized` is not implemented for `[u8]` note: required because it appears within the type `A<[u8]>` --> $DIR/unsized-exprs.rs:3:8 | @@ -28,7 +28,7 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation LL | udrop::>(A(*foo())); | ^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `A<[u8]>`, the trait `Sized` is not implemented for `[u8]`, which is required by `A<[u8]>: Sized` + = help: within `A<[u8]>`, the trait `Sized` is not implemented for `[u8]` note: required because it appears within the type `A<[u8]>` --> $DIR/unsized-exprs.rs:3:8 | diff --git a/tests/ui/unsized/unsized-enum2.stderr b/tests/ui/unsized/unsized-enum2.stderr index 48cca6eb4bd0..71cf782120e5 100644 --- a/tests/ui/unsized/unsized-enum2.stderr +++ b/tests/ui/unsized/unsized-enum2.stderr @@ -320,7 +320,7 @@ error[E0277]: the size for values of type `(dyn PathHelper1 + 'static)` cannot b LL | VI(Path1), | ^^^^^ doesn't have a size known at compile-time | - = help: within `Path1`, the trait `Sized` is not implemented for `(dyn PathHelper1 + 'static)`, which is required by `Path1: Sized` + = help: within `Path1`, the trait `Sized` is not implemented for `(dyn PathHelper1 + 'static)` note: required because it appears within the type `Path1` --> $DIR/unsized-enum2.rs:16:8 | @@ -343,7 +343,7 @@ error[E0277]: the size for values of type `(dyn PathHelper2 + 'static)` cannot b LL | VJ{x: Path2}, | ^^^^^ doesn't have a size known at compile-time | - = help: within `Path2`, the trait `Sized` is not implemented for `(dyn PathHelper2 + 'static)`, which is required by `Path2: Sized` + = help: within `Path2`, the trait `Sized` is not implemented for `(dyn PathHelper2 + 'static)` note: required because it appears within the type `Path2` --> $DIR/unsized-enum2.rs:17:8 | @@ -366,7 +366,7 @@ error[E0277]: the size for values of type `(dyn PathHelper3 + 'static)` cannot b LL | VK(isize, Path3), | ^^^^^ doesn't have a size known at compile-time | - = help: within `Path3`, the trait `Sized` is not implemented for `(dyn PathHelper3 + 'static)`, which is required by `Path3: Sized` + = help: within `Path3`, the trait `Sized` is not implemented for `(dyn PathHelper3 + 'static)` note: required because it appears within the type `Path3` --> $DIR/unsized-enum2.rs:18:8 | @@ -389,7 +389,7 @@ error[E0277]: the size for values of type `(dyn PathHelper4 + 'static)` cannot b LL | VL{u: isize, x: Path4}, | ^^^^^ doesn't have a size known at compile-time | - = help: within `Path4`, the trait `Sized` is not implemented for `(dyn PathHelper4 + 'static)`, which is required by `Path4: Sized` + = help: within `Path4`, the trait `Sized` is not implemented for `(dyn PathHelper4 + 'static)` note: required because it appears within the type `Path4` --> $DIR/unsized-enum2.rs:19:8 | diff --git a/tests/ui/wf/hir-wf-check-erase-regions.stderr b/tests/ui/wf/hir-wf-check-erase-regions.stderr index 93449d60e9d0..4b696dc1d1df 100644 --- a/tests/ui/wf/hir-wf-check-erase-regions.stderr +++ b/tests/ui/wf/hir-wf-check-erase-regions.stderr @@ -4,7 +4,7 @@ error[E0277]: `&'a T` is not an iterator LL | type IntoIter = std::iter::Flatten>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&'a T` is not an iterator | - = help: the trait `Iterator` is not implemented for `&'a T`, which is required by `Flatten>: Iterator` + = help: the trait `Iterator` is not implemented for `&'a T` = help: the trait `Iterator` is implemented for `&mut I` = note: required for `Flatten>` to implement `Iterator` note: required by a bound in `std::iter::IntoIterator::IntoIter` @@ -16,7 +16,7 @@ error[E0277]: `&'a T` is not an iterator LL | type IntoIter = std::iter::Flatten>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&'a T` is not an iterator | - = help: the trait `Iterator` is not implemented for `&'a T`, which is required by `&'a T: IntoIterator` + = help: the trait `Iterator` is not implemented for `&'a T` = help: the trait `Iterator` is implemented for `&mut I` = note: required for `&'a T` to implement `IntoIterator` note: required by a bound in `Flatten` @@ -28,7 +28,7 @@ error[E0277]: `&'a T` is not an iterator LL | fn into_iter(self) -> Self::IntoIter { | ^^^^^^^^^^^^^^ `&'a T` is not an iterator | - = help: the trait `Iterator` is not implemented for `&'a T`, which is required by `&'a T: IntoIterator` + = help: the trait `Iterator` is not implemented for `&'a T` = help: the trait `Iterator` is implemented for `&mut I` = note: required for `&'a T` to implement `IntoIterator` note: required by a bound in `Flatten` diff --git a/tests/ui/wf/wf-const-type.stderr b/tests/ui/wf/wf-const-type.stderr index d73642729ea7..dd6e97755bdd 100644 --- a/tests/ui/wf/wf-const-type.stderr +++ b/tests/ui/wf/wf-const-type.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `NotCopy: Copy` is not satisfied --> $DIR/wf-const-type.rs:10:12 | LL | const FOO: IsCopy> = IsCopy { t: None }; - | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option: Copy` + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy` | = note: required for `Option` to implement `Copy` note: required by a bound in `IsCopy` @@ -20,7 +20,7 @@ error[E0277]: the trait bound `NotCopy: Copy` is not satisfied --> $DIR/wf-const-type.rs:10:12 | LL | const FOO: IsCopy> = IsCopy { t: None }; - | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option: Copy` + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy` | = note: required for `Option` to implement `Copy` note: required by a bound in `IsCopy` @@ -39,7 +39,7 @@ error[E0277]: the trait bound `NotCopy: Copy` is not satisfied --> $DIR/wf-const-type.rs:10:50 | LL | const FOO: IsCopy> = IsCopy { t: None }; - | ^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option: Copy` + | ^^^^ the trait `Copy` is not implemented for `NotCopy` | = note: required for `Option` to implement `Copy` note: required by a bound in `IsCopy` diff --git a/tests/ui/wf/wf-static-type.stderr b/tests/ui/wf/wf-static-type.stderr index 36234f3fd176..53b90c69960b 100644 --- a/tests/ui/wf/wf-static-type.stderr +++ b/tests/ui/wf/wf-static-type.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `NotCopy: Copy` is not satisfied --> $DIR/wf-static-type.rs:10:13 | LL | static FOO: IsCopy> = IsCopy { t: None }; - | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option: Copy` + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy` | = note: required for `Option` to implement `Copy` note: required by a bound in `IsCopy` @@ -20,7 +20,7 @@ error[E0277]: the trait bound `NotCopy: Copy` is not satisfied --> $DIR/wf-static-type.rs:10:13 | LL | static FOO: IsCopy> = IsCopy { t: None }; - | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option: Copy` + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy` | = note: required for `Option` to implement `Copy` note: required by a bound in `IsCopy` @@ -39,7 +39,7 @@ error[E0277]: the trait bound `NotCopy: Copy` is not satisfied --> $DIR/wf-static-type.rs:10:51 | LL | static FOO: IsCopy> = IsCopy { t: None }; - | ^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option: Copy` + | ^^^^ the trait `Copy` is not implemented for `NotCopy` | = note: required for `Option` to implement `Copy` note: required by a bound in `IsCopy` From 7591eb60ad3b95d6e1937077f778791b063b5340 Mon Sep 17 00:00:00 2001 From: Michal Piotrowski Date: Wed, 30 Oct 2024 12:31:26 +0100 Subject: [PATCH 366/366] Fix compiler panic with a large number of threads --- compiler/rustc_session/src/config.rs | 4 ++++ compiler/rustc_session/src/options.rs | 11 ++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index d733e32f209d..20a1affa0087 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2464,6 +2464,10 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M early_dcx.early_fatal("value for threads must be a positive non-zero integer"); } + if unstable_opts.threads == parse::MAX_THREADS_CAP { + early_dcx.early_warn(format!("number of threads was capped at {}", parse::MAX_THREADS_CAP)); + } + let fuel = unstable_opts.fuel.is_some() || unstable_opts.print_fuel.is_some(); if fuel && unstable_opts.threads > 1 { early_dcx.early_fatal("optimization fuel is incompatible with multiple threads"); diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 54a4621db246..17eb3870049e 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -457,10 +457,11 @@ mod desc { "either a boolean (`yes`, `no`, `on`, `off`, etc), or `nll` (default: `nll`)"; } -mod parse { +pub mod parse { use std::str::FromStr; pub(crate) use super::*; + pub(crate) const MAX_THREADS_CAP: usize = 256; /// This is for boolean options that don't take a value and start with /// `no-`. This style of option is deprecated. @@ -657,7 +658,7 @@ mod parse { } pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool { - match v.and_then(|s| s.parse().ok()) { + let ret = match v.and_then(|s| s.parse().ok()) { Some(0) => { *slot = std::thread::available_parallelism().map_or(1, NonZero::::get); true @@ -667,7 +668,11 @@ mod parse { true } None => false, - } + }; + // We want to cap the number of threads here to avoid large numbers like 999999 and compiler panics. + // This solution was suggested here https://github.com/rust-lang/rust/issues/117638#issuecomment-1800925067 + *slot = slot.clone().min(MAX_THREADS_CAP); + ret } /// Use this for any numeric option that has a static default.