Skip to content

Commit c7a6720

Browse files
Rollup merge of #79287 - jonas-schievink:const-trait-impl, r=oli-obk
Allow using generic trait methods in `const fn` Next step for #67792, this now also allows code like the following: ```rust struct S; impl const PartialEq for S { fn eq(&self, _: &S) -> bool { true } } const fn equals_self<T: PartialEq>(t: &T) -> bool { *t == *t } pub const EQ: bool = equals_self(&S); ``` This works by threading const-ness of trait predicates through trait selection, in particular through `ParamCandidate`, and exposing it in the resulting `ImplSource`. Since this change makes two bounds `T: Trait` and `T: ?const Trait` that only differ in their const-ness be treated like different bounds, candidate winnowing has been changed to drop the `?const` candidate in favor of the const candidate, to avoid ambiguities when both a const and a non-const bound is present.
2 parents c58c245 + cb40684 commit c7a6720

File tree

22 files changed

+230
-33
lines changed

22 files changed

+230
-33
lines changed

compiler/rustc_infer/src/traits/util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToT
309309
fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
310310
while let Some(obligation) = self.base_iterator.next() {
311311
if let Some(data) = obligation.predicate.to_opt_poly_trait_ref() {
312-
return Some(data);
312+
return Some(data.value);
313313
}
314314
}
315315
None

compiler/rustc_middle/src/traits/mod.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use crate::ty::{self, AdtKind, Ty, TyCtxt};
1616
use rustc_errors::{Applicability, DiagnosticBuilder};
1717
use rustc_hir as hir;
1818
use rustc_hir::def_id::DefId;
19+
use rustc_hir::Constness;
1920
use rustc_span::symbol::Symbol;
2021
use rustc_span::{Span, DUMMY_SP};
2122
use smallvec::SmallVec;
@@ -457,7 +458,7 @@ pub enum ImplSource<'tcx, N> {
457458
/// for some type parameter. The `Vec<N>` represents the
458459
/// obligations incurred from normalizing the where-clause (if
459460
/// any).
460-
Param(Vec<N>),
461+
Param(Vec<N>, Constness),
461462

