From 32390a0df639dde480f11fb55f37ed39e2a62c5c Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Thu, 22 Jul 2021 21:56:07 +0800 Subject: [PATCH 01/20] move Constness into TraitPredicate --- compiler/rustc_hir/src/hir.rs | 9 +++++++ compiler/rustc_infer/src/traits/util.rs | 2 +- compiler/rustc_lint/src/traits.rs | 2 +- compiler/rustc_lint/src/unused.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_middle/src/ty/error.rs | 12 +++++++--- compiler/rustc_middle/src/ty/flags.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 24 ++++++++++++------- compiler/rustc_middle/src/ty/print/pretty.rs | 7 ++---- compiler/rustc_middle/src/ty/relate.rs | 19 ++++++++++++++- .../rustc_middle/src/ty/structural_impls.rs | 18 +++++++------- compiler/rustc_middle/src/ty/sty.rs | 5 +++- .../src/borrow_check/type_check/mod.rs | 8 +++---- .../src/transform/check_consts/check.rs | 7 ++++-- .../src/transform/function_item_references.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_resolve/src/late/lifetimes.rs | 2 +- .../src/traits/auto_trait.rs | 14 ++++------- .../src/traits/error_reporting/mod.rs | 13 +++++----- .../src/traits/error_reporting/suggestions.rs | 2 +- .../src/traits/fulfill.rs | 4 ++-- .../src/traits/object_safety.rs | 4 ++-- .../traits/query/type_op/prove_predicate.rs | 2 +- .../src/traits/select/mod.rs | 11 ++++----- .../rustc_trait_selection/src/traits/wf.rs | 4 ++-- compiler/rustc_traits/src/chalk/lowering.rs | 8 +++---- compiler/rustc_typeck/src/astconv/mod.rs | 2 +- compiler/rustc_typeck/src/check/_match.rs | 16 ++++++------- compiler/rustc_typeck/src/check/coercion.rs | 4 +--- compiler/rustc_typeck/src/check/dropck.rs | 2 +- .../rustc_typeck/src/check/fn_ctxt/_impl.rs | 2 +- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 4 ++-- .../rustc_typeck/src/check/fn_ctxt/mod.rs | 2 +- .../rustc_typeck/src/check/method/confirm.rs | 2 +- .../rustc_typeck/src/check/method/probe.rs | 2 +- .../rustc_typeck/src/check/method/suggest.rs | 6 ++--- compiler/rustc_typeck/src/check/mod.rs | 2 +- compiler/rustc_typeck/src/collect.rs | 6 ++--- .../rustc_typeck/src/collect/item_bounds.rs | 2 +- .../src/impl_wf_check/min_specialization.rs | 16 ++++++++----- src/librustdoc/clean/auto_trait.rs | 4 ++-- src/librustdoc/clean/mod.rs | 8 +++---- src/librustdoc/clean/simplify.rs | 2 +- .../rfc-2632-const-trait-impl/assoc-type.rs | 2 +- .../clippy_lints/src/future_not_send.rs | 2 +- .../src/needless_pass_by_value.rs | 2 +- .../src/unit_return_expecting_ord.rs | 2 +- .../clippy_utils/src/qualify_min_const_fn.rs | 2 +- src/tools/clippy/clippy_utils/src/ty.rs | 2 +- 49 files changed, 157 insertions(+), 124 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index fe1d190b4ec1a..9e655bc4a7e3e 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2751,6 +2751,15 @@ pub enum Constness { NotConst, } +impl fmt::Display for Constness { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match *self { + Self::Const => "const", + Self::NotConst => "non-const", + }) + } +} + #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] pub struct FnHeader { pub unsafety: Unsafety, diff --git a/compiler/rustc_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index ce1445f8a4746..3139e12116373 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -124,7 +124,7 @@ impl Elaborator<'tcx> { let bound_predicate = obligation.predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateKind::Trait(data) => { // Get predicates declared on the trait. let predicates = tcx.super_predicates_of(data.def_id()); diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index e713ce7c71bec..2c039b6d05d29 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -87,7 +87,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { let predicates = cx.tcx.explicit_predicates_of(item.def_id); for &(predicate, span) in predicates.predicates { let trait_predicate = match predicate.kind().skip_binder() { - Trait(trait_predicate, _constness) => trait_predicate, + Trait(trait_predicate) => trait_predicate, _ => continue, }; let def_id = trait_predicate.trait_ref.def_id; diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 2b580452a60eb..2d2897f3f9899 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -211,7 +211,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { let mut has_emitted = false; for &(predicate, _) in cx.tcx.explicit_item_bounds(def) { // We only look at the `DefId`, so it is safe to skip the binder here. - if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) = + if let ty::PredicateKind::Trait(ref poly_trait_predicate) = predicate.kind().skip_binder() { let def_id = poly_trait_predicate.trait_ref.def_id; diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index ef0392e51970b..106b443ee3c14 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2169,7 +2169,7 @@ impl<'tcx> TyCtxt<'tcx> { let generic_predicates = self.super_predicates_of(trait_did); for (predicate, _) in generic_predicates.predicates { - if let ty::PredicateKind::Trait(data, _) = predicate.kind().skip_binder() { + if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() { if set.insert(data.def_id()) { stack.push(data.def_id()); } diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index f1c7c1ea852a2..3846d9ffdbae5 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -33,6 +33,7 @@ impl ExpectedFound { #[derive(Clone, Debug, TypeFoldable)] pub enum TypeError<'tcx> { Mismatch, + ConstnessMismatch(ExpectedFound), UnsafetyMismatch(ExpectedFound), AbiMismatch(ExpectedFound), Mutability, @@ -106,6 +107,9 @@ impl<'tcx> fmt::Display for TypeError<'tcx> { CyclicTy(_) => write!(f, "cyclic type of infinite size"), CyclicConst(_) => write!(f, "encountered a self-referencing constant"), Mismatch => write!(f, "types differ"), + ConstnessMismatch(values) => { + write!(f, "expected {} fn, found {} fn", values.expected, values.found) + } UnsafetyMismatch(values) => { write!(f, "expected {} fn, found {} fn", values.expected, values.found) } @@ -213,9 +217,11 @@ impl<'tcx> TypeError<'tcx> { pub fn must_include_note(&self) -> bool { use self::TypeError::*; match self { - CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) - | FixedArraySize(_) | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) - | FloatMismatch(_) | VariadicMismatch(_) | TargetFeatureCast(_) => false, + CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_) + | Mismatch | AbiMismatch(_) | FixedArraySize(_) | ArgumentSorts(..) | Sorts(_) + | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_) | TargetFeatureCast(_) => { + false + } Mutability | ArgumentMutability(_) diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 9faa172a4973f..391c8292bd542 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -216,7 +216,7 @@ impl FlagComputation { fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) { match atom { - ty::PredicateKind::Trait(trait_pred, _constness) => { + ty::PredicateKind::Trait(trait_pred) => { self.add_substs(trait_pred.trait_ref.substs); } ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index a6aff42479069..6ea44789c7a38 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -456,7 +456,7 @@ pub enum PredicateKind<'tcx> { /// A trait predicate will have `Constness::Const` if it originates /// from a bound on a `const fn` without the `?const` opt-out (e.g., /// `const fn foobar() {}`). - Trait(TraitPredicate<'tcx>, Constness), + Trait(TraitPredicate<'tcx>), /// `where 'a: 'b` RegionOutlives(RegionOutlivesPredicate<'tcx>), @@ -612,6 +612,11 @@ impl<'tcx> Predicate<'tcx> { #[derive(HashStable, TypeFoldable)] pub struct TraitPredicate<'tcx> { pub trait_ref: TraitRef<'tcx>, + + /// A trait predicate will have `Constness::Const` if it originates + /// from a bound on a `const fn` without the `?const` opt-out (e.g., + /// `const fn foobar() {}`). + pub constness: hir::Constness, } pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>; @@ -745,8 +750,11 @@ impl ToPredicate<'tcx> for PredicateKind<'tcx> { impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness) - .to_predicate(tcx) + PredicateKind::Trait(ty::TraitPredicate { + trait_ref: self.value, + constness: self.constness, + }) + .to_predicate(tcx) } } @@ -754,15 +762,15 @@ impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { self.value .map_bound(|trait_ref| { - PredicateKind::Trait(ty::TraitPredicate { trait_ref }, self.constness) + PredicateKind::Trait(ty::TraitPredicate { trait_ref, constness: self.constness }) }) .to_predicate(tcx) } } -impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { +impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx) + self.map_bound(PredicateKind::Trait).to_predicate(tcx) } } @@ -788,8 +796,8 @@ impl<'tcx> Predicate<'tcx> { pub fn to_opt_poly_trait_ref(self) -> Option>> { let predicate = self.kind(); match predicate.skip_binder() { - PredicateKind::Trait(t, constness) => { - Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) }) + PredicateKind::Trait(t) => { + Some(ConstnessAnd { constness: t.constness, value: predicate.rebind(t.trait_ref) }) } PredicateKind::Projection(..) | PredicateKind::Subtype(..) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index dc94124e62ab6..c96621338f574 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -630,7 +630,7 @@ pub trait PrettyPrinter<'tcx>: for (predicate, _) in bounds { let predicate = predicate.subst(self.tcx(), substs); let bound_predicate = predicate.kind(); - if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() { + if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() { let trait_ref = bound_predicate.rebind(pred.trait_ref); // Don't print +Sized, but rather +?Sized if absent. if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() { @@ -2264,10 +2264,7 @@ define_print_and_forward_display! { ty::PredicateKind<'tcx> { match *self { - ty::PredicateKind::Trait(ref data, constness) => { - if let hir::Constness::Const = constness { - p!("const "); - } + ty::PredicateKind::Trait(ref data) => { p!(print(data)) } ty::PredicateKind::Subtype(predicate) => p!(print(predicate)), diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index a4c36be21992b..8efb88d404063 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -200,6 +200,20 @@ impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> { } } +impl<'tcx> Relate<'tcx> for ast::Constness { + fn relate>( + relation: &mut R, + a: ast::Constness, + b: ast::Constness, + ) -> RelateResult<'tcx, ast::Constness> { + if a != b { + Err(TypeError::ConstnessMismatch(expected_found(relation, a, b))) + } else { + Ok(a) + } + } +} + impl<'tcx> Relate<'tcx> for ast::Unsafety { fn relate>( relation: &mut R, @@ -767,7 +781,10 @@ impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> { a: ty::TraitPredicate<'tcx>, b: ty::TraitPredicate<'tcx>, ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> { - Ok(ty::TraitPredicate { trait_ref: relation.relate(a.trait_ref, b.trait_ref)? }) + Ok(ty::TraitPredicate { + trait_ref: relation.relate(a.trait_ref, b.trait_ref)?, + constness: relation.relate(a.constness, b.constness)?, + }) } } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 7290c41d615df..62397752db2fc 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -155,6 +155,9 @@ impl fmt::Debug for ty::ParamConst { impl fmt::Debug for ty::TraitPredicate<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let hir::Constness::Const = self.constness { + write!(f, "const ")?; + } write!(f, "TraitPredicate({:?})", self.trait_ref) } } @@ -174,12 +177,7 @@ impl fmt::Debug for ty::Predicate<'tcx> { impl fmt::Debug for ty::PredicateKind<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - ty::PredicateKind::Trait(ref a, constness) => { - if let hir::Constness::Const = constness { - write!(f, "const ")?; - } - a.fmt(f) - } + ty::PredicateKind::Trait(ref a) => a.fmt(f), ty::PredicateKind::Subtype(ref pair) => pair.fmt(f), ty::PredicateKind::RegionOutlives(ref pair) => pair.fmt(f), ty::PredicateKind::TypeOutlives(ref pair) => pair.fmt(f), @@ -366,7 +364,8 @@ impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialPredicate<'a> { impl<'a, 'tcx> Lift<'tcx> for ty::TraitPredicate<'a> { type Lifted = ty::TraitPredicate<'tcx>; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option> { - tcx.lift(self.trait_ref).map(|trait_ref| ty::TraitPredicate { trait_ref }) + tcx.lift(self.trait_ref) + .map(|trait_ref| ty::TraitPredicate { trait_ref, constness: self.constness }) } } @@ -419,9 +418,7 @@ impl<'a, 'tcx> Lift<'tcx> for ty::PredicateKind<'a> { type Lifted = ty::PredicateKind<'tcx>; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { match self { - ty::PredicateKind::Trait(data, constness) => { - tcx.lift(data).map(|data| ty::PredicateKind::Trait(data, constness)) - } + ty::PredicateKind::Trait(data) => tcx.lift(data).map(ty::PredicateKind::Trait), ty::PredicateKind::Subtype(data) => tcx.lift(data).map(ty::PredicateKind::Subtype), ty::PredicateKind::RegionOutlives(data) => { tcx.lift(data).map(ty::PredicateKind::RegionOutlives) @@ -584,6 +581,7 @@ impl<'a, 'tcx> Lift<'tcx> for ty::error::TypeError<'a> { Some(match self { Mismatch => Mismatch, + ConstnessMismatch(x) => ConstnessMismatch(x), UnsafetyMismatch(x) => UnsafetyMismatch(x), AbiMismatch(x) => AbiMismatch(x), Mutability => Mutability, diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 6a7e349819afd..a1edb8071c459 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -876,7 +876,10 @@ impl<'tcx> PolyTraitRef<'tcx> { } pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { - self.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }) + self.map_bound(|trait_ref| ty::TraitPredicate { + trait_ref, + constness: hir::Constness::NotConst, + }) } } diff --git a/compiler/rustc_mir/src/borrow_check/type_check/mod.rs b/compiler/rustc_mir/src/borrow_check/type_check/mod.rs index f69d08a6d5942..51a6f5bf1abfb 100644 --- a/compiler/rustc_mir/src/borrow_check/type_check/mod.rs +++ b/compiler/rustc_mir/src/borrow_check/type_check/mod.rs @@ -2688,10 +2688,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { category: ConstraintCategory, ) { self.prove_predicates( - Some(ty::PredicateKind::Trait( - ty::TraitPredicate { trait_ref }, - hir::Constness::NotConst, - )), + Some(ty::PredicateKind::Trait(ty::TraitPredicate { + trait_ref, + constness: hir::Constness::NotConst, + })), locations, category, ); diff --git a/compiler/rustc_mir/src/transform/check_consts/check.rs b/compiler/rustc_mir/src/transform/check_consts/check.rs index 109da59aa4380..48fd63b258ca7 100644 --- a/compiler/rustc_mir/src/transform/check_consts/check.rs +++ b/compiler/rustc_mir/src/transform/check_consts/check.rs @@ -423,7 +423,7 @@ impl Checker<'mir, 'tcx> { ty::PredicateKind::Subtype(_) => { bug!("subtype predicate on function: {:#?}", predicate) } - ty::PredicateKind::Trait(pred, _constness) => { + ty::PredicateKind::Trait(pred) => { if Some(pred.def_id()) == tcx.lang_items().sized_trait() { continue; } @@ -817,7 +817,10 @@ impl Visitor<'tcx> for Checker<'mir, 'tcx> { let obligation = Obligation::new( ObligationCause::dummy(), param_env, - Binder::dummy(TraitPredicate { trait_ref }), + Binder::dummy(TraitPredicate { + trait_ref, + constness: hir::Constness::Const, + }), ); let implsrc = tcx.infer_ctxt().enter(|infcx| { diff --git a/compiler/rustc_mir/src/transform/function_item_references.rs b/compiler/rustc_mir/src/transform/function_item_references.rs index 8d02ac6d9b774..26fe796cb916f 100644 --- a/compiler/rustc_mir/src/transform/function_item_references.rs +++ b/compiler/rustc_mir/src/transform/function_item_references.rs @@ -132,7 +132,7 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option> { - if let ty::PredicateKind::Trait(predicate, _) = bound { + if let ty::PredicateKind::Trait(predicate) = bound { if self.tcx.is_diagnostic_item(sym::pointer_trait, predicate.def_id()) { Some(predicate.trait_ref.self_ty()) } else { diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 1a0510d23cf13..3df8ade216925 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -122,7 +122,7 @@ where fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow { match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ty::TraitPredicate { trait_ref }, _) => { + ty::PredicateKind::Trait(ty::TraitPredicate { trait_ref, constness: _ }) => { self.visit_trait(trait_ref) } ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index e18dae0b8eebb..d79fd910b7e78 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -2657,7 +2657,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| { let bound_predicate = pred.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateKind::Trait(data) => { // The order here needs to match what we would get from `subst_supertrait` let pred_bound_vars = bound_predicate.bound_vars(); let mut all_bound_vars = bound_vars.clone(); diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index f54eb0914a5a7..282502cfa0d3d 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -285,6 +285,7 @@ impl AutoTraitFinder<'tcx> { def_id: trait_did, substs: infcx.tcx.mk_substs_trait(ty, &[]), }, + constness: hir::Constness::NotConst, })); let computed_preds = param_env.caller_bounds().iter(); @@ -344,10 +345,7 @@ impl AutoTraitFinder<'tcx> { Err(SelectionError::Unimplemented) => { if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) { already_visited.remove(&pred); - self.add_user_pred( - &mut user_computed_preds, - pred.without_const().to_predicate(self.tcx), - ); + self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx)); predicates.push_back(pred); } else { debug!( @@ -414,10 +412,8 @@ impl AutoTraitFinder<'tcx> { ) { let mut should_add_new = true; user_computed_preds.retain(|&old_pred| { - if let ( - ty::PredicateKind::Trait(new_trait, _), - ty::PredicateKind::Trait(old_trait, _), - ) = (new_pred.kind().skip_binder(), old_pred.kind().skip_binder()) + if let (ty::PredicateKind::Trait(new_trait), ty::PredicateKind::Trait(old_trait)) = + (new_pred.kind().skip_binder(), old_pred.kind().skip_binder()) { if new_trait.def_id() == old_trait.def_id() { let new_substs = new_trait.trait_ref.substs; @@ -638,7 +634,7 @@ impl AutoTraitFinder<'tcx> { let bound_predicate = predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(p, _) => { + ty::PredicateKind::Trait(p) => { // Add this to `predicates` so that we end up calling `select` // with it. If this predicate ends up being unimplemented, // then `evaluate_predicates` will handle adding it the `ParamEnv` diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index ac07cc1f03439..2f91666ca641d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -277,7 +277,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { let bound_predicate = obligation.predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_predicate, _) => { + ty::PredicateKind::Trait(trait_predicate) => { let trait_predicate = bound_predicate.rebind(trait_predicate); let trait_predicate = self.resolve_vars_if_possible(trait_predicate); @@ -518,8 +518,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ); trait_pred }); - let unit_obligation = - obligation.with(predicate.without_const().to_predicate(tcx)); + let unit_obligation = obligation.with(predicate.to_predicate(tcx)); if self.predicate_may_hold(&unit_obligation) { err.note("this trait is implemented for `()`."); err.note( @@ -1148,7 +1147,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { // FIXME: It should be possible to deal with `ForAll` in a cleaner way. let bound_error = error.kind(); let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) { - (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error, _)) => { + (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error)) => { (cond, bound_error.rebind(error)) } _ => { @@ -1159,7 +1158,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) { let bound_predicate = obligation.predicate.kind(); - if let ty::PredicateKind::Trait(implication, _) = bound_predicate.skip_binder() { + if let ty::PredicateKind::Trait(implication) = bound_predicate.skip_binder() { let error = error.to_poly_trait_ref(); let implication = bound_predicate.rebind(implication.trait_ref); // FIXME: I'm just not taking associated types at all here. @@ -1536,7 +1535,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { let bound_predicate = predicate.kind(); let mut err = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateKind::Trait(data) => { let trait_ref = bound_predicate.rebind(data.trait_ref); debug!("trait_ref {:?}", trait_ref); @@ -1803,7 +1802,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { match (obligation.predicate.kind().skip_binder(), obligation.cause.code.peel_derives()) { ( - ty::PredicateKind::Trait(pred, _), + ty::PredicateKind::Trait(pred), &ObligationCauseCode::BindingObligation(item_def_id, span), ) => (pred, item_def_id, span), _ => return, diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index b6ee51cfc1a47..269560843657d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1386,7 +1386,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // bound was introduced. At least one generator should be present for this diagnostic to be // modified. let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())), + ty::PredicateKind::Trait(p) => (Some(p.trait_ref), Some(p.self_ty())), _ => (None, None), }; let mut generator = None; diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 9ec1dd5c2ee3b..cf50c34530ed2 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -352,7 +352,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { // Evaluation will discard candidates using the leak check. // This means we need to pass it the bound version of our // predicate. - ty::PredicateKind::Trait(trait_ref, _constness) => { + ty::PredicateKind::Trait(trait_ref) => { let trait_obligation = obligation.with(binder.rebind(trait_ref)); self.process_trait_obligation( @@ -388,7 +388,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } }, Some(pred) => match pred { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateKind::Trait(data) => { let trait_obligation = obligation.with(Binder::dummy(data)); self.process_trait_obligation( diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 7ebef7f8883ae..04bc689d51161 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -280,7 +280,7 @@ fn predicate_references_self( let self_ty = tcx.types.self_param; let has_self_ty = |arg: &GenericArg<'_>| arg.walk().any(|arg| arg == self_ty.into()); match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ref data, _) => { + ty::PredicateKind::Trait(ref data) => { // In the case of a trait predicate, we can skip the "self" type. if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None } } @@ -331,7 +331,7 @@ fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool { let predicates = predicates.instantiate_identity(tcx).predicates; elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| { match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ref trait_pred, _) => { + ty::PredicateKind::Trait(ref trait_pred) => { trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0) } ty::PredicateKind::Projection(..) 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 de538c62c5e39..02e9b4d0f0e72 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 @@ -15,7 +15,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { // `&T`, accounts for about 60% percentage of the predicates // we have to prove. No need to canonicalize and all that for // such cases. - if let ty::PredicateKind::Trait(trait_ref, _) = key.value.predicate.kind().skip_binder() { + if let ty::PredicateKind::Trait(trait_ref) = key.value.predicate.kind().skip_binder() { if let Some(sized_def_id) = tcx.lang_items().sized_trait() { if trait_ref.def_id() == sized_def_id { if trait_ref.self_ty().is_trivially_sized(tcx) { diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 95611ebc8188c..1aa4bc0a412ce 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -42,7 +42,7 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::relate::TypeRelation; use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef}; use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate}; -use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, WithConstness}; +use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable}; use rustc_span::symbol::sym; use std::cell::{Cell, RefCell}; @@ -454,7 +454,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let result = ensure_sufficient_stack(|| { let bound_predicate = obligation.predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(t, _) => { + ty::PredicateKind::Trait(t) => { let t = bound_predicate.rebind(t); debug_assert!(!t.has_escaping_bound_vars()); let obligation = obligation.with(t); @@ -762,8 +762,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // if the regions match exactly. let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth); let tcx = self.tcx(); - let cycle = - cycle.map(|stack| stack.obligation.predicate.without_const().to_predicate(tcx)); + let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx)); if self.coinductive_match(cycle) { debug!("evaluate_stack --> recursive, coinductive"); Some(EvaluatedToOk) @@ -873,7 +872,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool { let result = match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()), + ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()), _ => false, }; debug!(?predicate, ?result, "coinductive_predicate"); @@ -1213,7 +1212,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .enumerate() .filter_map(|(idx, bound)| { let bound_predicate = bound.kind(); - if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() { + if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() { let bound = bound_predicate.rebind(pred.trait_ref); if self.infcx.probe(|_| { match self.match_normalize_trait_ref( diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 27c8e00c5596c..9c9664d7b5e84 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -108,7 +108,7 @@ pub fn predicate_obligations<'a, 'tcx>( // It's ok to skip the binder here because wf code is prepared for it match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(t, _) => { + ty::PredicateKind::Trait(t) => { wf.compute_trait_ref(&t.trait_ref, Elaborate::None); } ty::PredicateKind::RegionOutlives(..) => {} @@ -226,7 +226,7 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( } } } - ty::PredicateKind::Trait(pred, _) => { + ty::PredicateKind::Trait(pred) => { // An associated item obligation born out of the `trait` failed to be met. An example // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`. debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred); diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs index a838172d664c3..974755e9e2669 100644 --- a/compiler/rustc_traits/src/chalk/lowering.rs +++ b/compiler/rustc_traits/src/chalk/lowering.rs @@ -87,7 +87,7 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment { chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner))) } - ty::PredicateKind::Trait(predicate, _) => chalk_ir::DomainGoal::FromEnv( + ty::PredicateKind::Trait(predicate) => chalk_ir::DomainGoal::FromEnv( chalk_ir::FromEnv::Trait(predicate.trait_ref.lower_into(interner)), ), ty::PredicateKind::RegionOutlives(predicate) => chalk_ir::DomainGoal::Holds( @@ -137,7 +137,7 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi collect_bound_vars(interner, interner.tcx, self.kind()); let value = match predicate { - ty::PredicateKind::Trait(predicate, _) => { + ty::PredicateKind::Trait(predicate) => { chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)), )) @@ -569,7 +569,7 @@ impl<'tcx> LowerInto<'tcx, Option { + ty::PredicateKind::Trait(predicate) => { Some(chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner))) } ty::PredicateKind::RegionOutlives(predicate) => { @@ -702,7 +702,7 @@ impl<'tcx> LowerInto<'tcx, Option Some(chalk_ir::Binders::new( + ty::PredicateKind::Trait(predicate) => Some(chalk_ir::Binders::new( binders, chalk_solve::rust_ir::InlineBound::TraitBound( predicate.trait_ref.lower_into(interner), diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 92583f2b0ea9b..3f72a431bd155 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -1340,7 +1340,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let bound_predicate = obligation.predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(pred, _) => { + ty::PredicateKind::Trait(pred) => { let pred = bound_predicate.rebind(pred); associated_types.entry(span).or_default().extend( tcx.associated_items(pred.def_id()) diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 10c3a97e73a5a..4f8c8ca899f90 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -606,16 +606,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut suggest_box = !obligations.is_empty(); for o in obligations { match o.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(t, constness) => { - let pred = ty::PredicateKind::Trait( - ty::TraitPredicate { - trait_ref: ty::TraitRef { - def_id: t.def_id(), - substs: self.infcx.tcx.mk_substs_trait(outer_ty, &[]), - }, + ty::PredicateKind::Trait(t) => { + let pred = ty::PredicateKind::Trait(ty::TraitPredicate { + trait_ref: ty::TraitRef { + def_id: t.def_id(), + substs: self.infcx.tcx.mk_substs_trait(outer_ty, &[]), }, - constness, - ); + constness: t.constness, + }); let obl = Obligation::new( o.cause.clone(), self.param_env, diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index a83b39a110834..208eb27c84406 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -587,9 +587,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { debug!("coerce_unsized resolve step: {:?}", obligation); let bound_predicate = obligation.predicate.kind(); let trait_pred = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_pred, _) - if traits.contains(&trait_pred.def_id()) => - { + ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { if unsize_did == trait_pred.def_id() { let self_ty = trait_pred.self_ty(); let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); diff --git a/compiler/rustc_typeck/src/check/dropck.rs b/compiler/rustc_typeck/src/check/dropck.rs index 17f5020300d40..c34dd705bef7b 100644 --- a/compiler/rustc_typeck/src/check/dropck.rs +++ b/compiler/rustc_typeck/src/check/dropck.rs @@ -229,7 +229,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( let predicate = predicate.kind(); let p = p.kind(); match (predicate.skip_binder(), p.skip_binder()) { - (ty::PredicateKind::Trait(a, _), ty::PredicateKind::Trait(b, _)) => { + (ty::PredicateKind::Trait(a), ty::PredicateKind::Trait(b)) => { relator.relate(predicate.rebind(a), p.rebind(b)).is_ok() } (ty::PredicateKind::Projection(a), ty::PredicateKind::Projection(b)) => { diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index b84a79b768c9a..ee226aa82c665 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -796,7 +796,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bound_predicate.rebind(data).required_poly_trait_ref(self.tcx), obligation, )), - ty::PredicateKind::Trait(data, _) => { + ty::PredicateKind::Trait(data) => { Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation)) } ty::PredicateKind::Subtype(..) => None, diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index f65cc429fbd48..9952413353fa9 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -923,7 +923,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; } - if let ty::PredicateKind::Trait(predicate, _) = + if let ty::PredicateKind::Trait(predicate) = error.obligation.predicate.kind().skip_binder() { // Collect the argument position for all arguments that could have caused this @@ -974,7 +974,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let hir::ExprKind::Path(qpath) = &path.kind { if let hir::QPath::Resolved(_, path) = &qpath { for error in errors { - if let ty::PredicateKind::Trait(predicate, _) = + if let ty::PredicateKind::Trait(predicate) = error.obligation.predicate.kind().skip_binder() { // If any of the type arguments in this path segment caused the diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs b/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs index 13686cfec809a..75705e92e54bc 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs @@ -194,7 +194,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { predicates: tcx.arena.alloc_from_iter( self.param_env.caller_bounds().iter().filter_map(|predicate| { match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(data, _) if data.self_ty().is_param(index) => { + ty::PredicateKind::Trait(data) if data.self_ty().is_param(index) => { // HACK(eddyb) should get the original `Span`. let span = tcx.def_span(def_id); Some((predicate, span)) diff --git a/compiler/rustc_typeck/src/check/method/confirm.rs b/compiler/rustc_typeck/src/check/method/confirm.rs index 3aceaba882d6c..88be49e96e7be 100644 --- a/compiler/rustc_typeck/src/check/method/confirm.rs +++ b/compiler/rustc_typeck/src/check/method/confirm.rs @@ -507,7 +507,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { traits::elaborate_predicates(self.tcx, predicates.predicates.iter().copied()) // We don't care about regions here. .filter_map(|obligation| match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(trait_pred, _) if trait_pred.def_id() == sized_def_id => { + ty::PredicateKind::Trait(trait_pred) if trait_pred.def_id() == sized_def_id => { let span = iter::zip(&predicates.predicates, &predicates.spans) .find_map( |(p, span)| { diff --git a/compiler/rustc_typeck/src/check/method/probe.rs b/compiler/rustc_typeck/src/check/method/probe.rs index 9037ffe49a9a2..c6e6c8c5d70e2 100644 --- a/compiler/rustc_typeck/src/check/method/probe.rs +++ b/compiler/rustc_typeck/src/check/method/probe.rs @@ -832,7 +832,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| { let bound_predicate = predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_predicate, _) => { + ty::PredicateKind::Trait(trait_predicate) => { match *trait_predicate.trait_ref.self_ty().kind() { ty::Param(p) if p == param_ty => { Some(bound_predicate.rebind(trait_predicate.trait_ref)) diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index c7a7462668aa5..1d5a9e3e1f968 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -683,7 +683,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut collect_type_param_suggestions = |self_ty: Ty<'tcx>, parent_pred: &ty::Predicate<'tcx>, obligation: &str| { // We don't care about regions here, so it's fine to skip the binder here. - if let (ty::Param(_), ty::PredicateKind::Trait(p, _)) = + if let (ty::Param(_), ty::PredicateKind::Trait(p)) = (self_ty.kind(), parent_pred.kind().skip_binder()) { if let ty::Adt(def, _) = p.trait_ref.self_ty().kind() { @@ -763,7 +763,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bound_span_label(projection_ty.self_ty(), &obligation, &quiet); Some((obligation, projection_ty.self_ty())) } - ty::PredicateKind::Trait(poly_trait_ref, _) => { + ty::PredicateKind::Trait(poly_trait_ref) => { let p = poly_trait_ref.trait_ref; let self_ty = p.self_ty(); let path = p.print_only_trait_path(); @@ -1200,7 +1200,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match p.kind().skip_binder() { // Hide traits if they are present in predicates as they can be fixed without // having to implement them. - ty::PredicateKind::Trait(t, _) => t.def_id() == info.def_id, + ty::PredicateKind::Trait(t) => t.def_id() == info.def_id, ty::PredicateKind::Projection(p) => { p.projection_ty.item_def_id == info.def_id } diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index 92c162c4861b1..d1e583ed1845a 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -689,7 +689,7 @@ fn bounds_from_generic_predicates<'tcx>( debug!("predicate {:?}", predicate); let bound_predicate = predicate.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_predicate, _) => { + ty::PredicateKind::Trait(trait_predicate) => { let entry = types.entry(trait_predicate.self_ty()).or_default(); let def_id = trait_predicate.def_id(); if Some(def_id) != tcx.lang_items().sized_trait() { diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index eb94fde21099b..c16b7bab3a3ef 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -640,7 +640,7 @@ fn type_param_predicates( ) .into_iter() .filter(|(predicate, _)| match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(data, _) => data.self_ty().is_param(index), + ty::PredicateKind::Trait(data) => data.self_ty().is_param(index), _ => false, }), ); @@ -1198,7 +1198,7 @@ fn super_predicates_that_define_assoc_type( // which will, in turn, reach indirect supertraits. for &(pred, span) in superbounds { debug!("superbound: {:?}", pred); - if let ty::PredicateKind::Trait(bound, _) = pred.kind().skip_binder() { + if let ty::PredicateKind::Trait(bound) = pred.kind().skip_binder() { tcx.at(span).super_predicates_of(bound.def_id()); } } @@ -2439,7 +2439,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat .iter() .copied() .filter(|(pred, _)| match pred.kind().skip_binder() { - ty::PredicateKind::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()), + ty::PredicateKind::Trait(tr) => !is_assoc_item_ty(tr.self_ty()), ty::PredicateKind::Projection(proj) => { !is_assoc_item_ty(proj.projection_ty.self_ty()) } diff --git a/compiler/rustc_typeck/src/collect/item_bounds.rs b/compiler/rustc_typeck/src/collect/item_bounds.rs index a5b36445aae2e..1d08c4450afcf 100644 --- a/compiler/rustc_typeck/src/collect/item_bounds.rs +++ b/compiler/rustc_typeck/src/collect/item_bounds.rs @@ -38,7 +38,7 @@ fn associated_type_bounds<'tcx>( let bounds_from_parent = trait_predicates.predicates.iter().copied().filter(|(pred, _)| { match pred.kind().skip_binder() { - ty::PredicateKind::Trait(tr, _) => tr.self_ty() == item_ty, + ty::PredicateKind::Trait(tr) => tr.self_ty() == item_ty, ty::PredicateKind::Projection(proj) => proj.projection_ty.self_ty() == item_ty, ty::PredicateKind::TypeOutlives(outlives) => outlives.0 == item_ty, _ => false, diff --git a/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs b/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs index 505d9a59d9c2f..d5d81603fc516 100644 --- a/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs @@ -366,7 +366,10 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc _ if predicate.is_global() => (), // We allow specializing on explicitly marked traits with no associated // items. - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) => { + ty::PredicateKind::Trait(ty::TraitPredicate { + trait_ref, + constness: hir::Constness::NotConst, + }) => { if !matches!( trait_predicate_kind(tcx, predicate), Some(TraitSpecializationKind::Marker) @@ -376,7 +379,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc span, &format!( "cannot specialize on trait `{}`", - tcx.def_path_str(pred.def_id()), + tcx.def_path_str(trait_ref.def_id), ), ) .emit() @@ -394,10 +397,11 @@ fn trait_predicate_kind<'tcx>( predicate: ty::Predicate<'tcx>, ) -> Option { match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) => { - Some(tcx.trait_def(pred.def_id()).specialization_kind) - } - ty::PredicateKind::Trait(_, hir::Constness::Const) + ty::PredicateKind::Trait(ty::TraitPredicate { + trait_ref, + constness: hir::Constness::NotConst, + }) => Some(tcx.trait_def(trait_ref.def_id).specialization_kind), + ty::PredicateKind::Trait(_) | ty::PredicateKind::RegionOutlives(_) | ty::PredicateKind::TypeOutlives(_) | ty::PredicateKind::Projection(_) diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index e479d162b8ffb..58a87673241f5 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -316,7 +316,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { let bound_predicate = pred.kind(); let tcx = self.cx.tcx; let regions = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(poly_trait_pred, _) => { + ty::PredicateKind::Trait(poly_trait_pred) => { tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_trait_pred)) } ty::PredicateKind::Projection(poly_proj_pred) => { @@ -463,7 +463,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { .filter(|p| { !orig_bounds.contains(p) || match p.kind().skip_binder() { - ty::PredicateKind::Trait(pred, _) => pred.def_id() == sized_trait, + ty::PredicateKind::Trait(pred) => pred.def_id() == sized_trait, _ => false, } }) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 3d65fcedaf4e5..02cfea914209b 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -325,7 +325,7 @@ impl<'a> Clean> for ty::Predicate<'a> { fn clean(&self, cx: &mut DocContext<'_>) -> Option { let bound_predicate = self.kind(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)), + ty::PredicateKind::Trait(pred) => Some(bound_predicate.rebind(pred).clean(cx)), ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx), ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx), ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)), @@ -637,7 +637,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, ty::GenericPredicates<'tcx let param_idx = (|| { let bound_p = p.kind(); match bound_p.skip_binder() { - ty::PredicateKind::Trait(pred, _constness) => { + ty::PredicateKind::Trait(pred) => { if let ty::Param(param) = pred.self_ty().kind() { return Some(param.index); } @@ -1555,9 +1555,7 @@ impl<'tcx> Clean for Ty<'tcx> { .filter_map(|bound| { let bound_predicate = bound.kind(); let trait_ref = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(tr, _constness) => { - bound_predicate.rebind(tr.trait_ref) - } + ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref), ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => { if let Some(r) = reg.clean(cx) { regions.push(GenericBound::Outlives(r)); diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 3ec0a22a2c09a..c0d52d349280f 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -139,7 +139,7 @@ fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) .predicates .iter() .filter_map(|(pred, _)| { - if let ty::PredicateKind::Trait(pred, _) = pred.kind().skip_binder() { + if let ty::PredicateKind::Trait(pred) = pred.kind().skip_binder() { if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None } } else { None diff --git a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs index 4a1bd5da98b8a..fe3ad24be2a94 100644 --- a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs +++ b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs @@ -1,5 +1,5 @@ // ignore-test - +// // FIXME: This test should fail since, within a const impl of `Foo`, the bound on `Foo::Bar` should // require a const impl of `Add` for the associated type. diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index 0be03969bcbe2..3e35ada7b2a1c 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -93,7 +93,7 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { cx.tcx.infer_ctxt().enter(|infcx| { for FulfillmentError { obligation, .. } in send_errors { infcx.maybe_note_obligation_cause_for_async_await(db, &obligation); - if let Trait(trait_pred, _) = obligation.predicate.kind().skip_binder() { + if let Trait(trait_pred) = obligation.predicate.kind().skip_binder() { db.note(&format!( "`{}` doesn't implement `{}`", trait_pred.self_ty(), diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 03eeb54d8d1c2..5e559991c1697 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -121,7 +121,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { .filter_map(|obligation| { // Note that we do not want to deal with qualified predicates here. match obligation.predicate.kind().no_bound_vars() { - Some(ty::PredicateKind::Trait(pred, _)) if pred.def_id() != sized_trait => Some(pred), + Some(ty::PredicateKind::Trait(pred)) if pred.def_id() != sized_trait => Some(pred), _ => None, } }) diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 900d453176071..ee675838c4cb3 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -45,7 +45,7 @@ fn get_trait_predicates_for_trait_id<'tcx>( let mut preds = Vec::new(); for (pred, _) in generics.predicates { if_chain! { - if let PredicateKind::Trait(poly_trait_pred, _) = pred.kind().skip_binder(); + if let PredicateKind::Trait(poly_trait_pred) = pred.kind().skip_binder(); let trait_pred = cx.tcx.erase_late_bound_regions(pred.kind().rebind(poly_trait_pred)); if let Some(trait_def_id) = trait_id; if trait_def_id == trait_pred.trait_ref.def_id; 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 0e6ead675c247..dee9d487c78ea 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 @@ -36,7 +36,7 @@ pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, msrv: Option<&Ru ty::PredicateKind::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate), ty::PredicateKind::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate), ty::PredicateKind::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate), - ty::PredicateKind::Trait(pred, _) => { + ty::PredicateKind::Trait(pred) => { if Some(pred.def_id()) == tcx.lang_items().sized_trait() { continue; } diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index 4f9aaf396b806..a2221a0b283b0 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -157,7 +157,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty::Tuple(substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)), ty::Opaque(ref def_id, _) => { for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) { - if let ty::PredicateKind::Trait(trait_predicate, _) = predicate.kind().skip_binder() { + if let ty::PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() { if must_use_attr(cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() { return true; } From 4c8b6a20a99d3104100492e8c688d41e51aee3da Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Fri, 23 Jul 2021 00:01:47 +0800 Subject: [PATCH 02/20] Filter non-const impls when we expect a const one --- .../src/traits/select/candidate_assembly.rs | 4 +-- .../src/traits/select/mod.rs | 25 ++++++++++++++++--- 2 files changed, 23 insertions(+), 6 deletions(-) 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 c7bf1f2a94319..4312cc9468242 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -144,7 +144,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // Instead, we select the right impl now but report "`Bar` does // not implement `Clone`". if candidates.len() == 1 { - return self.filter_negative_and_reservation_impls(candidates.pop().unwrap()); + return self.filter_impls(candidates.pop().unwrap(), stack.obligation); } // Winnow, but record the exact outcome of evaluation, which @@ -217,7 +217,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } // Just one candidate left. - self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate) + self.filter_impls(candidates.pop().unwrap().candidate, stack.obligation) } pub(super) fn assemble_candidates<'o>( diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 1aa4bc0a412ce..f334452a79126 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1015,13 +1015,30 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { (result, dep_node) } - // Treat negative impls as unimplemented, and reservation impls as ambiguity. - fn filter_negative_and_reservation_impls( + fn filter_impls( &mut self, candidate: SelectionCandidate<'tcx>, + obligation: &TraitObligation<'tcx>, ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { + let tcx = self.tcx(); + // Respect const trait obligations + if let hir::Constness::Const = obligation.predicate.skip_binder().constness { + match candidate { + // const impl + ImplCandidate(def_id) if tcx.impl_constness(def_id) == hir::Constness::Const => {} + // const param + ParamCandidate(ty::ConstnessAnd { constness: hir::Constness::Const, .. }) => {} + // auto trait impl + AutoImplCandidate(..) => {} + // FIXME check if this is right, but this would allow Sized impls + BuiltinCandidate { .. } => {} + _ => { // reject all other types of candidates + return Err(Unimplemented) + } + } + } + // Treat negative impls as unimplemented, and reservation impls as ambiguity. if let ImplCandidate(def_id) = candidate { - let tcx = self.tcx(); match tcx.impl_polarity(def_id) { ty::ImplPolarity::Negative if !self.allow_negative_impls => { return Err(Unimplemented); @@ -1035,7 +1052,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let value = attr.and_then(|a| a.value_str()); if let Some(value) = value { debug!( - "filter_negative_and_reservation_impls: \ + "filter_impls: \ reservation impl ambiguity on {:?}", def_id ); From d356cd10f7380cc3d9e20d50f2d64e4a07ba196c Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Fri, 23 Jul 2021 00:07:56 +0800 Subject: [PATCH 03/20] fmt --- compiler/rustc_trait_selection/src/traits/select/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index f334452a79126..a158a37cd68cd 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1032,8 +1032,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { AutoImplCandidate(..) => {} // FIXME check if this is right, but this would allow Sized impls BuiltinCandidate { .. } => {} - _ => { // reject all other types of candidates - return Err(Unimplemented) + _ => { + // reject all other types of candidates + return Err(Unimplemented); } } } From 7e6db83b1416f1b3c6e81dd011895cf837e3dd23 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 24 Jul 2021 14:34:53 +0800 Subject: [PATCH 04/20] Inherited use constness and assoc change predicate --- Cargo.lock | 4 +-- compiler/rustc_middle/src/ty/assoc.rs | 9 ++++++ .../rustc_typeck/src/check/compare_method.rs | 26 +++++++++++++++-- compiler/rustc_typeck/src/check/inherited.rs | 28 ++++++++++++++++++- 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 940608975c5ec..d080a3f5b26b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -255,7 +255,7 @@ checksum = "81a18687293a1546b67c246452202bbbf143d239cb43494cc163da14979082da" [[package]] name = "cargo" -version = "0.57.0" +version = "0.56.0" dependencies = [ "anyhow", "atty", @@ -388,7 +388,7 @@ dependencies = [ [[package]] name = "cargo-util" -version = "0.1.1" +version = "0.1.0" dependencies = [ "anyhow", "core-foundation", diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index 2d177551664f6..994936351ff8c 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -16,6 +16,15 @@ pub enum AssocItemContainer { } impl AssocItemContainer { + /// Asserts that this is the `DefId` of an associated item declared + /// in an impl, and returns the trait `DefId`. + pub fn assert_impl(&self) -> DefId { + match *self { + ImplContainer(id) => id, + _ => bug!("associated item has wrong container type: {:?}", self), + } + } + /// Asserts that this is the `DefId` of an associated item declared /// in a trait, and returns the trait `DefId`. pub fn assert_trait(&self) -> DefId { diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index d35868881558e..01890f750263d 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -1292,7 +1292,24 @@ pub fn check_type_bounds<'tcx>( }; tcx.infer_ctxt().enter(move |infcx| { - let inh = Inherited::new(infcx, impl_ty.def_id.expect_local()); + // if the item is inside a const impl, we transform the predicates to be const. + let constness = tcx.impl_constness(impl_ty.container.assert_impl()); + let pred_map = match constness { + hir::Constness::NotConst => |p, _| p, + hir::Constness::Const => |p: ty::Predicate<'tcx>, tcx: TyCtxt<'tcx>| { + p.kind() + .map_bound(|kind| match kind { + ty::PredicateKind::Trait(mut tp) => { + tp.constness = hir::Constness::Const; + ty::PredicateKind::Trait(tp) + } + kind => kind, + }) + .to_predicate(tcx) + }, + }; + + let inh = Inherited::with_constness(infcx, impl_ty.def_id.expect_local(), constness); let infcx = &inh.infcx; let mut selcx = traits::SelectionContext::new(&infcx); @@ -1310,7 +1327,7 @@ pub fn check_type_bounds<'tcx>( .explicit_item_bounds(trait_ty.def_id) .iter() .map(|&(bound, span)| { - let concrete_ty_bound = bound.subst(tcx, rebased_substs); + let concrete_ty_bound = pred_map(bound.subst(tcx, rebased_substs), tcx); debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound); traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound) @@ -1328,7 +1345,10 @@ pub fn check_type_bounds<'tcx>( debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate); obligation.predicate = normalized_predicate; - inh.register_predicates(obligations); + inh.register_predicates(obligations.into_iter().map(|mut o| { + o.predicate = pred_map(o.predicate, tcx); + o + })); inh.register_predicate(obligation); } diff --git a/compiler/rustc_typeck/src/check/inherited.rs b/compiler/rustc_typeck/src/check/inherited.rs index fb7beae70ba1e..242edf5396c58 100644 --- a/compiler/rustc_typeck/src/check/inherited.rs +++ b/compiler/rustc_typeck/src/check/inherited.rs @@ -52,6 +52,9 @@ pub struct Inherited<'a, 'tcx> { pub(super) deferred_generator_interiors: RefCell, hir::GeneratorKind)>>, + /// Reports whether this is in a const context. + pub(super) constness: hir::Constness, + pub(super) body_id: Option, } @@ -93,6 +96,12 @@ impl<'tcx> InheritedBuilder<'tcx> { impl Inherited<'a, 'tcx> { pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self { + let tcx = infcx.tcx; + let item_id = tcx.hir().local_def_id_to_hir_id(def_id); + Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness()) + } + + pub(super) fn with_constness(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId, constness: hir::Constness) -> Self { let tcx = infcx.tcx; let item_id = tcx.hir().local_def_id_to_hir_id(def_id); let body_id = tcx.hir().maybe_body_owned_by(item_id); @@ -108,12 +117,29 @@ impl Inherited<'a, 'tcx> { deferred_call_resolutions: RefCell::new(Default::default()), deferred_cast_checks: RefCell::new(Vec::new()), deferred_generator_interiors: RefCell::new(Vec::new()), + constness, body_id, } } - pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) { + #[instrument(level = "debug", skip(self))] + fn transform_predicate(&self, p: &mut ty::Predicate<'tcx>) { + // Don't transform non-const bounds into const bounds, + // but transform const bounds to non-const when we are + // not in a const context. + if let hir::Constness::NotConst = self.constness { + let kind = p.kind(); + if let ty::PredicateKind::Trait(pred) = kind.as_ref().skip_binder() { + let mut pred = *pred; + pred.constness = hir::Constness::NotConst; + *p = kind.rebind(ty::PredicateKind::Trait(pred)).to_predicate(self.tcx); + } + } + } + + pub(super) fn register_predicate(&self, mut obligation: traits::PredicateObligation<'tcx>) { debug!("register_predicate({:?})", obligation); + self.transform_predicate(&mut obligation.predicate); if obligation.has_escaping_bound_vars() { span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation); } From 36ace4c0ada61df5a409a756bb161177876cfde8 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 24 Jul 2021 15:48:51 +0800 Subject: [PATCH 05/20] fmt --- compiler/rustc_trait_selection/src/traits/select/mod.rs | 3 ++- compiler/rustc_typeck/src/check/inherited.rs | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index a158a37cd68cd..be5787cda03f7 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1015,6 +1015,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { (result, dep_node) } + #[instrument(level = "debug", skip(self))] fn filter_impls( &mut self, candidate: SelectionCandidate<'tcx>, @@ -1031,7 +1032,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // auto trait impl AutoImplCandidate(..) => {} // FIXME check if this is right, but this would allow Sized impls - BuiltinCandidate { .. } => {} + // BuiltinCandidate { .. } => {} _ => { // reject all other types of candidates return Err(Unimplemented); diff --git a/compiler/rustc_typeck/src/check/inherited.rs b/compiler/rustc_typeck/src/check/inherited.rs index 242edf5396c58..36c376c7b896e 100644 --- a/compiler/rustc_typeck/src/check/inherited.rs +++ b/compiler/rustc_typeck/src/check/inherited.rs @@ -101,7 +101,11 @@ impl Inherited<'a, 'tcx> { Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness()) } - pub(super) fn with_constness(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId, constness: hir::Constness) -> Self { + pub(super) fn with_constness( + infcx: InferCtxt<'a, 'tcx>, + def_id: LocalDefId, + constness: hir::Constness, + ) -> Self { let tcx = infcx.tcx; let item_id = tcx.hir().local_def_id_to_hir_id(def_id); let body_id = tcx.hir().maybe_body_owned_by(item_id); From 3bab45d2acc24bf21c3fc760de0942b437e1ad54 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 24 Jul 2021 19:12:24 +0800 Subject: [PATCH 06/20] Make selection and evaluation caches use constness --- compiler/rustc_middle/src/traits/select.rs | 4 +- .../src/traits/select/mod.rs | 87 ++++++++++++------- 2 files changed, 59 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_middle/src/traits/select.rs b/compiler/rustc_middle/src/traits/select.rs index ab085175762ab..924568a01a7de 100644 --- a/compiler/rustc_middle/src/traits/select.rs +++ b/compiler/rustc_middle/src/traits/select.rs @@ -12,12 +12,12 @@ use rustc_hir::def_id::DefId; use rustc_query_system::cache::Cache; pub type SelectionCache<'tcx> = Cache< - ty::ParamEnvAnd<'tcx, ty::TraitRef<'tcx>>, + ty::ConstnessAnd>>, SelectionResult<'tcx, SelectionCandidate<'tcx>>, >; pub type EvaluationCache<'tcx> = - Cache>, EvaluationResult>; + Cache>>, EvaluationResult>; /// The selection process begins by considering all impls, where /// clauses, and so forth that might resolve an obligation. Sometimes diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index be5787cda03f7..5321993f0ce8c 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -41,6 +41,7 @@ use rustc_middle::ty::fast_reject; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::relate::TypeRelation; use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef}; +use rustc_middle::ty::WithConstness; use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate}; use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable}; use rustc_span::symbol::sym; @@ -141,7 +142,7 @@ struct TraitObligationStack<'prev, 'tcx> { /// The trait ref from `obligation` but "freshened" with the /// selection-context's freshener. Used to check for recursion. - fresh_trait_ref: ty::PolyTraitRef<'tcx>, + fresh_trait_ref: ty::ConstnessAnd>, /// Starts out equal to `depth` -- if, during evaluation, we /// encounter a cycle, then we will set this flag to the minimum @@ -804,7 +805,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // terms of `Fn` etc, but we could probably make this more // precise still. let unbound_input_types = - stack.fresh_trait_ref.skip_binder().substs.types().any(|ty| ty.is_fresh()); + stack.fresh_trait_ref.value.skip_binder().substs.types().any(|ty| ty.is_fresh()); // This check was an imperfect workaround for a bug in the old // intercrate mode; it should be removed when that goes away. if unbound_input_types && self.intercrate { @@ -925,7 +926,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn check_evaluation_cache( &self, param_env: ty::ParamEnv<'tcx>, - trait_ref: ty::PolyTraitRef<'tcx>, + trait_ref: ty::ConstnessAnd>, ) -> Option { let tcx = self.tcx(); if self.can_use_global_caches(param_env) { @@ -939,7 +940,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn insert_evaluation_cache( &mut self, param_env: ty::ParamEnv<'tcx>, - trait_ref: ty::PolyTraitRef<'tcx>, + trait_ref: ty::ConstnessAnd>, dep_node: DepNodeIndex, result: EvaluationResult, ) { @@ -1024,18 +1025,26 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let tcx = self.tcx(); // Respect const trait obligations if let hir::Constness::Const = obligation.predicate.skip_binder().constness { - match candidate { - // const impl - ImplCandidate(def_id) if tcx.impl_constness(def_id) == hir::Constness::Const => {} - // const param - ParamCandidate(ty::ConstnessAnd { constness: hir::Constness::Const, .. }) => {} - // auto trait impl - AutoImplCandidate(..) => {} - // FIXME check if this is right, but this would allow Sized impls - // BuiltinCandidate { .. } => {} - _ => { - // reject all other types of candidates - return Err(Unimplemented); + if Some(obligation.predicate.skip_binder().trait_ref.def_id) + != tcx.lang_items().sized_trait() + // const Sized bounds are skipped + { + match candidate { + // const impl + ImplCandidate(def_id) + if tcx.impl_constness(def_id) == hir::Constness::Const => {} + // const param + ParamCandidate(ty::ConstnessAnd { + constness: hir::Constness::Const, .. + }) => {} + // auto trait impl + AutoImplCandidate(..) => {} + // FIXME check if this is right, but this would allow Sized impls + // BuiltinCandidate { .. } => {} + _ => { + // reject all other types of candidates + return Err(Unimplemented); + } } } } @@ -1121,13 +1130,19 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> Option>> { let tcx = self.tcx(); - let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref; + let pred = &cache_fresh_trait_pred.skip_binder(); + let trait_ref = pred.trait_ref; if self.can_use_global_caches(param_env) { - if let Some(res) = tcx.selection_cache.get(¶m_env.and(*trait_ref), tcx) { + if let Some(res) = tcx + .selection_cache + .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx) + { return Some(res); } } - self.infcx.selection_cache.get(¶m_env.and(*trait_ref), tcx) + self.infcx + .selection_cache + .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx) } /// Determines whether can we safely cache the result @@ -1164,7 +1179,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>, ) { let tcx = self.tcx(); - let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref; + let pred = cache_fresh_trait_pred.skip_binder(); + let trait_ref = pred.trait_ref; if !self.can_cache_candidate(&candidate) { debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable"); @@ -1178,14 +1194,22 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { if !candidate.needs_infer() { debug!(?trait_ref, ?candidate, "insert_candidate_cache global"); // This may overwrite the cache with the same value. - tcx.selection_cache.insert(param_env.and(trait_ref), dep_node, candidate); + tcx.selection_cache.insert( + param_env.and(trait_ref).with_constness(pred.constness), + dep_node, + candidate, + ); return; } } } debug!(?trait_ref, ?candidate, "insert_candidate_cache local"); - self.infcx.selection_cache.insert(param_env.and(trait_ref), dep_node, candidate); + self.infcx.selection_cache.insert( + param_env.and(trait_ref).with_constness(pred.constness), + dep_node, + candidate, + ); } /// Matches a predicate against the bounds of its self type. @@ -2015,8 +2039,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn match_fresh_trait_refs( &self, - previous: ty::PolyTraitRef<'tcx>, - current: ty::PolyTraitRef<'tcx>, + previous: ty::ConstnessAnd>, + current: ty::ConstnessAnd>, param_env: ty::ParamEnv<'tcx>, ) -> bool { let mut matcher = ty::_match::Match::new(self.tcx(), param_env); @@ -2028,8 +2052,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { previous_stack: TraitObligationStackList<'o, 'tcx>, obligation: &'o TraitObligation<'tcx>, ) -> TraitObligationStack<'o, 'tcx> { - let fresh_trait_ref = - obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener); + let fresh_trait_ref = obligation + .predicate + .to_poly_trait_ref() + .fold_with(&mut self.freshener) + .with_constness(obligation.predicate.skip_binder().constness); let dfn = previous_stack.cache.next_dfn(); let depth = previous_stack.depth() + 1; @@ -2308,7 +2335,7 @@ struct ProvisionalEvaluationCache<'tcx> { /// - then we determine that `E` is in error -- we will then clear /// all cache values whose DFN is >= 4 -- in this case, that /// means the cached value for `F`. - map: RefCell, ProvisionalEvaluation>>, + map: RefCell>, ProvisionalEvaluation>>, } /// A cache value for the provisional cache: contains the depth-first @@ -2340,7 +2367,7 @@ impl<'tcx> ProvisionalEvaluationCache<'tcx> { /// `reached_depth` (from the returned value). fn get_provisional( &self, - fresh_trait_ref: ty::PolyTraitRef<'tcx>, + fresh_trait_ref: ty::ConstnessAnd>, ) -> Option { debug!( ?fresh_trait_ref, @@ -2358,7 +2385,7 @@ impl<'tcx> ProvisionalEvaluationCache<'tcx> { &self, from_dfn: usize, reached_depth: usize, - fresh_trait_ref: ty::PolyTraitRef<'tcx>, + fresh_trait_ref: ty::ConstnessAnd>, result: EvaluationResult, ) { debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional"); @@ -2436,7 +2463,7 @@ impl<'tcx> ProvisionalEvaluationCache<'tcx> { fn on_completion( &self, dfn: usize, - mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult), + mut op: impl FnMut(ty::ConstnessAnd>, EvaluationResult), ) { debug!(?dfn, "on_completion"); From 779eef2dae8b2f01af1dc7c8c677388fa7ba1742 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 24 Jul 2021 20:11:38 +0800 Subject: [PATCH 07/20] Relate impl --- compiler/rustc_middle/src/ty/relate.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 8efb88d404063..9c48f05617e09 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -214,6 +214,19 @@ impl<'tcx> Relate<'tcx> for ast::Constness { } } +impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::ConstnessAnd { + fn relate>( + relation: &mut R, + a: ty::ConstnessAnd, + b: ty::ConstnessAnd, + ) -> RelateResult<'tcx, ty::ConstnessAnd> { + Ok(ty::ConstnessAnd { + constness: relation.relate(a.constness, b.constness)?, + value: relation.relate(a.value, b.value)?, + }) + } +} + impl<'tcx> Relate<'tcx> for ast::Unsafety { fn relate>( relation: &mut R, From a00f2bcf5c8d98852d6cfda2468185eda41ff2ba Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 24 Jul 2021 23:32:43 +0800 Subject: [PATCH 08/20] Try to fix problem --- .../rustc_mir/src/borrow_check/type_check/mod.rs | 5 +++-- compiler/rustc_traits/src/type_op.rs | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_mir/src/borrow_check/type_check/mod.rs b/compiler/rustc_mir/src/borrow_check/type_check/mod.rs index 51a6f5bf1abfb..86dcb9c9c1b7a 100644 --- a/compiler/rustc_mir/src/borrow_check/type_check/mod.rs +++ b/compiler/rustc_mir/src/borrow_check/type_check/mod.rs @@ -1084,11 +1084,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { span_mirbug!( self, user_annotation, - "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}", + "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}", inferred_ty, def_id, user_substs, - terr + self.tcx().type_of(def_id), + terr, ); } } diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index 2c55ea7f5c14e..f4a0cc6767f09 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -6,7 +6,9 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::subst::{GenericArg, Subst, UserSelfTy, UserSubsts}; -use rustc_middle::ty::{self, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable, Variance}; +use rustc_middle::ty::{ + self, FnSig, Lift, PolyFnSig, PredicateKind, Ty, TyCtxt, TypeFoldable, Variance, +}; use rustc_middle::ty::{ParamEnv, ParamEnvAnd, Predicate, ToPredicate}; use rustc_span::DUMMY_SP; use rustc_trait_selection::infer::InferCtxtBuilderExt; @@ -85,7 +87,16 @@ impl AscribeUserTypeCx<'me, 'tcx> { Ok(()) } - fn prove_predicate(&mut self, predicate: Predicate<'tcx>) { + fn prove_predicate(&mut self, mut predicate: Predicate<'tcx>) { + if let PredicateKind::Trait(mut tr) = predicate.kind().skip_binder() { + if let hir::Constness::Const = tr.constness { + // FIXME check if we actually want to prove const predicates inside AscribeUserType + tr.constness = hir::Constness::NotConst; + predicate = + predicate.kind().rebind(PredicateKind::Trait(tr)).to_predicate(self.tcx()); + } + } + self.fulfill_cx.register_predicate_obligation( self.infcx, Obligation::new(ObligationCause::dummy(), self.param_env, predicate), @@ -126,6 +137,7 @@ impl AscribeUserTypeCx<'me, 'tcx> { // outlives" error messages. let instantiated_predicates = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs); + debug!(?instantiated_predicates.predicates); for instantiated_predicate in instantiated_predicates.predicates { let instantiated_predicate = self.normalize(instantiated_predicate); self.prove_predicate(instantiated_predicate); From 01bb3710b5e7114a470f07b6d0463a70ae728607 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 10:52:17 +0800 Subject: [PATCH 09/20] Pass constness to SelectionContext --- compiler/rustc_infer/src/traits/engine.rs | 18 +++++ .../src/traits/fulfill.rs | 26 ++++++++ .../src/traits/select/mod.rs | 65 +++++++++++++------ .../rustc_typeck/src/check/compare_method.rs | 4 +- .../rustc_typeck/src/check/fn_ctxt/_impl.rs | 11 +++- 5 files changed, 101 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index 2710debea9478..d60388b31c13c 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -1,5 +1,6 @@ use crate::infer::InferCtxt; use crate::traits::Obligation; +use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, ToPredicate, Ty, WithConstness}; @@ -49,11 +50,28 @@ pub trait TraitEngine<'tcx>: 'tcx { infcx: &InferCtxt<'_, 'tcx>, ) -> Result<(), Vec>>; + fn select_all_with_constness_or_error( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + _constness: hir::Constness, + ) -> Result<(), Vec>> { + self.select_all_or_error(infcx) + } + fn select_where_possible( &mut self, infcx: &InferCtxt<'_, 'tcx>, ) -> Result<(), Vec>>; + // FIXME this should not provide a default body for chalk as chalk should be updated + fn select_with_constness_where_possible( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + _constness: hir::Constness, + ) -> Result<(), Vec>> { + self.select_where_possible(infcx) + } + fn pending_obligations(&self) -> Vec>; } diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index cf50c34530ed2..4c5d8b5ec7978 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -3,6 +3,7 @@ use rustc_data_structures::obligation_forest::ProcessResult; use rustc_data_structures::obligation_forest::{Error, ForestObligation, Outcome}; use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor}; use rustc_errors::ErrorReported; +use rustc_hir as hir; use rustc_infer::traits::{SelectionError, TraitEngine, TraitEngineExt as _, TraitObligation}; use rustc_middle::mir::abstract_const::NotConstEvaluatable; use rustc_middle::mir::interpret::ErrorHandled; @@ -228,6 +229,22 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { if errors.is_empty() { Ok(()) } else { Err(errors) } } + fn select_all_with_constness_or_error( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + constness: rustc_hir::Constness, + ) -> Result<(), Vec>> { + self.select_with_constness_where_possible(infcx, constness)?; + + let errors: Vec<_> = self + .predicates + .to_errors(CodeAmbiguity) + .into_iter() + .map(to_fulfillment_error) + .collect(); + if errors.is_empty() { Ok(()) } else { Err(errors) } + } + fn select_where_possible( &mut self, infcx: &InferCtxt<'_, 'tcx>, @@ -236,6 +253,15 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { self.select(&mut selcx) } + fn select_with_constness_where_possible( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + constness: hir::Constness, + ) -> Result<(), Vec>> { + let mut selcx = SelectionContext::with_constness(infcx, constness); + self.select(&mut selcx) + } + fn pending_obligations(&self) -> Vec> { self.predicates.map_pending_obligations(|o| o.obligation.clone()) } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 5321993f0ce8c..f7c66f8b2849f 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -130,6 +130,9 @@ pub struct SelectionContext<'cx, 'tcx> { /// and a negative impl allow_negative_impls: bool, + /// Do we only want const impls when we have a const trait predicate? + const_impls_required: bool, + /// The mode that trait queries run in, which informs our error handling /// policy. In essence, canonicalized queries need their errors propagated /// rather than immediately reported because we do not have accurate spans. @@ -221,6 +224,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { intercrate: false, intercrate_ambiguity_causes: None, allow_negative_impls: false, + const_impls_required: false, query_mode: TraitQueryMode::Standard, } } @@ -232,6 +236,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { intercrate: true, intercrate_ambiguity_causes: None, allow_negative_impls: false, + const_impls_required: false, query_mode: TraitQueryMode::Standard, } } @@ -247,6 +252,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { intercrate: false, intercrate_ambiguity_causes: None, allow_negative_impls, + const_impls_required: false, query_mode: TraitQueryMode::Standard, } } @@ -262,10 +268,26 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { intercrate: false, intercrate_ambiguity_causes: None, allow_negative_impls: false, + const_impls_required: false, query_mode, } } + pub fn with_constness( + infcx: &'cx InferCtxt<'cx, 'tcx>, + constness: hir::Constness, + ) -> SelectionContext<'cx, 'tcx> { + SelectionContext { + infcx, + freshener: infcx.freshener_keep_static(), + intercrate: false, + intercrate_ambiguity_causes: None, + allow_negative_impls: false, + const_impls_required: matches!(constness, hir::Constness::Const), + query_mode: TraitQueryMode::Standard, + } + } + /// Enables tracking of intercrate ambiguity causes. These are /// used in coherence to give improved diagnostics. We don't do /// this until we detect a coherence error because it can lead to @@ -1024,26 +1046,29 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { let tcx = self.tcx(); // Respect const trait obligations - if let hir::Constness::Const = obligation.predicate.skip_binder().constness { - if Some(obligation.predicate.skip_binder().trait_ref.def_id) - != tcx.lang_items().sized_trait() - // const Sized bounds are skipped - { - match candidate { - // const impl - ImplCandidate(def_id) - if tcx.impl_constness(def_id) == hir::Constness::Const => {} - // const param - ParamCandidate(ty::ConstnessAnd { - constness: hir::Constness::Const, .. - }) => {} - // auto trait impl - AutoImplCandidate(..) => {} - // FIXME check if this is right, but this would allow Sized impls - // BuiltinCandidate { .. } => {} - _ => { - // reject all other types of candidates - return Err(Unimplemented); + if self.const_impls_required { + if let hir::Constness::Const = obligation.predicate.skip_binder().constness { + if Some(obligation.predicate.skip_binder().trait_ref.def_id) + != tcx.lang_items().sized_trait() + // const Sized bounds are skipped + { + match candidate { + // const impl + ImplCandidate(def_id) + if tcx.impl_constness(def_id) == hir::Constness::Const => {} + // const param + ParamCandidate(ty::ConstnessAnd { + constness: hir::Constness::Const, + .. + }) => {} + // auto trait impl + AutoImplCandidate(..) => {} + // FIXME check if this is right, but this would allow Sized impls + // BuiltinCandidate { .. } => {} + _ => { + // reject all other types of candidates + return Err(Unimplemented); + } } } } diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index 01890f750263d..0ce2746b128a8 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -1354,7 +1354,9 @@ pub fn check_type_bounds<'tcx>( // Check that all obligations are satisfied by the implementation's // version. - if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) { + if let Err(ref errors) = + inh.fulfillment_cx.borrow_mut().select_all_with_constness_or_error(&infcx, constness) + { infcx.report_fulfillment_errors(errors, None, false); return Err(ErrorReported); } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index ee226aa82c665..c13901ae8be2b 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -714,7 +714,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(in super::super) fn select_all_obligations_or_error(&self) { debug!("select_all_obligations_or_error"); - if let Err(errors) = self.fulfillment_cx.borrow_mut().select_all_or_error(&self) { + if let Err(errors) = self + .fulfillment_cx + .borrow_mut() + .select_all_with_constness_or_error(&self, self.inh.constness) + { self.report_fulfillment_errors(&errors, self.inh.body_id, false); } } @@ -725,7 +729,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fallback_has_occurred: bool, mutate_fulfillment_errors: impl Fn(&mut Vec>), ) { - let result = self.fulfillment_cx.borrow_mut().select_where_possible(self); + let result = self + .fulfillment_cx + .borrow_mut() + .select_with_constness_where_possible(self, self.inh.constness); if let Err(mut errors) = result { mutate_fulfillment_errors(&mut errors); self.report_fulfillment_errors(&errors, self.inh.body_id, fallback_has_occurred); From bcf0e2f52849dc5d23cde3df3d18a3524ead9629 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 11:13:23 +0800 Subject: [PATCH 10/20] Fix assoc-type test --- .../src/traits/query/evaluate_obligation.rs | 9 +++++++++ .../ui/rfc-2632-const-trait-impl/assoc-type.rs | 7 ++----- .../assoc-type.stderr | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr 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 2dc48e47efccd..8cc57f952ad4b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -1,3 +1,6 @@ +use rustc_hir as hir; +use rustc_middle::ty::PredicateKind; + use crate::infer::canonical::OriginalQueryValues; use crate::infer::InferCtxt; use crate::traits::{ @@ -46,6 +49,12 @@ impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, ) -> bool { + if let PredicateKind::Trait(pred) = obligation.predicate.kind().skip_binder() { + if let hir::Constness::Const = pred.constness { + // do not evaluate to holds when we have a const predicate. + return false; + } + } self.evaluate_obligation_no_overflow(obligation).must_apply_considering_regions() } diff --git a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs index fe3ad24be2a94..8d72adb6b61ed 100644 --- a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs +++ b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs @@ -1,8 +1,4 @@ -// ignore-test -// -// FIXME: This test should fail since, within a const impl of `Foo`, the bound on `Foo::Bar` should -// require a const impl of `Add` for the associated type. - +// FIXME(fee1-dead): this should have a better error message #![feature(const_trait_impl)] struct NonConstAdd(i32); @@ -21,6 +17,7 @@ trait Foo { impl const Foo for NonConstAdd { type Bar = NonConstAdd; + //~^ ERROR } fn main() {} diff --git a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr new file mode 100644 index 0000000000000..1fdc963e7b2db --- /dev/null +++ b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr @@ -0,0 +1,18 @@ +error[E0277]: cannot add `NonConstAdd` to `NonConstAdd` + --> $DIR/assoc-type.rs:19:5 + | +LL | type Bar: std::ops::Add; + | ------------- required by this bound in `Foo::Bar` +... +LL | type Bar = NonConstAdd; + | ^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `NonConstAdd + NonConstAdd` + | + = help: the trait `Add` is not implemented for `NonConstAdd` +help: consider introducing a `where` bound, but there might be an alternative better way to express this requirement + | +LL | impl const Foo for NonConstAdd where NonConstAdd: Add { + | ^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. From c6d0a20f7baae2cec4488195d4ca873f10b0f63b Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 11:34:43 +0800 Subject: [PATCH 11/20] handle the case when container is not impl --- compiler/rustc_middle/src/ty/assoc.rs | 8 +++----- compiler/rustc_typeck/src/check/compare_method.rs | 7 ++++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index 994936351ff8c..5cb2b90fe1116 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -16,12 +16,10 @@ pub enum AssocItemContainer { } impl AssocItemContainer { - /// Asserts that this is the `DefId` of an associated item declared - /// in an impl, and returns the trait `DefId`. - pub fn assert_impl(&self) -> DefId { + pub fn impl_def_id(&self) -> Option { match *self { - ImplContainer(id) => id, - _ => bug!("associated item has wrong container type: {:?}", self), + ImplContainer(id) => Some(id), + _ => None, } } diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index 0ce2746b128a8..a2ffb30f43bd7 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -1293,7 +1293,12 @@ pub fn check_type_bounds<'tcx>( tcx.infer_ctxt().enter(move |infcx| { // if the item is inside a const impl, we transform the predicates to be const. - let constness = tcx.impl_constness(impl_ty.container.assert_impl()); + let constness = impl_ty + .container + .impl_def_id() + .map(|did| tcx.impl_constness(did)) + .unwrap_or(hir::Constness::NotConst); + let pred_map = match constness { hir::Constness::NotConst => |p, _| p, hir::Constness::Const => |p: ty::Predicate<'tcx>, tcx: TyCtxt<'tcx>| { From 7106f8d8ee2574c4fbd9b89e76bc1d177e867876 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 12:06:32 +0800 Subject: [PATCH 12/20] Don't transform predicates in Inherited --- compiler/rustc_typeck/src/check/inherited.rs | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/compiler/rustc_typeck/src/check/inherited.rs b/compiler/rustc_typeck/src/check/inherited.rs index 36c376c7b896e..9d9c77ec072b8 100644 --- a/compiler/rustc_typeck/src/check/inherited.rs +++ b/compiler/rustc_typeck/src/check/inherited.rs @@ -126,24 +126,8 @@ impl Inherited<'a, 'tcx> { } } - #[instrument(level = "debug", skip(self))] - fn transform_predicate(&self, p: &mut ty::Predicate<'tcx>) { - // Don't transform non-const bounds into const bounds, - // but transform const bounds to non-const when we are - // not in a const context. - if let hir::Constness::NotConst = self.constness { - let kind = p.kind(); - if let ty::PredicateKind::Trait(pred) = kind.as_ref().skip_binder() { - let mut pred = *pred; - pred.constness = hir::Constness::NotConst; - *p = kind.rebind(ty::PredicateKind::Trait(pred)).to_predicate(self.tcx); - } - } - } - - pub(super) fn register_predicate(&self, mut obligation: traits::PredicateObligation<'tcx>) { + pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) { debug!("register_predicate({:?})", obligation); - self.transform_predicate(&mut obligation.predicate); if obligation.has_escaping_bound_vars() { span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation); } From 6b6ad781f8cae57aef80d35b1c5b7f36f239ed62 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 12:06:55 +0800 Subject: [PATCH 13/20] Fix call-generic-method-nonconst test --- compiler/rustc_hir/src/hir.rs | 6 +++++- .../call-generic-method-nonconst.rs | 4 +--- .../call-generic-method-nonconst.stderr | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.stderr diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 9e655bc4a7e3e..9fc39afac9f8b 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3261,7 +3261,7 @@ impl<'hir> Node<'hir> { } } - /// Returns `Constness::Const` when this node is a const fn/impl. + /// Returns `Constness::Const` when this node is a const fn/impl/item. pub fn constness(&self) -> Constness { match self { Node::Item(Item { @@ -3278,6 +3278,10 @@ impl<'hir> Node<'hir> { }) | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness, + Node::Item(Item { kind: ItemKind::Const(..), .. }) + | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. }) + | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const, + _ => Constness::NotConst, } } diff --git a/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.rs b/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.rs index 087f8fbdcd1ea..8343974f8c7e7 100644 --- a/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.rs +++ b/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.rs @@ -1,7 +1,5 @@ -// FIXME(jschievink): this is not rejected correctly (only when the non-const impl is actually used) -// ignore-test - #![feature(const_trait_impl)] +#![feature(const_fn_trait_bound)] struct S; diff --git a/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.stderr b/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.stderr new file mode 100644 index 0000000000000..75c7cab362147 --- /dev/null +++ b/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-nonconst.stderr @@ -0,0 +1,14 @@ +error[E0277]: can't compare `S` with `S` + --> $DIR/call-generic-method-nonconst.rs:19:34 + | +LL | const fn equals_self(t: &T) -> bool { + | --------- required by this bound in `equals_self` +... +LL | pub const EQ: bool = equals_self(&S); + | ^^ no implementation for `S == S` + | + = help: the trait `PartialEq` is not implemented for `S` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. From 869daad8fce326a4a6976cbd51964da5efacec28 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 12:29:18 +0800 Subject: [PATCH 14/20] Fix tests --- compiler/rustc_trait_selection/src/traits/select/mod.rs | 5 +++-- src/test/ui/consts/const-eval/issue-49296.rs | 4 +++- src/test/ui/consts/const-eval/issue-49296.stderr | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index f7c66f8b2849f..4c7ee5382d013 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1063,8 +1063,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }) => {} // auto trait impl AutoImplCandidate(..) => {} - // FIXME check if this is right, but this would allow Sized impls - // BuiltinCandidate { .. } => {} + // generator, this will raise error in other places + // or ignore error with const_async_blocks feature + GeneratorCandidate => {} _ => { // reject all other types of candidates return Err(Unimplemented); diff --git a/src/test/ui/consts/const-eval/issue-49296.rs b/src/test/ui/consts/const-eval/issue-49296.rs index ba0885532f113..bb8113e53f9c1 100644 --- a/src/test/ui/consts/const-eval/issue-49296.rs +++ b/src/test/ui/consts/const-eval/issue-49296.rs @@ -1,8 +1,10 @@ // issue-49296: Unsafe shenigans in constants can result in missing errors #![feature(const_fn_trait_bound)] +#![feature(const_trait_bound_opt_out)] +#![allow(incomplete_features)] -const unsafe fn transmute(t: T) -> U { +const unsafe fn transmute(t: T) -> U { #[repr(C)] union Transmute { from: T, diff --git a/src/test/ui/consts/const-eval/issue-49296.stderr b/src/test/ui/consts/const-eval/issue-49296.stderr index e87ef160b8278..28fdcb7c48637 100644 --- a/src/test/ui/consts/const-eval/issue-49296.stderr +++ b/src/test/ui/consts/const-eval/issue-49296.stderr @@ -1,5 +1,5 @@ error[E0080]: evaluation of constant value failed - --> $DIR/issue-49296.rs:18:16 + --> $DIR/issue-49296.rs:20:16 | LL | const X: u64 = *wat(42); | ^^^^^^^^ pointer to alloc2 was dereferenced after this allocation got freed From 7ea0280aa90256317c3b3cf8b13f47a4c5968dd0 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 14:04:55 +0800 Subject: [PATCH 15/20] Moved ui test --- .../alloc/src/collections/btree/map/tests.rs | 7 --- .../alloc/src/collections/btree/set/tests.rs | 7 --- library/alloc/tests/const_fns.rs | 53 +++++++++++++++++++ library/alloc/tests/lib.rs | 3 ++ src/test/ui/collections-const-new.rs | 20 ------- 5 files changed, 56 insertions(+), 34 deletions(-) create mode 100644 library/alloc/tests/const_fns.rs delete mode 100644 src/test/ui/collections-const-new.rs diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index 1e61692b7c63c..17e538483431c 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -1786,13 +1786,6 @@ fn test_ord_absence() { } } -#[allow(dead_code)] -fn test_const() { - const MAP: &'static BTreeMap<(), ()> = &BTreeMap::new(); - const LEN: usize = MAP.len(); - const IS_EMPTY: bool = MAP.is_empty(); -} - #[test] fn test_occupied_entry_key() { let mut a = BTreeMap::new(); diff --git a/library/alloc/src/collections/btree/set/tests.rs b/library/alloc/src/collections/btree/set/tests.rs index de7a10dca7b8c..5d590a26281d2 100644 --- a/library/alloc/src/collections/btree/set/tests.rs +++ b/library/alloc/src/collections/btree/set/tests.rs @@ -16,13 +16,6 @@ fn test_clone_eq() { assert_eq!(m.clone(), m); } -#[allow(dead_code)] -fn test_const() { - const SET: &'static BTreeSet<()> = &BTreeSet::new(); - const LEN: usize = SET.len(); - const IS_EMPTY: bool = SET.is_empty(); -} - #[test] fn test_iter_min_max() { let mut a = BTreeSet::new(); diff --git a/library/alloc/tests/const_fns.rs b/library/alloc/tests/const_fns.rs new file mode 100644 index 0000000000000..02e8f8f40228f --- /dev/null +++ b/library/alloc/tests/const_fns.rs @@ -0,0 +1,53 @@ +// Test several functions can be used for constants +// 1. Vec::new() +// 2. String::new() +// 3. BTreeMap::new() +// 4. BTreeSet::new() + +#[allow(dead_code)] +pub const MY_VEC: Vec = Vec::new(); + +#[allow(dead_code)] +pub const MY_STRING: String = String::new(); + +// FIXME remove this struct once we put `K: ?const Ord` on BTreeMap::new. +#[derive(PartialEq, Eq, PartialOrd)] +pub struct MyType; + +impl const Ord for MyType { + fn cmp(&self, _: &Self) -> Ordering { + Ordering::Equal + } + + fn max(self, _: Self) -> Self { + Self + } + + fn min(self, _: Self) -> Self { + Self + } + + fn clamp(self, _: Self, _: Self) -> Self { + Self + } +} + +use core::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; + +pub const MY_BTREEMAP: BTreeMap = BTreeMap::new(); +pub const MAP: &'static BTreeMap = &MY_BTREEMAP; +pub const MAP_LEN: usize = MAP.len(); +pub const MAP_IS_EMPTY: bool = MAP.is_empty(); + +pub const MY_BTREESET: BTreeSet = BTreeSet::new(); +pub const SET: &'static BTreeSet = &MY_BTREESET; +pub const SET_LEN: usize = SET.len(); +pub const SET_IS_EMPTY: bool = SET.is_empty(); + +#[test] +fn test_const() { + assert_eq!(MAP_LEN, 0); + assert_eq!(SET_LEN, 0); + assert!(MAP_IS_EMPTY && SET_IS_EMPTY) +} diff --git a/library/alloc/tests/lib.rs b/library/alloc/tests/lib.rs index 8fca2662fc304..7284c05d5ff16 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloc/tests/lib.rs @@ -23,6 +23,8 @@ #![feature(slice_partition_dedup)] #![feature(vec_spare_capacity)] #![feature(string_remove_matches)] +#![feature(const_btree_new)] +#![feature(const_trait_impl)] use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -32,6 +34,7 @@ mod binary_heap; mod borrow; mod boxed; mod btree_set_hash; +mod const_fns; mod cow_str; mod fmt; mod heap; diff --git a/src/test/ui/collections-const-new.rs b/src/test/ui/collections-const-new.rs deleted file mode 100644 index 978f25f9a9344..0000000000000 --- a/src/test/ui/collections-const-new.rs +++ /dev/null @@ -1,20 +0,0 @@ -// check-pass - -// Test several functions can be used for constants -// 1. Vec::new() -// 2. String::new() -// 3. BTreeMap::new() -// 4. BTreeSet::new() - -#![feature(const_btree_new)] - -const MY_VEC: Vec = Vec::new(); - -const MY_STRING: String = String::new(); - -use std::collections::{BTreeMap, BTreeSet}; -const MY_BTREEMAP: BTreeMap = BTreeMap::new(); - -const MY_BTREESET: BTreeSet = BTreeSet::new(); - -fn main() {} From 8c2a1e8e432d092896cf0487eca5de324fc06bfc Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 16:53:36 +0800 Subject: [PATCH 16/20] allow incomplete features for now --- library/alloc/tests/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/alloc/tests/lib.rs b/library/alloc/tests/lib.rs index 7284c05d5ff16..f7d68b5a89e99 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloc/tests/lib.rs @@ -25,6 +25,8 @@ #![feature(string_remove_matches)] #![feature(const_btree_new)] #![feature(const_trait_impl)] +// FIXME remove this when const_trait_impl is not incomplete anymore +#![allow(incomplete_features)] use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; From 1fa712d0ba4e1db6fa22cad00182d009afeb7770 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 17:25:01 +0800 Subject: [PATCH 17/20] Make assoc types work with `?const `opt=out --- compiler/rustc_hir/src/hir.rs | 10 ++++++-- .../rustc_typeck/src/check/compare_method.rs | 23 ++----------------- .../rustc_typeck/src/check/fn_ctxt/mod.rs | 2 +- compiler/rustc_typeck/src/check/inherited.rs | 2 +- compiler/rustc_typeck/src/collect.rs | 2 +- .../rfc-2632-const-trait-impl/assoc-type.rs | 10 ++++++++ .../assoc-type.stderr | 2 +- 7 files changed, 24 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 9fc39afac9f8b..3879d6052922a 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3261,8 +3261,13 @@ impl<'hir> Node<'hir> { } } - /// Returns `Constness::Const` when this node is a const fn/impl/item. - pub fn constness(&self) -> Constness { + /// Returns `Constness::Const` when this node is a const fn/impl/item, + /// + /// HACK(fee1-dead): or an associated type in a trait. This works because + /// only typeck cares about const trait predicates, so although the predicates + /// query would return const predicates when it does not need to be const, + /// it wouldn't have any effect. + pub fn constness_for_typeck(&self) -> Constness { match self { Node::Item(Item { kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..), @@ -3280,6 +3285,7 @@ impl<'hir> Node<'hir> { Node::Item(Item { kind: ItemKind::Const(..), .. }) | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. }) + | Node::TraitItem(TraitItem { kind: TraitItemKind::Type(..), .. }) | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const, _ => Constness::NotConst, diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index a2ffb30f43bd7..316a097556aec 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -1292,28 +1292,12 @@ pub fn check_type_bounds<'tcx>( }; tcx.infer_ctxt().enter(move |infcx| { - // if the item is inside a const impl, we transform the predicates to be const. let constness = impl_ty .container .impl_def_id() .map(|did| tcx.impl_constness(did)) .unwrap_or(hir::Constness::NotConst); - let pred_map = match constness { - hir::Constness::NotConst => |p, _| p, - hir::Constness::Const => |p: ty::Predicate<'tcx>, tcx: TyCtxt<'tcx>| { - p.kind() - .map_bound(|kind| match kind { - ty::PredicateKind::Trait(mut tp) => { - tp.constness = hir::Constness::Const; - ty::PredicateKind::Trait(tp) - } - kind => kind, - }) - .to_predicate(tcx) - }, - }; - let inh = Inherited::with_constness(infcx, impl_ty.def_id.expect_local(), constness); let infcx = &inh.infcx; let mut selcx = traits::SelectionContext::new(&infcx); @@ -1332,7 +1316,7 @@ pub fn check_type_bounds<'tcx>( .explicit_item_bounds(trait_ty.def_id) .iter() .map(|&(bound, span)| { - let concrete_ty_bound = pred_map(bound.subst(tcx, rebased_substs), tcx); + let concrete_ty_bound = bound.subst(tcx, rebased_substs); debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound); traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound) @@ -1350,10 +1334,7 @@ pub fn check_type_bounds<'tcx>( debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate); obligation.predicate = normalized_predicate; - inh.register_predicates(obligations.into_iter().map(|mut o| { - o.predicate = pred_map(o.predicate, tcx); - o - })); + inh.register_predicates(obligations); inh.register_predicate(obligation); } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs b/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs index 75705e92e54bc..c0ecee155c6dd 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs @@ -174,7 +174,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { } fn default_constness_for_trait_bounds(&self) -> hir::Constness { - self.tcx.hir().get(self.body_id).constness() + self.tcx.hir().get(self.body_id).constness_for_typeck() } fn get_type_parameter_bounds( diff --git a/compiler/rustc_typeck/src/check/inherited.rs b/compiler/rustc_typeck/src/check/inherited.rs index 9d9c77ec072b8..6006c8f7513d7 100644 --- a/compiler/rustc_typeck/src/check/inherited.rs +++ b/compiler/rustc_typeck/src/check/inherited.rs @@ -98,7 +98,7 @@ impl Inherited<'a, 'tcx> { pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self { let tcx = infcx.tcx; let item_id = tcx.hir().local_def_id_to_hir_id(def_id); - Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness()) + Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck()) } pub(super) fn with_constness( diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index c16b7bab3a3ef..9fbf5ab85334f 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -364,7 +364,7 @@ impl AstConv<'tcx> for ItemCtxt<'tcx> { } fn default_constness_for_trait_bounds(&self) -> hir::Constness { - self.node().constness() + self.node().constness_for_typeck() } fn get_type_parameter_bounds( diff --git a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs index 8d72adb6b61ed..1dbd000afd73e 100644 --- a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs +++ b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs @@ -1,5 +1,7 @@ // FIXME(fee1-dead): this should have a better error message #![feature(const_trait_impl)] +#![feature(const_trait_bound_opt_out)] +#![allow(incomplete_features)] struct NonConstAdd(i32); @@ -20,4 +22,12 @@ impl const Foo for NonConstAdd { //~^ ERROR } +trait Baz { + type Qux: ?const std::ops::Add; +} + +impl const Baz for NonConstAdd { + type Qux = NonConstAdd; // OK +} + fn main() {} diff --git a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr index 1fdc963e7b2db..0cbeb71d23538 100644 --- a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr +++ b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr @@ -1,5 +1,5 @@ error[E0277]: cannot add `NonConstAdd` to `NonConstAdd` - --> $DIR/assoc-type.rs:19:5 + --> $DIR/assoc-type.rs:21:5 | LL | type Bar: std::ops::Add; | ------------- required by this bound in `Foo::Bar` From 54d4fc245a7290c40479f48f5a6158525db38b4f Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 26 Jul 2021 18:02:18 +0800 Subject: [PATCH 18/20] Bless test --- .../projection-bound-cycle-generic.stderr | 4 ++-- .../ui/generic-associated-types/projection-bound-cycle.stderr | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/ui/generic-associated-types/projection-bound-cycle-generic.stderr b/src/test/ui/generic-associated-types/projection-bound-cycle-generic.stderr index 345e2b3fcb12c..e7f801a7bd4b1 100644 --- a/src/test/ui/generic-associated-types/projection-bound-cycle-generic.stderr +++ b/src/test/ui/generic-associated-types/projection-bound-cycle-generic.stderr @@ -1,8 +1,8 @@ error[E0275]: overflow evaluating the requirement `::Item: Sized` --> $DIR/projection-bound-cycle-generic.rs:44:18 | -LL | struct OnlySized where T: Sized { f: T } - | - required by this bound in `OnlySized` +LL | type Item: Sized where ::Item: Sized; + | ----- required by this bound in `Foo::Item` ... LL | type Assoc = OnlySized<::Item>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/test/ui/generic-associated-types/projection-bound-cycle.stderr b/src/test/ui/generic-associated-types/projection-bound-cycle.stderr index eefc09fa78863..67195c65d36e6 100644 --- a/src/test/ui/generic-associated-types/projection-bound-cycle.stderr +++ b/src/test/ui/generic-associated-types/projection-bound-cycle.stderr @@ -1,8 +1,8 @@ error[E0275]: overflow evaluating the requirement `::Item: Sized` --> $DIR/projection-bound-cycle.rs:46:18 | -LL | struct OnlySized where T: Sized { f: T } - | - required by this bound in `OnlySized` +LL | type Item: Sized where ::Item: Sized; + | ----- required by this bound in `Foo::Item` ... LL | type Assoc = OnlySized<::Item>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ From 2931a9df2f5813568537d79fe003cb94f7565c41 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Tue, 27 Jul 2021 09:51:57 +0800 Subject: [PATCH 19/20] make check less conservative and add explanation --- .../rustc_trait_selection/src/traits/fulfill.rs | 14 ++++++++++++-- .../src/traits/query/evaluate_obligation.rs | 9 --------- .../rustc_trait_selection/src/traits/select/mod.rs | 12 ++++++++++++ 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 4c5d8b5ec7978..7048f0dbedcb6 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -649,7 +649,12 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { if obligation.predicate.is_global() { // no type variables present, can use evaluation for better caching. // FIXME: consider caching errors too. - if infcx.predicate_must_hold_considering_regions(obligation) { + // + // If the predicate is considered const, then we cannot use this because + // it will cause false negatives in the ui tests. + if !self.selcx.is_predicate_const(obligation.predicate) + && infcx.predicate_must_hold_considering_regions(obligation) + { debug!( "selecting trait at depth {} evaluated to holds", obligation.recursion_depth @@ -703,7 +708,12 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { if obligation.predicate.is_global() { // no type variables present, can use evaluation for better caching. // FIXME: consider caching errors too. - if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) { + // + // If the predicate is considered const, then we cannot use this because + // it will cause false negatives in the ui tests. + if !self.selcx.is_predicate_const(obligation.predicate) + && self.selcx.infcx().predicate_must_hold_considering_regions(obligation) + { return ProcessResult::Changed(vec![]); } else { tracing::debug!("Does NOT hold: {:?}", obligation); 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 8cc57f952ad4b..2dc48e47efccd 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -1,6 +1,3 @@ -use rustc_hir as hir; -use rustc_middle::ty::PredicateKind; - use crate::infer::canonical::OriginalQueryValues; use crate::infer::InferCtxt; use crate::traits::{ @@ -49,12 +46,6 @@ impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, ) -> bool { - if let PredicateKind::Trait(pred) = obligation.predicate.kind().skip_binder() { - if let hir::Constness::Const = pred.constness { - // do not evaluate to holds when we have a const predicate. - return false; - } - } self.evaluate_obligation_no_overflow(obligation).must_apply_considering_regions() } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 4c7ee5382d013..dcf5ac63b78ea 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -316,6 +316,18 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { self.infcx.tcx } + /// returns `true` if the predicate is considered `const` to + /// this selection context. + pub fn is_predicate_const(&self, pred: ty::Predicate<'_>) -> bool { + match pred.kind().skip_binder() { + ty::PredicateKind::Trait(ty::TraitPredicate { + constness: hir::Constness::Const, + .. + }) if self.const_impls_required => true, + _ => false, + } + } + /////////////////////////////////////////////////////////////////////////// // Selection // From 74627c17c5fab9de9d634ad29166000d127170ca Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Fri, 13 Aug 2021 11:30:33 +0000 Subject: [PATCH 20/20] Fix Cargo.lock and ui test --- Cargo.lock | 4 ++-- src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d080a3f5b26b7..940608975c5ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -255,7 +255,7 @@ checksum = "81a18687293a1546b67c246452202bbbf143d239cb43494cc163da14979082da" [[package]] name = "cargo" -version = "0.56.0" +version = "0.57.0" dependencies = [ "anyhow", "atty", @@ -388,7 +388,7 @@ dependencies = [ [[package]] name = "cargo-util" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "core-foundation", diff --git a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr index 0cbeb71d23538..f690d95cc589b 100644 --- a/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr +++ b/src/test/ui/rfc-2632-const-trait-impl/assoc-type.stderr @@ -11,7 +11,7 @@ LL | type Bar = NonConstAdd; help: consider introducing a `where` bound, but there might be an alternative better way to express this requirement | LL | impl const Foo for NonConstAdd where NonConstAdd: Add { - | ^^^^^^^^^^^^^^^^^^^^^^ + | ++++++++++++++++++++++ error: aborting due to previous error