Skip to content

Commit 6cec8cb

Browse files
authored
Rollup merge of #108830 - compiler-errors:new-solver-fast-reject-faster, r=lcnr
Treat projections with infer as placeholder during fast reject in new solver r? ``@lcnr`` Kind of a shame that we need to change all of the call sites for `for_each_relevant_impl`, etc. to pass an extra parameter. I guess I could have the "default" fn which calls a configurable fn?
2 parents b4c7fc4 + 84d254e commit 6cec8cb

File tree

20 files changed

+250
-83
lines changed

20 files changed

+250
-83
lines changed

compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_errors::struct_span_err;
1111
use rustc_hir as hir;
1212
use rustc_hir::def::DefKind;
1313
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
14-
use rustc_middle::ty::fast_reject::{simplify_type, SimplifiedType, TreatParams};
14+
use rustc_middle::ty::fast_reject::{simplify_type, SimplifiedType, TreatParams, TreatProjections};
1515
use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt};
1616
use rustc_span::symbol::sym;
1717

@@ -99,7 +99,12 @@ impl<'tcx> InherentCollect<'tcx> {
9999
}
100100
}
101101

102-
if let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::AsInfer) {
102+
if let Some(simp) = simplify_type(
103+
self.tcx,
104+
self_ty,
105+
TreatParams::AsCandidateKey,
106+
TreatProjections::AsCandidateKey,
107+
) {
103108
self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
104109
} else {
105110
bug!("unexpected self type: {:?}", self_ty);
@@ -159,7 +164,12 @@ impl<'tcx> InherentCollect<'tcx> {
159164
}
160165
}
161166

162-
if let Some(simp) = simplify_type(self.tcx, ty, TreatParams::AsInfer) {
167+
if let Some(simp) = simplify_type(
168+
self.tcx,
169+
ty,
170+
TreatParams::AsCandidateKey,
171+
TreatProjections::AsCandidateKey,
172+
) {
163173
self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
164174
} else {
165175
bug!("unexpected primitive type: {:?}", ty);

compiler/rustc_hir_typeck/src/method/probe.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_infer::infer::canonical::OriginalQueryValues;
1515
use rustc_infer::infer::canonical::{Canonical, QueryResponse};
1616
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
1717
use rustc_middle::middle::stability;
18+
use rustc_middle::ty::fast_reject::TreatProjections;
1819
use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
1920
use rustc_middle::ty::AssocItem;
2021
use rustc_middle::ty::GenericParamDefKind;
@@ -699,7 +700,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
699700
}
700701

701702
fn assemble_inherent_candidates_for_incoherent_ty(&mut self, self_ty: Ty<'tcx>) {
702-
let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::AsInfer) else {
703+
let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::AsCandidateKey, TreatProjections::AsCandidateKey) else {
703704
bug!("unexpected incoherent type: {:?}", self_ty)
704705
};
705706
for &impl_def_id in self.tcx.incoherent_impls(simp) {

compiler/rustc_hir_typeck/src/method/suggest.rs

+15-7
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use rustc_infer::infer::{
2525
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
2626
use rustc_middle::traits::util::supertraits;
2727
use rustc_middle::ty::fast_reject::DeepRejectCtxt;
28+
use rustc_middle::ty::fast_reject::TreatProjections;
2829
use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
2930
use rustc_middle::ty::print::{with_crate_prefix, with_forced_trimmed_paths};
3031
use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt};
@@ -1257,7 +1258,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12571258
let target_ty = self
12581259
.autoderef(sugg_span, rcvr_ty)
12591260
.find(|(rcvr_ty, _)| {
1260-
DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer }
1261+
DeepRejectCtxt { treat_obligation_params: TreatParams::AsCandidateKey }
12611262
.types_may_unify(*rcvr_ty, impl_ty)
12621263
})
12631264
.map_or(impl_ty, |(ty, _)| ty)
@@ -1516,7 +1517,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15161517
.into_iter()
15171518
.any(|info| self.associated_value(info.def_id, item_name).is_some());
15181519
let found_assoc = |ty: Ty<'tcx>| {
1519-
simplify_type(tcx, ty, TreatParams::AsInfer)
1520+
simplify_type(tcx, ty, TreatParams::AsCandidateKey, TreatProjections::AsCandidateKey)
15201521
.and_then(|simp| {
15211522
tcx.incoherent_impls(simp)
15221523
.iter()
@@ -2645,9 +2646,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26452646
// FIXME: Even though negative bounds are not implemented, we could maybe handle
26462647
// cases where a positive bound implies a negative impl.
26472648
(candidates, Vec::new())
2648-
} else if let Some(simp_rcvr_ty) =
2649-
simplify_type(self.tcx, rcvr_ty, TreatParams::AsPlaceholder)
2650-
{
2649+
} else if let Some(simp_rcvr_ty) = simplify_type(
2650+
self.tcx,
2651+
rcvr_ty,
2652+
TreatParams::ForLookup,
2653+
TreatProjections::ForLookup,
2654+
) {
26512655
let mut potential_candidates = Vec::new();
26522656
let mut explicitly_negative = Vec::new();
26532657
for candidate in candidates {
@@ -2660,8 +2664,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26602664
})
26612665
.any(|imp_did| {
26622666
let imp = self.tcx.impl_trait_ref(imp_did).unwrap().subst_identity();
2663-
let imp_simp =
2664-
simplify_type(self.tcx, imp.self_ty(), TreatParams::AsPlaceholder);
2667+
let imp_simp = simplify_type(
2668+
self.tcx,
2669+
imp.self_ty(),
2670+
TreatParams::ForLookup,
2671+
TreatProjections::ForLookup,
2672+
);
26652673
imp_simp.map_or(false, |s| s == simp_rcvr_ty)
26662674
})
26672675
{

compiler/rustc_metadata/src/rmeta/encoder.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use rustc_middle::middle::exported_symbols::{
2626
use rustc_middle::mir::interpret;
2727
use rustc_middle::traits::specialization_graph;
2828
use rustc_middle::ty::codec::TyEncoder;
29-
use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
29+
use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams, TreatProjections};
3030
use rustc_middle::ty::query::Providers;
3131
use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
3232
use rustc_middle::util::common::to_readable_str;
@@ -1858,7 +1858,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
18581858
let simplified_self_ty = fast_reject::simplify_type(
18591859
self.tcx,
18601860
trait_ref.self_ty(),
1861-
TreatParams::AsInfer,
1861+
TreatParams::AsCandidateKey,
1862+
TreatProjections::AsCandidateKey,
18621863
);
18631864

18641865
fx_hash_map

compiler/rustc_middle/src/ty/fast_reject.rs

+39-24
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,35 @@ pub enum SimplifiedType {
5151
/// generic parameters as if they were inference variables in that case.
5252
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
5353
pub enum TreatParams {
54-
/// Treat parameters as placeholders in the given environment.
54+
/// Treat parameters as infer vars. This is the correct mode for caching
55+
/// an impl's type for lookup.
56+
AsCandidateKey,
57+
/// Treat parameters as placeholders in the given environment. This is the
58+
/// correct mode for *lookup*, as during candidate selection.
59+
ForLookup,
60+
}
61+
62+
/// During fast-rejection, we have the choice of treating projection types
63+
/// as either simplifyable or not, depending on whether we expect the projection
64+
/// to be normalized/rigid.
65+
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
66+
pub enum TreatProjections {
67+
/// In candidates, we may be able to normalize the projection
68+
/// after instantiating the candidate and equating it with a goal.
5569
///
56-
/// Note that this also causes us to treat projections as if they were
57-
/// placeholders. This is only correct if the given projection cannot
58-
/// be normalized in the current context. Even if normalization fails,
59-
/// it may still succeed later if the projection contains any inference
60-
/// variables.
61-
AsPlaceholder,
62-
AsInfer,
70+
/// We must assume that the `impl<T> Trait<T> for <T as Id>::This`
71+
/// can apply to all self types so we don't return a simplified type
72+
/// for `<T as Id>::This`.
73+
AsCandidateKey,
74+
/// In the old solver we don't try to normalize projections
75+
/// when looking up impls and only access them by using the
76+
/// current self type. This means that if the self type is
77+
/// a projection which could later be normalized, we must not
78+
/// treat it as rigid.
79+
ForLookup,
80+
/// We can treat projections in the self type as opaque as
81+
/// we separately look up impls for the normalized self type.
82+
NextSolverLookup,
6383
}
6484

6585
/// Tries to simplify a type by only returning the outermost injective¹ layer, if one exists.
@@ -87,6 +107,7 @@ pub fn simplify_type<'tcx>(
87107
tcx: TyCtxt<'tcx>,
88108
ty: Ty<'tcx>,
89109
treat_params: TreatParams,
110+
treat_projections: TreatProjections,
90111
) -> Option<SimplifiedType> {
91112
match *ty.kind() {
92113
ty::Bool => Some(BoolSimplifiedType),
@@ -115,19 +136,13 @@ pub fn simplify_type<'tcx>(
115136
ty::FnPtr(f) => Some(FunctionSimplifiedType(f.skip_binder().inputs().len())),
116137
ty::Placeholder(..) => Some(PlaceholderSimplifiedType),
117138
ty::Param(_) => match treat_params {
118-
TreatParams::AsPlaceholder => Some(PlaceholderSimplifiedType),
119-
TreatParams::AsInfer => None,
139+
TreatParams::ForLookup => Some(PlaceholderSimplifiedType),
140+
TreatParams::AsCandidateKey => None,
120141
},
121-
ty::Alias(..) => match treat_params {
122-
// When treating `ty::Param` as a placeholder, projections also
123-
// don't unify with anything else as long as they are fully normalized.
124-
//
125-
// We will have to be careful with lazy normalization here.
126-
TreatParams::AsPlaceholder if !ty.has_non_region_infer() => {
127-
debug!("treating `{}` as a placeholder", ty);
128-
Some(PlaceholderSimplifiedType)
129-
}
130-
TreatParams::AsPlaceholder | TreatParams::AsInfer => None,
142+
ty::Alias(..) => match treat_projections {
143+
TreatProjections::ForLookup if !ty.needs_infer() => Some(PlaceholderSimplifiedType),
144+
TreatProjections::NextSolverLookup => Some(PlaceholderSimplifiedType),
145+
TreatProjections::AsCandidateKey | TreatProjections::ForLookup => None,
131146
},
132147
ty::Foreign(def_id) => Some(ForeignSimplifiedType(def_id)),
133148
ty::Bound(..) | ty::Infer(_) | ty::Error(_) => None,
@@ -295,8 +310,8 @@ impl DeepRejectCtxt {
295310
// Depending on the value of `treat_obligation_params`, we either
296311
// treat generic parameters like placeholders or like inference variables.
297312
ty::Param(_) => match self.treat_obligation_params {
298-
TreatParams::AsPlaceholder => false,
299-
TreatParams::AsInfer => true,
313+
TreatParams::ForLookup => false,
314+
TreatParams::AsCandidateKey => true,
300315
},
301316

302317
ty::Infer(_) => true,
@@ -333,8 +348,8 @@ impl DeepRejectCtxt {
333348
let k = impl_ct.kind();
334349
match obligation_ct.kind() {
335350
ty::ConstKind::Param(_) => match self.treat_obligation_params {
336-
TreatParams::AsPlaceholder => false,
337-
TreatParams::AsInfer => true,
351+
TreatParams::ForLookup => false,
352+
TreatParams::AsCandidateKey => true,
338353
},
339354

340355
// As we don't necessarily eagerly evaluate constants,

compiler/rustc_middle/src/ty/trait_def.rs

+41-17
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::traits::specialization_graph;
2-
use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
2+
use crate::ty::fast_reject::{self, SimplifiedType, TreatParams, TreatProjections};
33
use crate::ty::visit::TypeVisitableExt;
44
use crate::ty::{Ident, Ty, TyCtxt};
55
use hir::def_id::LOCAL_CRATE;
@@ -118,16 +118,32 @@ impl<'tcx> TyCtxt<'tcx> {
118118
/// Iterate over every impl that could possibly match the self type `self_ty`.
119119
///
120120
/// `trait_def_id` MUST BE the `DefId` of a trait.
121-
pub fn for_each_relevant_impl<F: FnMut(DefId)>(
121+
pub fn for_each_relevant_impl(
122122
self,
123123
trait_def_id: DefId,
124124
self_ty: Ty<'tcx>,
125-
mut f: F,
125+
f: impl FnMut(DefId),
126126
) {
127-
let _: Option<()> = self.find_map_relevant_impl(trait_def_id, self_ty, |did| {
128-
f(did);
129-
None
130-
});
127+
self.for_each_relevant_impl_treating_projections(
128+
trait_def_id,
129+
self_ty,
130+
TreatProjections::ForLookup,
131+
f,
132+
)
133+
}
134+
135+
pub fn for_each_relevant_impl_treating_projections(
136+
self,
137+
trait_def_id: DefId,
138+
self_ty: Ty<'tcx>,
139+
treat_projections: TreatProjections,
140+
mut f: impl FnMut(DefId),
141+
) {
142+
let _: Option<()> =
143+
self.find_map_relevant_impl(trait_def_id, self_ty, treat_projections, |did| {
144+
f(did);
145+
None
146+
});
131147
}
132148

133149
/// `trait_def_id` MUST BE the `DefId` of a trait.
@@ -137,7 +153,12 @@ impl<'tcx> TyCtxt<'tcx> {
137153
self_ty: Ty<'tcx>,
138154
) -> impl Iterator<Item = DefId> + 'tcx {
139155
let impls = self.trait_impls_of(trait_def_id);
140-
if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::AsInfer) {
156+
if let Some(simp) = fast_reject::simplify_type(
157+
self,
158+
self_ty,
159+
TreatParams::AsCandidateKey,
160+
TreatProjections::AsCandidateKey,
161+
) {
141162
if let Some(impls) = impls.non_blanket_impls.get(&simp) {
142163
return impls.iter().copied();
143164
}
@@ -150,11 +171,12 @@ impl<'tcx> TyCtxt<'tcx> {
150171
/// the first non-none value.
151172
///
152173
/// `trait_def_id` MUST BE the `DefId` of a trait.
153-
pub fn find_map_relevant_impl<T, F: FnMut(DefId) -> Option<T>>(
174+
pub fn find_map_relevant_impl<T>(
154175
self,
155176
trait_def_id: DefId,
156177
self_ty: Ty<'tcx>,
157-
mut f: F,
178+
treat_projections: TreatProjections,
179+
mut f: impl FnMut(DefId) -> Option<T>,
158180
) -> Option<T> {
159181
// FIXME: This depends on the set of all impls for the trait. That is
160182
// unfortunate wrt. incremental compilation.
@@ -169,14 +191,13 @@ impl<'tcx> TyCtxt<'tcx> {
169191
}
170192
}
171193

172-
// Note that we're using `TreatParams::AsPlaceholder` to query `non_blanket_impls` while using
173-
// `TreatParams::AsInfer` while actually adding them.
174-
//
175194
// This way, when searching for some impl for `T: Trait`, we do not look at any impls
176195
// whose outer level is not a parameter or projection. Especially for things like
177196
// `T: Clone` this is incredibly useful as we would otherwise look at all the impls
178197
// of `Clone` for `Option<T>`, `Vec<T>`, `ConcreteType` and so on.
179-
if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::AsPlaceholder) {
198+
if let Some(simp) =
199+
fast_reject::simplify_type(self, self_ty, TreatParams::ForLookup, treat_projections)
200+
{
180201
if let Some(impls) = impls.non_blanket_impls.get(&simp) {
181202
for &impl_def_id in impls {
182203
if let result @ Some(_) = f(impl_def_id) {
@@ -237,9 +258,12 @@ pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> Trait
237258
continue;
238259
}
239260

240-
if let Some(simplified_self_ty) =
241-
fast_reject::simplify_type(tcx, impl_self_ty, TreatParams::AsInfer)
242-
{
261+
if let Some(simplified_self_ty) = fast_reject::simplify_type(
262+
tcx,
263+
impl_self_ty,
264+
TreatParams::AsCandidateKey,
265+
TreatProjections::AsCandidateKey,
266+
) {
243267
impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
244268
} else {
245269
impls.blanket_impls.push(impl_def_id);

compiler/rustc_middle/src/ty/util.rs

+14-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
44
use crate::mir;
5+
use crate::ty::fast_reject::TreatProjections;
56
use crate::ty::layout::IntegerExt;
67
use crate::ty::{
78
self, FallibleTypeFolder, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
@@ -363,14 +364,20 @@ impl<'tcx> TyCtxt<'tcx> {
363364
self.ensure().coherent_trait(drop_trait);
364365

365366
let ty = self.type_of(adt_did).subst_identity();
366-
let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
367-
if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
368-
if validate(self, impl_did).is_ok() {
369-
return Some((*item_id, self.constness(impl_did)));
367+
let (did, constness) = self.find_map_relevant_impl(
368+
drop_trait,
369+
ty,
370+
// FIXME: This could also be some other mode, like "unexpected"
371+
TreatProjections::ForLookup,
372+
|impl_did| {
373+
if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
374+
if validate(self, impl_did).is_ok() {
375+
return Some((*item_id, self.constness(impl_did)));
376+
}
370377
}
371-
}
372-
None
373-
})?;
378+
None
379+
},
380+
)?;
374381

375382
Some(ty::Destructor { did, constness })
376383
}

compiler/rustc_passes/src/check_attr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2215,7 +2215,7 @@ impl CheckAttrVisitor<'_> {
22152215
// `fn(TokenStream) -> TokenStream` after some substitution of generic arguments.
22162216
//
22172217
// Properly checking this means pulling in additional `rustc` crates, so we don't.
2218-
let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer };
2218+
let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsCandidateKey };
22192219

22202220
if sig.abi != Abi::Rust {
22212221
tcx.sess.emit_err(errors::ProcMacroInvalidAbi {

0 commit comments

Comments
 (0)