462463
/// Virtual calls through an object.
463464
Object(ImplSourceObjectData<'tcx, N>),
@@ -487,7 +488,7 @@ impl<'tcx, N> ImplSource<'tcx, N> {
487488
pub fn nested_obligations(self) -> Vec<N> {
488489
match self {
489490
ImplSource::UserDefined(i) => i.nested,
490-
ImplSource::Param(n) => n,
491+
ImplSource::Param(n, _) => n,
491492
ImplSource::Builtin(i) => i.nested,
492493
ImplSource::AutoImpl(d) => d.nested,
493494
ImplSource::Closure(c) => c.nested,
@@ -502,7 +503,7 @@ impl<'tcx, N> ImplSource<'tcx, N> {
502503
pub fn borrow_nested_obligations(&self) -> &[N] {
503504
match &self {
504505
ImplSource::UserDefined(i) => &i.nested[..],
505-
ImplSource::Param(n) => &n[..],
506+
ImplSource::Param(n, _) => &n[..],
506507
ImplSource::Builtin(i) => &i.nested[..],
507508
ImplSource::AutoImpl(d) => &d.nested[..],
508509
ImplSource::Closure(c) => &c.nested[..],
@@ -524,7 +525,7 @@ impl<'tcx, N> ImplSource<'tcx, N> {
524525
substs: i.substs,
525526
nested: i.nested.into_iter().map(f).collect(),
526527
}),
527-
ImplSource::Param(n) => ImplSource::Param(n.into_iter().map(f).collect()),
528+
ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
528529
ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
529530
nested: i.nested.into_iter().map(f).collect(),
530531
}),

compiler/rustc_middle/src/traits/select.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ pub enum SelectionCandidate<'tcx> {
101101
/// `false` if there are no *further* obligations.
102102
has_nested: bool,
103103
},
104-
ParamCandidate(ty::PolyTraitRef<'tcx>),
104+
ParamCandidate(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>),
105105
ImplCandidate(DefId),
106106
AutoImplCandidate(DefId),
107107

compiler/rustc_middle/src/traits/structural_impls.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ impl<'tcx, N: fmt::Debug> fmt::Debug for traits::ImplSource<'tcx, N> {
2121

2222
super::ImplSource::Object(ref d) => write!(f, "{:?}", d),
2323

24-
super::ImplSource::Param(ref n) => write!(f, "ImplSourceParamData({:?})", n),
24+
super::ImplSource::Param(ref n, ct) => {
25+
write!(f, "ImplSourceParamData({:?}, {:?})", n, ct)
26+
}
2527

2628
super::ImplSource::Builtin(ref d) => write!(f, "{:?}", d),
2729

compiler/rustc_middle/src/ty/context.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
4242
use rustc_hir::definitions::{DefPathHash, Definitions};
4343
use rustc_hir::intravisit::Visitor;
4444
use rustc_hir::lang_items::LangItem;
45-
use rustc_hir::{HirId, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet, Node, TraitCandidate};
45+
use rustc_hir::{
46+
Constness, HirId, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet, Node, TraitCandidate,
47+
};
4648
use rustc_index::vec::{Idx, IndexVec};
4749
use rustc_macros::HashStable;
4850
use rustc_session::config::{BorrowckMode, CrateType, OutputFilenames};
@@ -1635,6 +1637,8 @@ nop_list_lift! {projs; ProjectionKind => ProjectionKind}
16351637
// This is the impl for `&'a InternalSubsts<'a>`.
16361638
nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
16371639

1640+
CloneLiftImpls! { for<'tcx> { Constness, } }
1641+
16381642
pub mod tls {
16391643
use super::{ptr_eq, GlobalCtxt, TyCtxt};
16401644

compiler/rustc_middle/src/ty/mod.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -1503,9 +1503,11 @@ impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
15031503
}
15041504

15051505
impl<'tcx> Predicate<'tcx> {
1506-
pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1506+
pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
15071507
match self.skip_binders() {
1508-
PredicateAtom::Trait(t, _) => Some(ty::Binder::bind(t.trait_ref)),
1508+
PredicateAtom::Trait(t, constness) => {
1509+
Some(ConstnessAnd { constness, value: ty::Binder::bind(t.trait_ref) })
1510+
}
15091511
PredicateAtom::Projection(..)
15101512
| PredicateAtom::Subtype(..)
15111513
| PredicateAtom::RegionOutlives(..)
@@ -1947,7 +1949,7 @@ impl<'tcx> ParamEnv<'tcx> {
19471949
}
19481950
}
19491951

1950-
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1952+
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
19511953
pub struct ConstnessAnd<T> {
19521954
pub constness: Constness,
19531955
pub value: T,

compiler/rustc_mir/src/transform/check_consts/validation.rs

+36-4
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,18 @@ use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorReported};
44
use rustc_hir::def_id::DefId;
55
use rustc_hir::{self as hir, HirId, LangItem};
66
use rustc_infer::infer::TyCtxtInferExt;
7+
use rustc_infer::traits::{ImplSource, Obligation, ObligationCause};
78
use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
89
use rustc_middle::mir::*;
910
use rustc_middle::ty::cast::CastTy;
1011
use rustc_middle::ty::subst::GenericArgKind;
1112
use rustc_middle::ty::{
1213
self, adjustment::PointerCast, Instance, InstanceDef, Ty, TyCtxt, TypeAndMut,
1314
};
15+
use rustc_middle::ty::{Binder, TraitPredicate, TraitRef};
1416
use rustc_span::{sym, Span, Symbol};
1517
use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
16-
use rustc_trait_selection::traits::{self, TraitEngine};
18+
use rustc_trait_selection::traits::{self, SelectionContext, TraitEngine};
1719

1820
use std::mem;
1921
use std::ops::Deref;
@@ -765,9 +767,39 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> {
765767
}
766768
};
767769

768-
// Resolve a trait method call to its concrete implementation, which may be in a
769-
// `const` trait impl.
770-
if self.tcx.features().const_trait_impl {
770+
// Attempting to call a trait method?
771+
if let Some(trait_id) = tcx.trait_of_item(callee) {
772+
if !self.tcx.features().const_trait_impl {
773+
self.check_op(ops::FnCallNonConst(callee));
774+
return;
775+
}
776+
777+
let trait_ref = TraitRef::from_method(tcx, trait_id, substs);
778+
let obligation = Obligation::new(
779+
ObligationCause::dummy(),
780+
param_env,
781+
Binder::bind(TraitPredicate {
782+
trait_ref: TraitRef::from_method(tcx, trait_id, substs),
783+
}),
784+
);
785+
786+
let implsrc = tcx.infer_ctxt().enter(|infcx| {
787+
let mut selcx = SelectionContext::new(&infcx);
788+
selcx.select(&obligation).unwrap()
789+
});
790+
791+
// If the method is provided via a where-clause that does not use the `?const`
792+
// opt-out, the call is allowed.
793+
if let Some(ImplSource::Param(_, hir::Constness::Const)) = implsrc {
794+
debug!(
795+
"const_trait_impl: provided {:?} via where-clause in {:?}",
796+
trait_ref, param_env
797+
);
798+
return;
799+
}
800+
801+
// Resolve a trait method call to its concrete implementation, which may be in a
802+
// `const` trait impl.
771803
let instance = Instance::resolve(tcx, param_env, callee, substs);
772804
debug!("Resolving ({:?}) -> {:?}", callee, instance);
773805
if let Ok(Some(func)) = instance {

compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -350,11 +350,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
350350

351351
// Micro-optimization: filter out predicates relating to different traits.
352352
let matching_bounds =
353-
all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
353+
all_bounds.filter(|p| p.value.def_id() == stack.obligation.predicate.def_id());
354354

355355
// Keep only those bounds which may apply, and propagate overflow if it occurs.
356356
for bound in matching_bounds {
357-
let wc = self.evaluate_where_clause(stack, bound)?;
357+
let wc = self.evaluate_where_clause(stack, bound.value)?;
358358
if wc.may_apply() {
359359
candidates.vec.push(ParamCandidate(bound));
360360
}

compiler/rustc_trait_selection/src/traits/select/confirmation.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//! https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation
99
use rustc_data_structures::stack::ensure_sufficient_stack;
1010
use rustc_hir::lang_items::LangItem;
11+
use rustc_hir::Constness;
1112
use rustc_index::bit_set::GrowableBitSet;
1213
use rustc_infer::infer::InferOk;
1314
use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType;
@@ -55,8 +56,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
5556
}
5657

5758
ParamCandidate(param) => {
58-
let obligations = self.confirm_param_candidate(obligation, param);
59-
Ok(ImplSource::Param(obligations))
59+
let obligations = self.confirm_param_candidate(obligation, param.value);
60+
Ok(ImplSource::Param(obligations, param.constness))
6061
}
6162

6263
ImplCandidate(impl_def_id) => {
@@ -70,7 +71,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
7071

7172
ProjectionCandidate(idx) => {
7273
let obligations = self.confirm_projection_candidate(obligation, idx)?;
73-
Ok(ImplSource::Param(obligations))
74+
// FIXME(jschievink): constness
75+
Ok(ImplSource::Param(obligations, Constness::NotConst))
7476
}
7577

7678
ObjectCandidate(idx) => {
@@ -106,7 +108,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
106108
// This indicates something like `Trait + Send: Send`. In this case, we know that
107109
// this holds because that's what the object type is telling us, and there's really
108110
// no additional obligations to prove and no types in particular to unify, etc.
109-
Ok(ImplSource::Param(Vec::new()))
111+
Ok(ImplSource::Param(Vec::new(), Constness::NotConst))
110112
}
111113

112114
BuiltinUnsizeCandidate => {
@@ -151,7 +153,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
151153
obligations.extend(self.infcx.commit_if_ok(|_| {
152154
self.infcx
153155
.at(&obligation.cause, obligation.param_env)
154-
.sup(placeholder_trait_predicate.trait_ref.to_poly_trait_ref(), candidate)
156+
.sup(placeholder_trait_predicate.trait_ref.to_poly_trait_ref(), candidate.value)
155157
.map(|InferOk { obligations, .. }| obligations)
156158
.map_err(|_| Unimplemented)
157159
})?);

compiler/rustc_trait_selection/src/traits/select/mod.rs

+12-4
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
3131
use rustc_errors::ErrorReported;
3232
use rustc_hir as hir;
3333
use rustc_hir::def_id::DefId;
34+
use rustc_hir::Constness;
3435
use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
3536
use rustc_middle::mir::interpret::ErrorHandled;
3637
use rustc_middle::ty::fast_reject;
@@ -1335,7 +1336,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
13351336
(BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate, _) => true,
13361337
(_, BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate) => false,
13371338

1338-
(ParamCandidate(..), ParamCandidate(..)) => false,
1339+
(ParamCandidate(other), ParamCandidate(victim)) => {
1340+
if other.value == victim.value && victim.constness == Constness::NotConst {
1341+
// Drop otherwise equivalent non-const candidates in favor of const candidates.
1342+
true
1343+
} else {
1344+
false
1345+
}
1346+
}
13391347

13401348
// Global bounds from the where clause should be ignored
13411349
// here (see issue #50825). Otherwise, we have a where
@@ -1354,11 +1362,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
13541362
| TraitAliasCandidate(..)
13551363
| ObjectCandidate(_)
13561364
| ProjectionCandidate(_),
1357-
) => !is_global(cand),
1365+
) => !is_global(&cand.value),
13581366
(ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
13591367
// Prefer these to a global where-clause bound
13601368
// (see issue #50825).
1361-
is_global(cand)
1369+
is_global(&cand.value)
13621370
}
13631371
(
13641372
ImplCandidate(_)
@@ -1373,7 +1381,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
13731381
) => {
13741382
// Prefer these to a global where-clause bound
13751383
// (see issue #50825).
1376-
is_global(cand) && other.evaluation.must_apply_modulo_regions()
1384+
is_global(&cand.value) && other.evaluation.must_apply_modulo_regions()
13771385
}
13781386

13791387
(ProjectionCandidate(i), ProjectionCandidate(j))

compiler/rustc_trait_selection/src/traits/specialize/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -498,8 +498,8 @@ fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String>
498498

499499
for (p, _) in predicates {
500500
if let Some(poly_trait_ref) = p.to_opt_poly_trait_ref() {
501-
if Some(poly_trait_ref.def_id()) == sized_trait {
502-
types_without_default_bounds.remove(poly_trait_ref.self_ty().skip_binder());
501+
if Some(poly_trait_ref.value.def_id()) == sized_trait {
502+
types_without_default_bounds.remove(poly_trait_ref.value.self_ty().skip_binder());
503503
continue;
504504
}
505505
}

compiler/rustc_trait_selection/src/traits/util.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ impl<'tcx> TraitAliasExpander<'tcx> {
125125
let items = predicates.predicates.iter().rev().filter_map(|(pred, span)| {
126126
pred.subst_supertrait(tcx, &trait_ref)
127127
.to_opt_poly_trait_ref()
128-
.map(|trait_ref| item.clone_and_push(trait_ref, *span))
128+
.map(|trait_ref| item.clone_and_push(trait_ref.value, *span))
129129
});
130130
debug!("expand_trait_aliases: items={:?}", items.clone());
131131

@@ -182,7 +182,7 @@ impl Iterator for SupertraitDefIds<'tcx> {
182182
.predicates
183183
.iter()
184184
.filter_map(|(pred, _)| pred.to_opt_poly_trait_ref())
185-
.map(|trait_ref| trait_ref.def_id())
185+
.map(|trait_ref| trait_ref.value.def_id())
186186
.filter(|&super_def_id| visited.insert(super_def_id)),
187187
);
188188
Some(def_id)

compiler/rustc_trait_selection/src/traits/wf.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
294294
let mut cause = cause.clone();
295295
if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() {
296296
let derived_cause = traits::DerivedObligationCause {
297-
parent_trait_ref,
297+
parent_trait_ref: parent_trait_ref.value,
298298
parent_code: Rc::new(obligation.cause.code.clone()),
299299
};
300300
cause.make_mut().code =

compiler/rustc_typeck/src/astconv/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1364,7 +1364,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
13641364
|| {
13651365
traits::transitive_bounds(
13661366
tcx,
1367-
predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1367+
predicates.iter().filter_map(|(p, _)| {
1368+
p.to_opt_poly_trait_ref().map(|trait_ref| trait_ref.value)
1369+
}),
13681370
)
13691371
},
13701372
|| param_name.to_string(),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//! Basic test for calling methods on generic type parameters in `const fn`.
2+
3+
// check-pass
4+
5+
#![feature(const_fn)]
6+
#![feature(const_trait_impl)]
7+
#![allow(incomplete_features)]
8+
9+
struct S;
10+
11+
impl const PartialEq for S {
12+
fn eq(&self, _: &S) -> bool {
13+
true
14+
}
15+
}
16+
17+
const fn equals_self<T: PartialEq>(t: &T) -> bool {
18+
*t == *t
19+
}
20+
21+
const fn equals_self_wrapper<T: PartialEq>(t: &T) -> bool {
22+
equals_self(t)
23+
}
24+
25+
pub const EQ: bool = equals_self_wrapper(&S);
26+
27+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// check-pass
2+
3+
#![feature(const_fn)]
4+
#![feature(const_trait_impl)]
5+
#![feature(const_trait_bound_opt_out)]
6+
#![allow(incomplete_features)]
7+
8+
struct S;
9+
10+
impl const PartialEq for S {
11+
fn eq(&self, _: &S) -> bool {
12+
true
13+
}
14+
}
15+
16+
// This duplicate bound should not result in ambiguities. It should be equivalent to a single const
17+
// bound.
18+
const fn equals_self<T: PartialEq + ?const PartialEq>(t: &T) -> bool {
19+
*t == *t
20+
}
21+
22+
pub const EQ: bool = equals_self(&S);
23+
24+
fn main() {}

0 commit comments

Comments
 (0)