From 954d9a8f8eb2777671395d83c67025488a3b49fa Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 27 Mar 2023 14:39:32 +0000 Subject: [PATCH 1/9] Remove `remap_env_constness` in queries --- compiler/rustc_macros/src/query.rs | 8 ------ compiler/rustc_middle/src/infer/canonical.rs | 8 ------ compiler/rustc_middle/src/query/mod.rs | 25 ------------------- compiler/rustc_middle/src/ty/mod.rs | 6 ----- compiler/rustc_middle/src/ty/query.rs | 14 ----------- .../traits/query/type_op/prove_predicate.rs | 8 +----- tests/ui/const-generics/issues/issue-88119.rs | 8 +++++- .../const-generics/issues/issue-88119.stderr | 17 +++++++++++++ 8 files changed, 25 insertions(+), 69 deletions(-) create mode 100644 tests/ui/const-generics/issues/issue-88119.stderr diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index f85ba38003c13..a8b25ff66d788 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -112,9 +112,6 @@ struct QueryModifiers { /// Use a separate query provider for local and extern crates separate_provide_extern: Option, - /// Always remap the ParamEnv's constness before hashing. - remap_env_constness: Option, - /// Generate a `feed` method to set the query's value from another query. feedable: Option, } @@ -130,7 +127,6 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { let mut eval_always = None; let mut depth_limit = None; let mut separate_provide_extern = None; - let mut remap_env_constness = None; let mut feedable = None; while !input.is_empty() { @@ -189,8 +185,6 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { try_insert!(depth_limit = modifier); } else if modifier == "separate_provide_extern" { try_insert!(separate_provide_extern = modifier); - } else if modifier == "remap_env_constness" { - try_insert!(remap_env_constness = modifier); } else if modifier == "feedable" { try_insert!(feedable = modifier); } else { @@ -211,7 +205,6 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { eval_always, depth_limit, separate_provide_extern, - remap_env_constness, feedable, }) } @@ -332,7 +325,6 @@ pub fn rustc_queries(input: TokenStream) -> TokenStream { eval_always, depth_limit, separate_provide_extern, - remap_env_constness, ); if modifiers.cache.is_some() { diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index f668c4e77beae..1b3b15fe641f5 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -336,14 +336,6 @@ impl<'tcx, R> Canonical<'tcx, QueryResponse<'tcx, R>> { } } -impl<'tcx, R> Canonical<'tcx, ty::ParamEnvAnd<'tcx, R>> { - #[inline] - pub fn without_const(mut self) -> Self { - self.value = self.value.without_const(); - self - } -} - impl<'tcx, V> Canonical<'tcx, V> { /// Allows you to map the `value` of a canonical while keeping the /// same set of bound variables. diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 964168967564f..f411f7a8f417e 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1088,7 +1088,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>> ) -> Option> { desc { "destructuring MIR constant"} - remap_env_constness } /// Dereference a constant reference or raw pointer and turn the result into a constant @@ -1097,7 +1096,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>> ) -> mir::ConstantKind<'tcx> { desc { "dereferencing MIR constant" } - remap_env_constness } query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> ConstValue<'tcx> { @@ -1340,32 +1338,26 @@ rustc_queries! { /// `ty.is_copy()`, etc, since that will prune the environment where possible. query is_copy_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is `Copy`", env.value } - remap_env_constness } /// Query backing `Ty::is_sized`. query is_sized_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is `Sized`", env.value } - remap_env_constness } /// Query backing `Ty::is_freeze`. query is_freeze_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is freeze", env.value } - remap_env_constness } /// Query backing `Ty::is_unpin`. query is_unpin_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is `Unpin`", env.value } - remap_env_constness } /// Query backing `Ty::needs_drop`. query needs_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` needs drop", env.value } - remap_env_constness } /// Query backing `Ty::has_significant_drop_raw`. query has_significant_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` has a significant drop", env.value } - remap_env_constness } /// Query backing `Ty::is_structural_eq_shallow`. @@ -1405,7 +1397,6 @@ rustc_queries! { ) -> Result, ty::layout::LayoutError<'tcx>> { depth_limit desc { "computing layout of `{}`", key.value } - remap_env_constness } /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers. @@ -1416,7 +1407,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List>)> ) -> Result<&'tcx abi::call::FnAbi<'tcx, Ty<'tcx>>, ty::layout::FnAbiError<'tcx>> { desc { "computing call ABI of `{}` function pointers", key.value.0 } - remap_env_constness } /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for @@ -1428,7 +1418,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, (ty::Instance<'tcx>, &'tcx ty::List>)> ) -> Result<&'tcx abi::call::FnAbi<'tcx, Ty<'tcx>>, ty::layout::FnAbiError<'tcx>> { desc { "computing call ABI of `{}`", key.value.0 } - remap_env_constness } query dylib_dependency_formats(_: CrateNum) @@ -1935,7 +1924,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: invoke `try_normalize_erasing_regions` instead. @@ -1943,7 +1931,6 @@ rustc_queries! { goal: ParamEnvAnd<'tcx, GenericArg<'tcx>> ) -> Result, NoSolution> { desc { "normalizing `{}`", goal.value } - remap_env_constness } query implied_outlives_bounds( @@ -1953,7 +1940,6 @@ rustc_queries! { NoSolution, > { desc { "computing implied outlives bounds for `{}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: @@ -1965,7 +1951,6 @@ rustc_queries! { NoSolution, > { desc { "computing dropck types for `{}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: invoke `infcx.predicate_may_hold()` or @@ -1993,7 +1978,6 @@ rustc_queries! { NoSolution, > { desc { "evaluating `type_op_ascribe_user_type` `{:?}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Eq` type-op @@ -2004,7 +1988,6 @@ rustc_queries! { NoSolution, > { desc { "evaluating `type_op_eq` `{:?}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Subtype` type-op @@ -2015,7 +1998,6 @@ rustc_queries! { NoSolution, > { desc { "evaluating `type_op_subtype` `{:?}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: part of the `ProvePredicate` type-op @@ -2036,7 +2018,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{}`", goal.value.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Normalize` type-op @@ -2047,7 +2028,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{:?}`", goal.value.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Normalize` type-op @@ -2058,7 +2038,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{:?}`", goal.value.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Normalize` type-op @@ -2069,7 +2048,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{:?}`", goal.value.value.value } - remap_env_constness } query subst_and_check_impossible_predicates(key: (DefId, SubstsRef<'tcx>)) -> bool { @@ -2091,7 +2069,6 @@ rustc_queries! { goal: CanonicalTyGoal<'tcx> ) -> MethodAutoderefStepsResult<'tcx> { desc { "computing autoderef types for `{}`", goal.value.value } - remap_env_constness } query supported_target_features(_: CrateNum) -> &'tcx FxHashMap> { @@ -2136,7 +2113,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)> ) -> Result>, ErrorGuaranteed> { desc { "resolving instance `{}`", ty::Instance::new(key.value.0, key.value.1) } - remap_env_constness } query resolve_instance_of_const_arg( @@ -2146,7 +2122,6 @@ rustc_queries! { "resolving instance of the const argument `{}`", ty::Instance::new(key.value.0.to_def_id(), key.value.2), } - remap_env_constness } query reveal_opaque_types_in_bounds(key: &'tcx ty::List>) -> &'tcx ty::List> { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index c856bb25e1474..5d07153fa8c7c 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1849,12 +1849,6 @@ impl<'tcx, T> ParamEnvAnd<'tcx, T> { pub fn into_parts(self) -> (ParamEnv<'tcx>, T) { (self.param_env, self.value) } - - #[inline] - pub fn without_const(mut self) -> Self { - self.param_env = self.param_env.without_const(); - self - } } #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)] diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index fa9fea7234486..97592cbc567d7 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -202,16 +202,6 @@ macro_rules! separate_provide_extern_default { }; } -macro_rules! opt_remap_env_constness { - ([][$name:ident]) => {}; - ([(remap_env_constness) $($rest:tt)*][$name:ident]) => { - let $name = $name.without_const(); - }; - ([$other:tt $($modifiers:tt)*][$name:ident]) => { - opt_remap_env_constness!([$($modifiers)*][$name]) - }; -} - macro_rules! define_callbacks { ( $($(#[$attr:meta])* @@ -353,7 +343,6 @@ macro_rules! define_callbacks { #[inline(always)] pub fn $name(self, key: query_helper_param_ty!($($K)*)) { let key = key.into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) { Some(_) => return, @@ -372,7 +361,6 @@ macro_rules! define_callbacks { #[inline(always)] pub fn $name(self, key: query_helper_param_ty!($($K)*)) { let key = key.into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) { Some(_) => return, @@ -402,7 +390,6 @@ macro_rules! define_callbacks { pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> $V { let key = key.into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); restore::<$V>(match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) { Some(value) => value, @@ -492,7 +479,6 @@ macro_rules! define_feedable { #[inline(always)] pub fn $name(self, value: query_provided::$name<'tcx>) -> $V { let key = self.key().into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); let tcx = self.tcx; let erased = query_provided_to_value::$name(tcx, value); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs index b63da28e27475..baa2fbb6751c3 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs @@ -32,14 +32,8 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, - mut canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, + canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, ) -> Fallible> { - match canonicalized.value.value.predicate.kind().skip_binder() { - ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => { - canonicalized.value.param_env.remap_constness_with(pred.constness); - } - _ => canonicalized.value.param_env = canonicalized.value.param_env.without_const(), - } tcx.type_op_prove_predicate(canonicalized) } } diff --git a/tests/ui/const-generics/issues/issue-88119.rs b/tests/ui/const-generics/issues/issue-88119.rs index 647b0eea86daf..ddc6599a53eeb 100644 --- a/tests/ui/const-generics/issues/issue-88119.rs +++ b/tests/ui/const-generics/issues/issue-88119.rs @@ -1,4 +1,10 @@ -// check-pass +// known-bug: #88119 +// failure-status: 101 +// normalize-stderr-test "note: .*\n" -> "" +// normalize-stderr-test "thread 'rustc' panicked.*\n" -> "" +// normalize-stderr-test "\s\d{1,}: .*\n" -> "" +// normalize-stderr-test "\s at .*\n" -> "" +// rustc-env:RUST_BACKTRACE=0 #![allow(incomplete_features)] #![feature(const_trait_impl, generic_const_exprs)] diff --git a/tests/ui/const-generics/issues/issue-88119.stderr b/tests/ui/const-generics/issues/issue-88119.stderr new file mode 100644 index 0000000000000..b4e18c86b1fd6 --- /dev/null +++ b/tests/ui/const-generics/issues/issue-88119.stderr @@ -0,0 +1,17 @@ +error: internal compiler error: no errors encountered even though `delay_span_bug` issued + +error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` + | + = + +error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` + | + = + + + + +query stack during panic: +end of query stack +error: aborting due to 3 previous errors + From 886c0e638806a2541b08ffb1efb88366376aac4b Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 8 Apr 2023 09:27:48 +0000 Subject: [PATCH 2/9] fix ICE --- compiler/rustc_traits/src/type_op.rs | 1 + tests/ui/const-generics/issues/issue-88119.rs | 8 +------ .../const-generics/issues/issue-88119.stderr | 17 -------------- .../trait-method-ptr-in-consts-ice.rs | 23 +++++++++++++++++++ 4 files changed, 25 insertions(+), 24 deletions(-) delete mode 100644 tests/ui/const-generics/issues/issue-88119.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index e0fd487b3d37f..19622112f2a28 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -89,6 +89,7 @@ fn relate_mir_and_user_substs<'tcx>( def_id: hir::def_id::DefId, user_substs: UserSubsts<'tcx>, ) -> Result<(), NoSolution> { + let param_env = param_env.without_const(); let UserSubsts { user_self_ty, substs } = user_substs; let tcx = ocx.infcx.tcx; let cause = ObligationCause::dummy_with_span(span); diff --git a/tests/ui/const-generics/issues/issue-88119.rs b/tests/ui/const-generics/issues/issue-88119.rs index ddc6599a53eeb..647b0eea86daf 100644 --- a/tests/ui/const-generics/issues/issue-88119.rs +++ b/tests/ui/const-generics/issues/issue-88119.rs @@ -1,10 +1,4 @@ -// known-bug: #88119 -// failure-status: 101 -// normalize-stderr-test "note: .*\n" -> "" -// normalize-stderr-test "thread 'rustc' panicked.*\n" -> "" -// normalize-stderr-test "\s\d{1,}: .*\n" -> "" -// normalize-stderr-test "\s at .*\n" -> "" -// rustc-env:RUST_BACKTRACE=0 +// check-pass #![allow(incomplete_features)] #![feature(const_trait_impl, generic_const_exprs)] diff --git a/tests/ui/const-generics/issues/issue-88119.stderr b/tests/ui/const-generics/issues/issue-88119.stderr deleted file mode 100644 index b4e18c86b1fd6..0000000000000 --- a/tests/ui/const-generics/issues/issue-88119.stderr +++ /dev/null @@ -1,17 +0,0 @@ -error: internal compiler error: no errors encountered even though `delay_span_bug` issued - -error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` - | - = - -error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` - | - = - - - - -query stack during panic: -end of query stack -error: aborting due to 3 previous errors - diff --git a/tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs b/tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs new file mode 100644 index 0000000000000..7d7cb967c6619 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs @@ -0,0 +1,23 @@ +// check-pass + +struct LazyLock { + data: (Option, fn() -> T), +} + +impl LazyLock { + pub const fn new(f: fn() -> T) -> LazyLock { + LazyLock { data: (None, f) } + } +} + +struct A(Option); + +impl Default for A { + fn default() -> Self { + A(None) + } +} + +static EMPTY_SET: LazyLock> = LazyLock::new(A::default); + +fn main() {} From 4460a1dc28a10cd74a6e5636d6e2cd8c8f06ba4b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 15 Apr 2023 09:31:11 +1000 Subject: [PATCH 3/9] Remove `TypeSuper{Foldable,Visitable}` impls for `Region`. These traits exist so that folders/visitors can recurse into types of interest: binders, types, regions, predicates, and consts. But `Region` is non-recursive and cannot contain other types of interest, so its methods in these traits are trivial. This commit inlines and removes those trivial methods. --- .../rustc_hir_analysis/src/variance/mod.rs | 2 +- .../trait_impl_difference.rs | 4 +- compiler/rustc_middle/src/ty/fold.rs | 3 +- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- .../rustc_middle/src/ty/structural_impls.rs | 18 --------- compiler/rustc_middle/src/ty/visit.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 2 +- compiler/rustc_traits/src/chalk/lowering.rs | 8 ++-- compiler/rustc_type_ir/src/fold.rs | 37 +++++++++---------- compiler/rustc_type_ir/src/visit.rs | 28 ++++++++------ src/librustdoc/clean/auto_trait.rs | 11 +++--- 11 files changed, 51 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index 0a45119ff055b..4d240e90b143d 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -105,7 +105,7 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc if let ty::RegionKind::ReEarlyBound(ebr) = r.kind() { self.variances[ebr.index as usize] = ty::Invariant; } - r.super_visit_with(self) + ControlFlow::Continue(()) } #[instrument(level = "trace", skip(self), ret)] diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs index 2875448ee157c..ce70bcc5c8511 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -13,7 +13,7 @@ use rustc_hir::intravisit::Visitor; use rustc_middle::hir::nested_filter; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::print::RegionHighlightMode; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor}; use rustc_span::Span; use std::ops::ControlFlow; @@ -81,7 +81,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { self.highlight.highlighting_region(r, self.counter); self.counter += 1; } - r.super_visit_with(self) + ControlFlow::Continue(()) } } diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index 203e16bea27fe..25890eb15cde4 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -37,7 +37,8 @@ where } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { - let r = r.super_fold_with(self); + // This one is a little different, because `super_fold_with` is not + // implemented on non-recursive `Region`. (self.lt_op)(r) } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 72caadaf66199..af76cf7cc4e0d 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2518,7 +2518,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { self.used_region_names.insert(name); } - r.super_visit_with(self) + ControlFlow::Continue(()) } // We collect types in order to prevent really large types from compiling for diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 5c604bb6db274..619fcea8b7d4b 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -583,24 +583,6 @@ impl<'tcx> TypeVisitable> for ty::Region<'tcx> { } } -impl<'tcx> TypeSuperFoldable> for ty::Region<'tcx> { - fn try_super_fold_with>>( - self, - _folder: &mut F, - ) -> Result { - Ok(self) - } -} - -impl<'tcx> TypeSuperVisitable> for ty::Region<'tcx> { - fn super_visit_with>>( - &self, - _visitor: &mut V, - ) -> ControlFlow { - ControlFlow::Continue(()) - } -} - impl<'tcx> TypeFoldable> for ty::Predicate<'tcx> { fn try_fold_with>>( self, diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index 08a62c900f972..24a1f04c7e388 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -364,7 +364,7 @@ impl<'tcx> TypeVisitor> for ValidateBoundVars<'tcx> { _ => (), }; - r.super_visit_with(self) + ControlFlow::Continue(()) } } diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 8a203dec86bab..ed82b9c015277 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -450,7 +450,7 @@ fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefI { return ControlFlow::Break(()); } - r.super_visit_with(self) + ControlFlow::Continue(()) } fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow { if let ty::ConstKind::Param(param) = ct.kind() diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs index 2be72879b7b13..31eea22d72b88 100644 --- a/compiler/rustc_traits/src/chalk/lowering.rs +++ b/compiler/rustc_traits/src/chalk/lowering.rs @@ -998,7 +998,7 @@ impl<'tcx> TypeVisitor> for BoundVarsCollector<'tcx> { _ => (), }; - r.super_visit_with(self) + ControlFlow::Continue(()) } } @@ -1048,7 +1048,7 @@ impl<'a, 'tcx> TypeFolder> for NamedBoundVarSubstitutor<'a, 'tcx> { _ => (), }; - r.super_fold_with(self) + r } } @@ -1142,7 +1142,7 @@ impl<'tcx> TypeFolder> for ParamsSubstitutor<'tcx> { } }, - _ => r.super_fold_with(self), + _ => r, } } } @@ -1223,6 +1223,6 @@ impl<'tcx> TypeVisitor> for PlaceholdersCollector { _ => (), }; - r.super_visit_with(self) + ControlFlow::Continue(()) } } diff --git a/compiler/rustc_type_ir/src/fold.rs b/compiler/rustc_type_ir/src/fold.rs index 3a053d4c6a997..371c611912286 100644 --- a/compiler/rustc_type_ir/src/fold.rs +++ b/compiler/rustc_type_ir/src/fold.rs @@ -16,8 +16,10 @@ //! - Types of interest, for which the methods delegate to the folder. //! - All other types, including generic containers like `Vec` and `Option`. //! It defines a "skeleton" of how they should be folded. -//! - `TypeSuperFoldable`. This is implemented only for each type of interest, -//! and defines the folding "skeleton" for these types. +//! - `TypeSuperFoldable`. This is implemented only for recursive types of +//! interest, and defines the folding "skeleton" for these types. (This +//! excludes `Region` because it is non-recursive, i.e. it never contains +//! other types of interest.) //! - `TypeFolder`/`FallibleTypeFolder`. One of these is implemented for each //! folder. This defines how types of interest are folded. //! @@ -72,9 +74,9 @@ pub trait TypeFoldable: TypeVisitable { // This trait is implemented for types of interest. pub trait TypeSuperFoldable: TypeFoldable { - /// Provides a default fold for a type of interest. This should only be - /// called within `TypeFolder` methods, when a non-custom traversal is - /// desired for the value of the type of interest passed to that method. + /// Provides a default fold for a recursive type of interest. This should + /// only be called within `TypeFolder` methods, when a non-custom traversal + /// is desired for the value of the type of interest passed to that method. /// For example, in `MyFolder::try_fold_ty(ty)`, it is valid to call /// `ty.try_super_fold_with(self)`, but any other folding should be done /// with `xyz.try_fold_with(self)`. @@ -118,11 +120,11 @@ pub trait TypeFolder: FallibleTypeFolder { t.super_fold_with(self) } - fn fold_region(&mut self, r: I::Region) -> I::Region - where - I::Region: TypeSuperFoldable, - { - r.super_fold_with(self) + // The default region folder is a no-op because `Region` is non-recursive + // and has no `super_visit_with` method to call. That also explains the + // lack of `I::Region: TypeSuperFoldable` bound on this method. + fn fold_region(&mut self, r: I::Region) -> I::Region { + r } fn fold_const(&mut self, c: I::Const) -> I::Const @@ -167,11 +169,11 @@ pub trait FallibleTypeFolder: Sized { t.try_super_fold_with(self) } - fn try_fold_region(&mut self, r: I::Region) -> Result - where - I::Region: TypeSuperFoldable, - { - r.try_super_fold_with(self) + // The default region folder is a no-op because `Region` is non-recursive + // and has no `super_visit_with` method to call. That also explains the + // lack of `I::Region: TypeSuperFoldable` bound on this method. + fn try_fold_region(&mut self, r: I::Region) -> Result { + Ok(r) } fn try_fold_const(&mut self, c: I::Const) -> Result @@ -216,10 +218,7 @@ where Ok(self.fold_ty(t)) } - fn try_fold_region(&mut self, r: I::Region) -> Result - where - I::Region: TypeSuperFoldable, - { + fn try_fold_region(&mut self, r: I::Region) -> Result { Ok(self.fold_region(r)) } diff --git a/compiler/rustc_type_ir/src/visit.rs b/compiler/rustc_type_ir/src/visit.rs index 62239fd20066a..878c7aec6c18e 100644 --- a/compiler/rustc_type_ir/src/visit.rs +++ b/compiler/rustc_type_ir/src/visit.rs @@ -13,8 +13,11 @@ //! - Types of interest, for which the methods delegate to the visitor. //! - All other types, including generic containers like `Vec` and `Option`. //! It defines a "skeleton" of how they should be visited. -//! - `TypeSuperVisitable`. This is implemented only for each type of interest, -//! and defines the visiting "skeleton" for these types. +//! - `TypeSuperVisitable`. This is implemented only for recursive types of +//! interest, and defines the visiting "skeleton" for these types. (This +//! excludes `Region` because it is non-recursive, i.e. it never contains +//! other types of interest.) +//! //! - `TypeVisitor`. This is implemented for each visitor. This defines how //! types of interest are visited. //! @@ -62,12 +65,13 @@ pub trait TypeVisitable: fmt::Debug + Clone { fn visit_with>(&self, visitor: &mut V) -> ControlFlow; } +// This trait is implemented for types of interest. pub trait TypeSuperVisitable: TypeVisitable { - /// Provides a default visit for a type of interest. This should only be - /// called within `TypeVisitor` methods, when a non-custom traversal is - /// desired for the value of the type of interest passed to that method. - /// For example, in `MyVisitor::visit_ty(ty)`, it is valid to call - /// `ty.super_visit_with(self)`, but any other visiting should be done + /// Provides a default visit for a recursive type of interest. This should + /// only be called within `TypeVisitor` methods, when a non-custom + /// traversal is desired for the value of the type of interest passed to + /// that method. For example, in `MyVisitor::visit_ty(ty)`, it is valid to + /// call `ty.super_visit_with(self)`, but any other visiting should be done /// with `xyz.visit_with(self)`. fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow; } @@ -92,11 +96,11 @@ pub trait TypeVisitor: Sized { t.super_visit_with(self) } - fn visit_region(&mut self, r: I::Region) -> ControlFlow - where - I::Region: TypeSuperVisitable, - { - r.super_visit_with(self) + // The default region visitor is a no-op because `Region` is non-recursive + // and has no `super_visit_with` method to call. That also explains the + // lack of `I::Region: TypeSuperVisitable` bound. + fn visit_region(&mut self, _r: I::Region) -> ControlFlow { + ControlFlow::Continue(()) } fn visit_const(&mut self, c: I::Const) -> ControlFlow diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 9479b3ee0369a..f6088f4e64a41 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; -use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable, TypeSuperFoldable}; +use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable}; use rustc_trait_selection::traits::auto_trait::{self, AutoTraitResult}; use thin_vec::ThinVec; @@ -740,10 +740,9 @@ impl<'a, 'tcx> TypeFolder> for RegionReplacer<'a, 'tcx> { } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { - (match *r { - ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(), - _ => None, - }) - .unwrap_or_else(|| r.super_fold_with(self)) + match *r { + ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned().unwrap_or(r), + _ => r, + } } } From ee8f92ba0a3f1ceb74a9474f61761b3e3e3e5ac5 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sun, 16 Apr 2023 11:48:01 +0200 Subject: [PATCH 4/9] Use lints via `lint_defs` instead of `lints` This gets rid of a blocking dependency edge from `rustc_lint->rustc_analysis->rustc_hir_typeck->rustc_interface` --- Cargo.lock | 2 +- compiler/rustc_hir_analysis/Cargo.toml | 2 +- compiler/rustc_hir_analysis/src/check/check.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 12be36ef86126..094eb6fa67efb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4775,7 +4775,7 @@ dependencies = [ "rustc_hir", "rustc_index", "rustc_infer", - "rustc_lint", + "rustc_lint_defs", "rustc_macros", "rustc_middle", "rustc_session", diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index fab16b80fb59c..a64466884d8b2 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -23,7 +23,7 @@ rustc_span = { path = "../rustc_span" } rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_lint = { path = "../rustc_lint" } +rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_type_ir = { path = "../rustc_type_ir" } rustc_feature = { path = "../rustc_feature" } thin-vec = "0.2.12" diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 0bb98fdf2a23e..0c54fd70c9b5e 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -15,7 +15,7 @@ use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::{Obligation, TraitEngineExt as _}; -use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS; +use rustc_lint_defs::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS; use rustc_middle::hir::nested_filter; use rustc_middle::middle::stability::EvalResult; use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES}; From 2109fe4e4e3cd8b81a4f91fab8be9a30f2eee8bc Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sun, 16 Apr 2023 12:03:39 +0200 Subject: [PATCH 5/9] Move some utils out of `rustc_const_eval` This allows us to get rid of the `rustc_const_eval->rustc_borrowck` dependency edge which was delaying the compilation of borrowck. The added utils in `rustc_middle` are small and should not affect compile times there. --- Cargo.lock | 1 - compiler/rustc_borrowck/Cargo.toml | 1 - compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs | 4 ++-- compiler/rustc_borrowck/src/diagnostics/mod.rs | 6 +++--- .../rustc_borrowck/src/diagnostics/mutability_errors.rs | 2 +- compiler/rustc_borrowck/src/lib.rs | 1 + .../src/util/collect_writes.rs | 0 compiler/rustc_borrowck/src/util/mod.rs | 3 +++ .../rustc_const_eval/src/transform/check_consts/ops.rs | 2 +- compiler/rustc_const_eval/src/util/mod.rs | 5 ----- compiler/rustc_middle/src/lib.rs | 6 +----- .../src/util/call_kind.rs | 4 ++-- .../src/util/find_self_call.rs | 6 +++--- compiler/rustc_middle/src/util/mod.rs | 7 +++++++ .../rustc_mir_transform/src/check_const_item_mutation.rs | 7 ++++++- 15 files changed, 30 insertions(+), 25 deletions(-) rename compiler/{rustc_const_eval => rustc_borrowck}/src/util/collect_writes.rs (100%) create mode 100644 compiler/rustc_borrowck/src/util/mod.rs rename compiler/{rustc_const_eval => rustc_middle}/src/util/call_kind.rs (97%) rename compiler/{rustc_const_eval => rustc_middle}/src/util/find_self_call.rs (92%) create mode 100644 compiler/rustc_middle/src/util/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 12be36ef86126..670f4cc956205 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4421,7 +4421,6 @@ dependencies = [ "either", "itertools", "polonius-engine", - "rustc_const_eval", "rustc_data_structures", "rustc_errors", "rustc_graphviz", diff --git a/compiler/rustc_borrowck/Cargo.toml b/compiler/rustc_borrowck/Cargo.toml index 87c113f3e30b7..e0bb87336e54a 100644 --- a/compiler/rustc_borrowck/Cargo.toml +++ b/compiler/rustc_borrowck/Cargo.toml @@ -20,7 +20,6 @@ rustc_infer = { path = "../rustc_infer" } rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_const_eval = { path = "../rustc_const_eval" } rustc_mir_dataflow = { path = "../rustc_mir_dataflow" } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 75a3dd0c0f3d6..6259ae47e896b 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1,5 +1,4 @@ use either::Either; -use rustc_const_eval::util::CallKind; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{ @@ -18,6 +17,7 @@ use rustc_middle::mir::{ ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, VarBindingForm, }; use rustc_middle::ty::{self, suggest_constraining_type_params, PredicateKind, Ty}; +use rustc_middle::util::CallKind; use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex}; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::DesugaringKind; @@ -2424,7 +2424,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { Some((method_did, method_substs)), ) = ( &self.body[loan.reserve_location.block].terminator, - rustc_const_eval::util::find_self_call( + rustc_middle::util::find_self_call( tcx, self.body, loan.assigned_place.local, diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 110354a20d839..dd003b5b0402b 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1,7 +1,6 @@ //! Borrow checker diagnostics. use itertools::Itertools; -use rustc_const_eval::util::{call_kind, CallDesugaringKind}; use rustc_errors::{Applicability, Diagnostic}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, Namespace}; @@ -15,6 +14,7 @@ use rustc_middle::mir::{ }; use rustc_middle::ty::print::Print; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; +use rustc_middle::util::{call_kind, CallDesugaringKind}; use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult}; use rustc_span::def_id::LocalDefId; use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP}; @@ -45,7 +45,7 @@ pub(crate) use mutability_errors::AccessKind; pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder; pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors}; pub(crate) use region_name::{RegionName, RegionNameSource}; -pub(crate) use rustc_const_eval::util::CallKind; +pub(crate) use rustc_middle::util::CallKind; pub(super) struct DescribePlaceOpt { pub including_downcast: bool, @@ -874,7 +874,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { }) = &self.body[location.block].terminator { let Some((method_did, method_substs)) = - rustc_const_eval::util::find_self_call( + rustc_middle::util::find_self_call( self.infcx.tcx, &self.body, target_temp, diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 9d90400965040..9c907147e5ad9 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -15,8 +15,8 @@ use rustc_span::{sym, BytePos, Span}; use rustc_target::abi::FieldIdx; use crate::diagnostics::BorrowedContentSource; +use crate::util::FindAssignments; use crate::MirBorrowckCtxt; -use rustc_const_eval::util::collect_writes::FindAssignments; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum AccessKind { diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 70d0a101b4ed9..fdd82c7e3b281 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -88,6 +88,7 @@ mod session_diagnostics; mod type_check; mod universal_regions; mod used_muts; +mod util; /// A public API provided for the Rust compiler consumers. pub mod consumers; diff --git a/compiler/rustc_const_eval/src/util/collect_writes.rs b/compiler/rustc_borrowck/src/util/collect_writes.rs similarity index 100% rename from compiler/rustc_const_eval/src/util/collect_writes.rs rename to compiler/rustc_borrowck/src/util/collect_writes.rs diff --git a/compiler/rustc_borrowck/src/util/mod.rs b/compiler/rustc_borrowck/src/util/mod.rs new file mode 100644 index 0000000000000..7377d4de7274f --- /dev/null +++ b/compiler/rustc_borrowck/src/util/mod.rs @@ -0,0 +1,3 @@ +mod collect_writes; + +pub use collect_writes::FindAssignments; diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index c0f5b3725b36d..4fe842856aad1 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -14,6 +14,7 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{suggest_constraining_type_param, Adt, Closure, FnDef, FnPtr, Param, Ty}; use rustc_middle::ty::{Binder, TraitRef}; +use rustc_middle::util::{call_kind, CallDesugaringKind, CallKind}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; use rustc_span::{BytePos, Pos, Span, Symbol}; @@ -21,7 +22,6 @@ use rustc_trait_selection::traits::SelectionContext; use super::ConstCx; use crate::errors; -use crate::util::{call_kind, CallDesugaringKind, CallKind}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Status { diff --git a/compiler/rustc_const_eval/src/util/mod.rs b/compiler/rustc_const_eval/src/util/mod.rs index c0aabd77ceead..7641f560714d4 100644 --- a/compiler/rustc_const_eval/src/util/mod.rs +++ b/compiler/rustc_const_eval/src/util/mod.rs @@ -1,14 +1,9 @@ mod alignment; -mod call_kind; mod check_validity_requirement; -pub mod collect_writes; mod compare_types; -mod find_self_call; mod type_name; pub use self::alignment::is_disaligned; -pub use self::call_kind::{call_kind, CallDesugaringKind, CallKind}; pub use self::check_validity_requirement::check_validity_requirement; pub use self::compare_types::{is_equal_up_to_subtyping, is_subtype}; -pub use self::find_self_call::find_self_call; pub use self::type_name::type_name; diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index b4edb02f6c48d..1ddc08eac7dfe 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -99,13 +99,9 @@ pub mod mir; pub mod thir; pub mod traits; pub mod ty; +pub mod util; mod values; -pub mod util { - pub mod bug; - pub mod common; -} - // Allows macros to refer to this crate as `::rustc_middle` extern crate self as rustc_middle; diff --git a/compiler/rustc_const_eval/src/util/call_kind.rs b/compiler/rustc_middle/src/util/call_kind.rs similarity index 97% rename from compiler/rustc_const_eval/src/util/call_kind.rs rename to compiler/rustc_middle/src/util/call_kind.rs index 995363c0edd92..627c84c388c04 100644 --- a/compiler/rustc_const_eval/src/util/call_kind.rs +++ b/compiler/rustc_middle/src/util/call_kind.rs @@ -2,10 +2,10 @@ //! as well as errors when attempting to call a non-const function in a const //! context. +use crate::ty::subst::SubstsRef; +use crate::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt}; use rustc_hir::def_id::DefId; use rustc_hir::{lang_items, LangItem}; -use rustc_middle::ty::subst::SubstsRef; -use rustc_middle::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt}; use rustc_span::symbol::Ident; use rustc_span::{sym, DesugaringKind, Span}; diff --git a/compiler/rustc_const_eval/src/util/find_self_call.rs b/compiler/rustc_middle/src/util/find_self_call.rs similarity index 92% rename from compiler/rustc_const_eval/src/util/find_self_call.rs rename to compiler/rustc_middle/src/util/find_self_call.rs index 33ad128eeeb75..0eab0adf07e48 100644 --- a/compiler/rustc_const_eval/src/util/find_self_call.rs +++ b/compiler/rustc_middle/src/util/find_self_call.rs @@ -1,6 +1,6 @@ -use rustc_middle::mir::*; -use rustc_middle::ty::subst::SubstsRef; -use rustc_middle::ty::{self, TyCtxt}; +use crate::mir::*; +use crate::ty::subst::SubstsRef; +use crate::ty::{self, TyCtxt}; use rustc_span::def_id::DefId; /// Checks if the specified `local` is used as the `self` parameter of a method call diff --git a/compiler/rustc_middle/src/util/mod.rs b/compiler/rustc_middle/src/util/mod.rs new file mode 100644 index 0000000000000..53b4257899bce --- /dev/null +++ b/compiler/rustc_middle/src/util/mod.rs @@ -0,0 +1,7 @@ +pub mod bug; +pub mod call_kind; +pub mod common; +pub mod find_self_call; + +pub use call_kind::{call_kind, CallDesugaringKind, CallKind}; +pub use find_self_call::find_self_call; diff --git a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs index 3d32c586554d5..57b24c9c552a5 100644 --- a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs +++ b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs @@ -134,7 +134,12 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> { // the `self` parameter of a method call (as the terminator of our current // BasicBlock). If so, we emit a more specific lint. let method_did = self.target_local.and_then(|target_local| { - crate::util::find_self_call(self.tcx, &self.body, target_local, loc.block) + rustc_middle::util::find_self_call( + self.tcx, + &self.body, + target_local, + loc.block, + ) }); let lint_loc = if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc }; From bcc15bba953dcb749d88950539b5e206a8bd86bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 20:49:54 +0200 Subject: [PATCH 6/9] use matches! macro in more places --- compiler/rustc_ast/src/ast.rs | 20 +++++++++---------- compiler/rustc_ast_lowering/src/lib.rs | 5 +---- compiler/rustc_hir/src/def.rs | 5 +---- compiler/rustc_hir_analysis/src/collect.rs | 5 +---- compiler/rustc_hir_typeck/src/expr.rs | 6 ++---- .../nice_region_error/static_impl_trait.rs | 11 ++++------ compiler/rustc_infer/src/infer/mod.rs | 8 ++++---- compiler/rustc_infer/src/traits/mod.rs | 8 ++++---- compiler/rustc_mir_build/src/errors.rs | 9 ++------- .../src/thir/pattern/check_match.rs | 6 ++---- compiler/rustc_parse/src/parser/item.rs | 14 ++++++------- .../rustc_parse/src/parser/nonterminal.rs | 10 ++++------ compiler/rustc_resolve/src/diagnostics.rs | 20 ++++++++++--------- 13 files changed, 52 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index df1a716755b48..ab0409efb3b29 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1298,17 +1298,17 @@ impl Expr { /// To a first-order approximation, is this a pattern? pub fn is_approximately_pattern(&self) -> bool { - match &self.peel_parens().kind { + matches!( + &self.peel_parens().kind, ExprKind::Array(_) - | ExprKind::Call(_, _) - | ExprKind::Tup(_) - | ExprKind::Lit(_) - | ExprKind::Range(_, _, _) - | ExprKind::Underscore - | ExprKind::Path(_, _) - | ExprKind::Struct(_) => true, - _ => false, - } + | ExprKind::Call(_, _) + | ExprKind::Tup(_) + | ExprKind::Lit(_) + | ExprKind::Range(_, _, _) + | ExprKind::Underscore + | ExprKind::Path(_, _) + | ExprKind::Struct(_) + ) } } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index f7ae96b7c4a3d..2af47e11637c5 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -332,10 +332,7 @@ enum FnDeclKind { impl FnDeclKind { fn param_impl_trait_allowed(&self) -> bool { - match self { - FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => true, - _ => false, - } + matches!(self, FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait) } fn return_impl_trait_allowed(&self, tcx: TyCtxt<'_>) -> bool { diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 8c58129c800f8..30bf8c2ad104b 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -234,10 +234,7 @@ impl DefKind { #[inline] pub fn is_fn_like(self) -> bool { - match self { - DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true, - _ => false, - } + matches!(self, DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator) } /// Whether `query get_codegen_attrs` should be used with this definition. diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index cbbaf8f857dac..7c07a1ebaec07 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1457,10 +1457,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( } fn is_foreign_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { - match tcx.hir().get_by_def_id(def_id) { - Node::ForeignItem(..) => true, - _ => false, - } + matches!(tcx.hir().get_by_def_id(def_id), Node::ForeignItem(..)) } fn generator_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 6ffa0134f3d55..ffc73d64fc04b 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1735,10 +1735,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { self.check_expr_has_type_or_error(base_expr, adt_ty, |_| { let base_ty = self.typeck_results.borrow().expr_ty(*base_expr); - let same_adt = match (adt_ty.kind(), base_ty.kind()) { - (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true, - _ => false, - }; + let same_adt = matches!((adt_ty.kind(), base_ty.kind()), + (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt); if self.tcx.sess.is_nightly_build() && same_adt { feature_err( &self.tcx.sess.parse_sess, diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index 22c1e3871175e..27c3b796d14e5 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -312,13 +312,10 @@ pub fn suggest_new_region_bound( Applicability::MaybeIncorrect, ); } - } else if opaque.bounds.iter().any(|arg| match arg { - GenericBound::Outlives(Lifetime { ident, .. }) - if ident.name.to_string() == lifetime_name => - { - true - } - _ => false, + } else if opaque.bounds.iter().any(|arg| { + matches!(arg, + GenericBound::Outlives(Lifetime { ident, .. }) + if ident.name.to_string() == lifetime_name ) }) { } else { // get a lifetime name of existing named lifetimes if any diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 66f51328bbe7c..f263a0773e4e1 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1577,10 +1577,10 @@ impl<'tcx> InferCtxt<'tcx> { (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => { use self::type_variable::TypeVariableValue; - match inner.try_type_variables_probe_ref(ty_var) { - Some(TypeVariableValue::Unknown { .. }) => true, - _ => false, - } + matches!( + inner.try_type_variables_probe_ref(ty_var), + Some(TypeVariableValue::Unknown { .. }) + ) } _ => false, }; diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index e01b6caf43064..9dd4f0a8e4cec 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -89,10 +89,10 @@ impl<'tcx> PredicateObligation<'tcx> { impl<'tcx> TraitObligation<'tcx> { /// Returns `true` if the trait predicate is considered `const` in its ParamEnv. pub fn is_const(&self) -> bool { - match (self.predicate.skip_binder().constness, self.param_env.constness()) { - (ty::BoundConstness::ConstIfConst, hir::Constness::Const) => true, - _ => false, - } + matches!( + (self.predicate.skip_binder().constness, self.param_env.constness()), + (ty::BoundConstness::ConstIfConst, hir::Constness::Const) + ) } pub fn derived_cause( diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 43e787db41a88..dcdeaf008d671 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -384,13 +384,8 @@ impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> { diag.span_note(span, fluent::mir_build_def_note); } - let is_variant_list_non_exhaustive = match self.ty.kind() { - ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => { - true - } - _ => false, - }; - + let is_variant_list_non_exhaustive = matches!(self.ty.kind(), + ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local()); if is_variant_list_non_exhaustive { diag.note(fluent::mir_build_non_exhaustive_type_note); } else { 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 bac46db2b1e62..0ef48c42f8757 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -671,10 +671,8 @@ fn non_exhaustive_match<'p, 'tcx>( }; }; - let is_variant_list_non_exhaustive = match scrut_ty.kind() { - ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => true, - _ => false, - }; + let is_variant_list_non_exhaustive = matches!(scrut_ty.kind(), + ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local()); adt_defined_here(cx, &mut err, scrut_ty, &witnesses); err.note(&format!( diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 6422b8ac1ba45..f5fef6ad019eb 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2577,14 +2577,12 @@ impl<'a> Parser<'a> { } fn recover_self_param(&mut self) -> bool { - match self - .parse_outer_attributes() - .and_then(|_| self.parse_self_param()) - .map_err(|e| e.cancel()) - { - Ok(Some(_)) => true, - _ => false, - } + matches!( + self.parse_outer_attributes() + .and_then(|_| self.parse_self_param()) + .map_err(|e| e.cancel()), + Ok(Some(_)) + ) } } diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 7a4d53ed8bbe0..adb0d372a40df 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -20,12 +20,10 @@ impl<'a> Parser<'a> { pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool { /// Checks whether the non-terminal may contain a single (non-keyword) identifier. fn may_be_ident(nt: &token::Nonterminal) -> bool { - match *nt { - token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => { - false - } - _ => true, - } + !matches!( + *nt, + token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) + ) } match kind { diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 0c9d306081eb8..c5ec19732be0d 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -663,15 +663,17 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Ident::with_dummy_span(name), Namespace::ValueNS, &parent_scope, - &|res: Res| match res { - Res::Def( - DefKind::Ctor(CtorOf::Variant, CtorKind::Const) - | DefKind::Ctor(CtorOf::Struct, CtorKind::Const) - | DefKind::Const - | DefKind::AssocConst, - _, - ) => true, - _ => false, + &|res: Res| { + matches!( + res, + Res::Def( + DefKind::Ctor(CtorOf::Variant, CtorKind::Const) + | DefKind::Ctor(CtorOf::Struct, CtorKind::Const) + | DefKind::Const + | DefKind::AssocConst, + _, + ) + ) }, ); From 6ef8648a4860e5d6108ebd21839c750de4f79dff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 19:17:08 +0200 Subject: [PATCH 7/9] more clippy fixes: clippy::{iter_cloned_collect, unwarp_or_else_default, option_map_or_none} --- compiler/rustc_hir_analysis/src/check/compare_impl_item.rs | 2 +- compiler/rustc_mir_transform/src/coverage/debug.rs | 6 ++---- compiler/rustc_transmute/src/layout/tree.rs | 2 +- src/librustdoc/clean/auto_trait.rs | 2 +- 4 files changed, 5 insertions(+), 7 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 5d119a7737a4c..863a9977446c1 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -1317,7 +1317,7 @@ fn compare_number_of_generics<'tcx>( impl_count, kind, pluralize!(impl_count), - suffix.unwrap_or_else(String::new), + suffix.unwrap_or_default(), ), ); } diff --git a/compiler/rustc_mir_transform/src/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs index 725883b83fa92..e554c47064680 100644 --- a/compiler/rustc_mir_transform/src/coverage/debug.rs +++ b/compiler/rustc_mir_transform/src/coverage/debug.rs @@ -292,10 +292,8 @@ impl DebugCounters { } pub fn some_block_label(&self, operand: ExpressionOperandId) -> Option<&String> { - self.some_counters.as_ref().map_or(None, |counters| { - counters - .get(&operand) - .map_or(None, |debug_counter| debug_counter.some_block_label.as_ref()) + self.some_counters.as_ref().and_then(|counters| { + counters.get(&operand).and_then(|debug_counter| debug_counter.some_block_label.as_ref()) }) } diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index 2a89494c80b04..a6d88b1342ae8 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -196,7 +196,7 @@ pub(crate) mod rustc { fn from(err: LayoutError<'tcx>) -> Self { match err { LayoutError::Unknown(..) => Self::Unknown, - err @ _ => unimplemented!("{:?}", err), + err => unimplemented!("{:?}", err), } } } diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 9479b3ee0369a..767ea8c3100fa 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -141,7 +141,7 @@ where let f = auto_trait::AutoTraitFinder::new(tcx); debug!("get_auto_trait_impls({:?})", ty); - let auto_traits: Vec<_> = self.cx.auto_traits.iter().copied().collect(); + let auto_traits: Vec<_> = self.cx.auto_traits.to_vec(); let mut auto_traits: Vec = auto_traits .into_iter() .filter_map(|trait_def_id| { From 99fd9cb6971fc68d6865c2e2cf7722030001f609 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 16 Apr 2023 04:01:34 -0700 Subject: [PATCH 8/9] Remove the loop in `Align::from_bytes` Perf is almost certainly irrelevant, but might as well simplify it, since `trailing_zeros` does exactly what's needed. --- compiler/rustc_abi/src/lib.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index b0c0ee942ea8f..7a3defd2a5dc4 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -665,15 +665,12 @@ impl Align { format!("`{}` is too large", align) } - let mut bytes = align; - let mut pow2: u8 = 0; - while (bytes & 1) == 0 { - pow2 += 1; - bytes >>= 1; - } - if bytes != 1 { + let tz = align.trailing_zeros(); + if align != (1 << tz) { return Err(not_power_of_2(align)); } + + let pow2 = tz as u8; if pow2 > Self::MAX.pow2 { return Err(too_large(align)); } From 543f8bc38c78c05319b5774ec2337c6d3c9b434b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 20:18:30 +0200 Subject: [PATCH 9/9] fix clippy::toplevel_ref_arg and ::manual_map --- compiler/rustc_builtin_macros/src/format.rs | 8 +--- compiler/rustc_data_structures/src/sso/map.rs | 7 +--- compiler/rustc_lint/src/unused.rs | 39 ++++++++----------- .../src/const_prop_lint.rs | 2 +- compiler/rustc_parse/src/parser/attr.rs | 6 +-- compiler/rustc_resolve/src/diagnostics.rs | 10 ++--- compiler/rustc_span/src/lib.rs | 7 ++-- compiler/rustc_span/src/source_map.rs | 4 +- .../rustc_trait_selection/src/traits/util.rs | 9 +---- compiler/rustc_ty_utils/src/instance.rs | 11 ++---- .../rustc_ty_utils/src/structural_match.rs | 2 +- src/librustdoc/formats/cache.rs | 7 ++-- 12 files changed, 42 insertions(+), 70 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index f0fc61d7c4f21..f17df5b0a83c7 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -141,13 +141,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult< args: args .named_args() .iter() - .filter_map(|a| { - if let Some(ident) = a.kind.ident() { - Some((a, ident)) - } else { - None - } - }) + .filter_map(|a| a.kind.ident().map(|ident| (a, ident))) .map(|(arg, n)| n.span.to(arg.expr.span)) .collect(), }); diff --git a/compiler/rustc_data_structures/src/sso/map.rs b/compiler/rustc_data_structures/src/sso/map.rs index 89b8c85264969..99581ed237590 100644 --- a/compiler/rustc_data_structures/src/sso/map.rs +++ b/compiler/rustc_data_structures/src/sso/map.rs @@ -256,12 +256,9 @@ impl SsoHashMap { pub fn remove(&mut self, key: &K) -> Option { match self { SsoHashMap::Array(array) => { - if let Some(index) = array.iter().position(|(k, _v)| k == key) { - Some(array.swap_remove(index).1) - } else { - None - } + array.iter().position(|(k, _v)| k == key).map(|index| array.swap_remove(index).1) } + SsoHashMap::Map(map) => map.remove(key), } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 1159d11e5c0c8..80a64e59c0f0e 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -636,20 +636,14 @@ trait UnusedDelimLint { return; } let spans = match value.kind { - ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => { - if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) { - Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi()))) - } else { - None - } - } + ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => block.stmts[0] + .span + .find_ancestor_inside(value.span) + .map(|span| (value.span.with_hi(span.lo()), value.span.with_lo(span.hi()))), ast::ExprKind::Paren(ref expr) => { - let expr_span = expr.span.find_ancestor_inside(value.span); - if let Some(expr_span) = expr_span { - Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi()))) - } else { - None - } + expr.span.find_ancestor_inside(value.span).map(|expr_span| { + (value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())) + }) } _ => return, }; @@ -928,11 +922,10 @@ impl UnusedParens { // Otherwise proceed with linting. _ => {} } - let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) { - Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi()))) - } else { - None - }; + let spans = inner + .span + .find_ancestor_inside(value.span) + .map(|inner| (value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi()))); self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space); } } @@ -1043,11 +1036,11 @@ impl EarlyLintPass for UnusedParens { if self.with_self_ty_parens && b.generic_params.len() > 0 => {} ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {} _ => { - let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) { - Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi()))) - } else { - None - }; + let spans = r + .span + .find_ancestor_inside(ty.span) + .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi()))); + self.emit_unused_delims(cx, ty.span, spans, "type", (false, false)); } } diff --git a/compiler/rustc_mir_transform/src/const_prop_lint.rs b/compiler/rustc_mir_transform/src/const_prop_lint.rs index 699fe44892b2c..3a105a2abaeb9 100644 --- a/compiler/rustc_mir_transform/src/const_prop_lint.rs +++ b/compiler/rustc_mir_transform/src/const_prop_lint.rs @@ -493,7 +493,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { cond: &Operand<'tcx>, location: Location, ) -> Option { - let ref value = self.eval_operand(&cond, location)?; + let value = &self.eval_operand(&cond, location)?; trace!("assertion on {:?} should be {:?}", value, expected); let expected = Scalar::from_bool(expected); diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index e3e7c63e3448c..e1db19557cfe2 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -45,10 +45,10 @@ impl<'a> Parser<'a> { Some(InnerAttrForbiddenReason::AfterOuterDocComment { prev_doc_comment_span: prev_outer_attr_sp.unwrap(), }) - } else if let Some(prev_outer_attr_sp) = prev_outer_attr_sp { - Some(InnerAttrForbiddenReason::AfterOuterAttribute { prev_outer_attr_sp }) } else { - None + prev_outer_attr_sp.map(|prev_outer_attr_sp| { + InnerAttrForbiddenReason::AfterOuterAttribute { prev_outer_attr_sp } + }) }; let inner_parse_policy = InnerAttrPolicy::Forbidden(inner_error_reason); just_parsed_doc_comment = false; diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 0c9d306081eb8..4f8e966ff6672 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1867,15 +1867,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span), _ => None, }; - let suggestion = if let Some(span) = match_span { - Some(( + let suggestion = match_span.map(|span| { + ( vec![(span, String::from(""))], format!("`{}` is defined here, but is not a type", ident), Applicability::MaybeIncorrect, - )) - } else { - None - }; + ) + }); (format!("use of undeclared type `{}`", ident), suggestion) } else { diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index aa8859ed1a358..1e9653d0c5bb8 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1663,10 +1663,11 @@ impl SourceFile { if let Some(ref src) = self.src { Some(Cow::from(get_until_newline(src, begin))) - } else if let Some(src) = self.external_src.borrow().get_source() { - Some(Cow::Owned(String::from(get_until_newline(src, begin)))) } else { - None + self.external_src + .borrow() + .get_source() + .map(|src| Cow::Owned(String::from(get_until_newline(src, begin)))) } } diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 88e3674f89943..29a7e74a81660 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -906,10 +906,8 @@ impl SourceMap { let snippet = if let Some(ref src) = local_begin.sf.src { Some(&src[start_index..]) - } else if let Some(src) = src.get_source() { - Some(&src[start_index..]) } else { - None + src.get_source().map(|src| &src[start_index..]) }; match snippet { diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 20357d4d2501a..7792ceabe7e40 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -243,16 +243,11 @@ pub fn get_vtable_index_of_object_method<'tcx, N>( ) -> Option { // Count number of methods preceding the one we are selecting and // add them to the total offset. - if let Some(index) = tcx - .own_existential_vtable_entries(object.upcast_trait_ref.def_id()) + tcx.own_existential_vtable_entries(object.upcast_trait_ref.def_id()) .iter() .copied() .position(|def_id| def_id == method_def_id) - { - Some(object.vtable_base + index) - } else { - None - } + .map(|index| object.vtable_base + index) } pub fn closure_trait_ref_and_return_type<'tcx>( diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 0a6c118093e50..47cd7af221d26 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -234,15 +234,12 @@ fn resolve_associated_item<'tcx>( _ => None, }, traits::ImplSource::Object(ref data) => { - if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id) - { - Some(Instance { + traits::get_vtable_index_of_object_method(tcx, data, trait_item_id).map(|index| { + Instance { def: ty::InstanceDef::Virtual(trait_item_id, index), substs: rcvr_substs, - }) - } else { - None - } + } + }) } traits::ImplSource::Builtin(..) => { let lang_items = tcx.lang_items(); diff --git a/compiler/rustc_ty_utils/src/structural_match.rs b/compiler/rustc_ty_utils/src/structural_match.rs index a55bb7e7e904d..9cb0fc105943c 100644 --- a/compiler/rustc_ty_utils/src/structural_match.rs +++ b/compiler/rustc_ty_utils/src/structural_match.rs @@ -13,7 +13,7 @@ use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; /// Note that this does *not* recursively check if the substructure of `adt_ty` /// implements the traits. fn has_structural_eq_impls<'tcx>(tcx: TyCtxt<'tcx>, adt_ty: Ty<'tcx>) -> bool { - let ref infcx = tcx.infer_ctxt().build(); + let infcx = &tcx.infer_ctxt().build(); let cause = ObligationCause::dummy(); let ocx = ObligationCtxt::new(infcx); diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index c0329182032ac..841abfab666bf 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -300,14 +300,13 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache), ParentStackItem::Type(item_id) => item_id.as_def_id(), }; - let path = match did.and_then(|did| self.cache.paths.get(&did)) { + let path = did + .and_then(|did| self.cache.paths.get(&did)) // The current stack not necessarily has correlation // for where the type was defined. On the other // hand, `paths` always has the right // information if present. - Some((fqp, _)) => Some(&fqp[..fqp.len() - 1]), - None => None, - }; + .map(|(fqp, _)| &fqp[..fqp.len() - 1]); ((did, path), true) } }