Skip to content

Commit 69ac533

Browse files
committed
Auto merge of #86986 - lcnr:simplify_type, r=nikomatsakis,oli-obk
extend `simplify_type` might cause a slight perf inprovement and imo more accurately represents what types there are. considering that I was going to use this in #85048 it seems like we might need this in the future anyways 🤷
2 parents c5ecc15 + 00cbacb commit 69ac533

File tree

12 files changed

+179
-80
lines changed

12 files changed

+179
-80
lines changed

compiler/rustc_metadata/src/rmeta/encoder.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use rustc_middle::mir::interpret;
2626
use rustc_middle::thir;
2727
use rustc_middle::traits::specialization_graph;
2828
use rustc_middle::ty::codec::TyEncoder;
29+
use rustc_middle::ty::fast_reject::{self, SimplifyParams, StripReferences};
2930
use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
3031
use rustc_serialize::{opaque, Encodable, Encoder};
3132
use rustc_session::config::CrateType;
@@ -2033,15 +2034,19 @@ impl EncodeContext<'a, 'tcx> {
20332034

20342035
struct ImplVisitor<'tcx> {
20352036
tcx: TyCtxt<'tcx>,
2036-
impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
2037+
impls: FxHashMap<DefId, Vec<(DefIndex, Option<fast_reject::SimplifiedType>)>>,
20372038
}
20382039

20392040
impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
20402041
fn visit_item(&mut self, item: &hir::Item<'_>) {
20412042
if let hir::ItemKind::Impl { .. } = item.kind {
20422043
if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2043-
let simplified_self_ty =
2044-
ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
2044+
let simplified_self_ty = fast_reject::simplify_type(
2045+
self.tcx,
2046+
trait_ref.self_ty(),
2047+
SimplifyParams::No,
2048+
StripReferences::No,
2049+
);
20452050

20462051
self.impls
20472052
.entry(trait_ref.def_id)

compiler/rustc_middle/src/ty/fast_reject.rs

+60-22
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::mir::Mutability;
12
use crate::ty::{self, Ty, TyCtxt};
23
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34
use rustc_hir::def_id::DefId;
@@ -27,9 +28,12 @@ where
2728
UintSimplifiedType(ty::UintTy),
2829
FloatSimplifiedType(ty::FloatTy),
2930
AdtSimplifiedType(D),
31+
ForeignSimplifiedType(D),
3032
StrSimplifiedType,
3133
ArraySimplifiedType,
32-
PtrSimplifiedType,
34+
SliceSimplifiedType,
35+
RefSimplifiedType(Mutability),
36+
PtrSimplifiedType(Mutability),
3337
NeverSimplifiedType,
3438
TupleSimplifiedType(usize),
3539
/// A trait object, all of whose components are markers
@@ -42,22 +46,48 @@ where
4246
OpaqueSimplifiedType(D),
4347
FunctionSimplifiedType(usize),
4448
ParameterSimplifiedType,
45-
ForeignSimplifiedType(DefId),
4649
}
4750

48-
/// Tries to simplify a type by dropping type parameters, deref'ing away any reference types, etc.
49-
/// The idea is to get something simple that we can use to quickly decide if two types could unify
50-
/// during method lookup.
51+
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
52+
pub enum SimplifyParams {
53+
Yes,
54+
No,
55+
}
56+
57+
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
58+
pub enum StripReferences {
59+
Yes,
60+
No,
61+
}
62+
63+
/// Tries to simplify a type by only returning the outermost injective¹ layer, if one exists.
64+
///
65+
/// The idea is to get something simple that we can use to quickly decide if two types could unify,
66+
/// for example during method lookup.
5167
///
52-
/// If `can_simplify_params` is false, then we will fail to simplify type parameters entirely. This
53-
/// is useful when those type parameters would be instantiated with fresh type variables, since
54-
/// then we can't say much about whether two types would unify. Put another way,
55-
/// `can_simplify_params` should be true if type parameters appear free in `ty` and `false` if they
56-
/// are to be considered bound.
68+
/// A special case here are parameters and projections. Projections can be normalized to
69+
/// a different type, meaning that `<T as Trait>::Assoc` and `u8` can be unified, even though
70+
/// their outermost layer is different while parameters like `T` of impls are later replaced
71+
/// with an inference variable, which then also allows unification with other types.
72+
///
73+
/// When using `SimplifyParams::Yes`, we still return a simplified type for params and projections²,
74+
/// the reasoning for this can be seen at the places doing this.
75+
///
76+
/// For diagnostics we strip references with `StripReferences::Yes`. This is currently the best
77+
/// way to skip some unhelpful suggestions.
78+
///
79+
/// ¹ meaning that if two outermost layers are different, then the whole types are also different.
80+
/// ² FIXME(@lcnr): this seems like it can actually end up being unsound with the way it's used during
81+
/// candidate selection. We do not consider non blanket impls for `<_ as Trait>::Assoc` even
82+
/// though `_` can be inferred to a concrete type later at which point a concrete impl
83+
/// could actually apply. After experimenting for about an hour I wasn't able to cause any issues
84+
/// this way so I am not going to change this until we actually find an issue as I am really
85+
/// interesting in getting an actual test for this.
5786
pub fn simplify_type(
5887
tcx: TyCtxt<'_>,
5988
ty: Ty<'_>,
60-
can_simplify_params: bool,
89+
can_simplify_params: SimplifyParams,
90+
strip_references: StripReferences,
6191
) -> Option<SimplifiedType> {
6292
match *ty.kind() {
6393
ty::Bool => Some(BoolSimplifiedType),
@@ -67,19 +97,24 @@ pub fn simplify_type(
6797
ty::Float(float_type) => Some(FloatSimplifiedType(float_type)),
6898
ty::Adt(def, _) => Some(AdtSimplifiedType(def.did)),
6999
ty::Str => Some(StrSimplifiedType),
70-
ty::Array(..) | ty::Slice(_) => Some(ArraySimplifiedType),
71-
ty::RawPtr(_) => Some(PtrSimplifiedType),
100+
ty::Array(..) => Some(ArraySimplifiedType),
101+
ty::Slice(..) => Some(SliceSimplifiedType),
102+
ty::RawPtr(ptr) => Some(PtrSimplifiedType(ptr.mutbl)),
72103
ty::Dynamic(ref trait_info, ..) => match trait_info.principal_def_id() {
73104
Some(principal_def_id) if !tcx.trait_is_auto(principal_def_id) => {
74105
Some(TraitSimplifiedType(principal_def_id))
75106
}
76107
_ => Some(MarkerTraitObjectSimplifiedType),
77108
},
78-
ty::Ref(_, ty, _) => {
79-
// since we introduce auto-refs during method lookup, we
80-
// just treat &T and T as equivalent from the point of
81-
// view of possibly unifying
82-
simplify_type(tcx, ty, can_simplify_params)
109+
ty::Ref(_, ty, mutbl) => {
110+
if strip_references == StripReferences::Yes {
111+
// For diagnostics, when recommending similar impls we want to
112+
// recommend impls even when there is a reference mismatch,
113+
// so we treat &T and T equivalently in that case.
114+
simplify_type(tcx, ty, can_simplify_params, strip_references)
115+
} else {
116+
Some(RefSimplifiedType(mutbl))
117+
}
83118
}
84119
ty::FnDef(def_id, _) | ty::Closure(def_id, _) => Some(ClosureSimplifiedType(def_id)),
85120
ty::Generator(def_id, _, _) => Some(GeneratorSimplifiedType(def_id)),
@@ -90,7 +125,7 @@ pub fn simplify_type(
90125
ty::Tuple(ref tys) => Some(TupleSimplifiedType(tys.len())),
91126
ty::FnPtr(ref f) => Some(FunctionSimplifiedType(f.skip_binder().inputs().len())),
92127
ty::Projection(_) | ty::Param(_) => {
93-
if can_simplify_params {
128+
if can_simplify_params == SimplifyParams::Yes {
94129
// In normalized types, projections don't unify with
95130
// anything. when lazy normalization happens, this
96131
// will change. It would still be nice to have a way
@@ -120,9 +155,12 @@ impl<D: Copy + Debug + Ord + Eq> SimplifiedTypeGen<D> {
120155
UintSimplifiedType(t) => UintSimplifiedType(t),
121156
FloatSimplifiedType(t) => FloatSimplifiedType(t),
122157
AdtSimplifiedType(d) => AdtSimplifiedType(map(d)),
158+
ForeignSimplifiedType(d) => ForeignSimplifiedType(map(d)),
123159
StrSimplifiedType => StrSimplifiedType,
124160
ArraySimplifiedType => ArraySimplifiedType,
125-
PtrSimplifiedType => PtrSimplifiedType,
161+
SliceSimplifiedType => SliceSimplifiedType,
162+
RefSimplifiedType(m) => RefSimplifiedType(m),
163+
PtrSimplifiedType(m) => PtrSimplifiedType(m),
126164
NeverSimplifiedType => NeverSimplifiedType,
127165
MarkerTraitObjectSimplifiedType => MarkerTraitObjectSimplifiedType,
128166
TupleSimplifiedType(n) => TupleSimplifiedType(n),
@@ -133,7 +171,6 @@ impl<D: Copy + Debug + Ord + Eq> SimplifiedTypeGen<D> {
133171
OpaqueSimplifiedType(d) => OpaqueSimplifiedType(map(d)),
134172
FunctionSimplifiedType(n) => FunctionSimplifiedType(n),
135173
ParameterSimplifiedType => ParameterSimplifiedType,
136-
ForeignSimplifiedType(d) => ForeignSimplifiedType(d),
137174
}
138175
}
139176
}
@@ -149,12 +186,13 @@ where
149186
| CharSimplifiedType
150187
| StrSimplifiedType
151188
| ArraySimplifiedType
152-
| PtrSimplifiedType
189+
| SliceSimplifiedType
153190
| NeverSimplifiedType
154191
| ParameterSimplifiedType
155192
| MarkerTraitObjectSimplifiedType => {
156193
// nothing to do
157194
}
195+
RefSimplifiedType(m) | PtrSimplifiedType(m) => m.hash_stable(hcx, hasher),
158196
IntSimplifiedType(t) => t.hash_stable(hcx, hasher),
159197
UintSimplifiedType(t) => t.hash_stable(hcx, hasher),
160198
FloatSimplifiedType(t) => t.hash_stable(hcx, hasher),

compiler/rustc_middle/src/ty/trait_def.rs

+18-27
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::traits::specialization_graph;
2-
use crate::ty::fast_reject;
2+
use crate::ty::fast_reject::{self, SimplifyParams, StripReferences};
33
use crate::ty::fold::TypeFoldable;
44
use crate::ty::{Ty, TyCtxt};
55
use rustc_hir as hir;
@@ -146,6 +146,11 @@ impl<'tcx> TyCtxt<'tcx> {
146146
self_ty: Ty<'tcx>,
147147
mut f: F,
148148
) -> Option<T> {
149+
// FIXME: This depends on the set of all impls for the trait. That is
150+
// unfortunate wrt. incremental compilation.
151+
//
152+
// If we want to be faster, we could have separate queries for
153+
// blanket and non-blanket impls, and compare them separately.
149154
let impls = self.trait_impls_of(def_id);
150155

151156
for &impl_def_id in impls.blanket_impls.iter() {
@@ -154,32 +159,16 @@ impl<'tcx> TyCtxt<'tcx> {
154159
}
155160
}
156161

157-
// simplify_type(.., false) basically replaces type parameters and
158-
// projections with infer-variables. This is, of course, done on
159-
// the impl trait-ref when it is instantiated, but not on the
160-
// predicate trait-ref which is passed here.
161-
//
162-
// for example, if we match `S: Copy` against an impl like
163-
// `impl<T:Copy> Copy for Option<T>`, we replace the type variable
164-
// in `Option<T>` with an infer variable, to `Option<_>` (this
165-
// doesn't actually change fast_reject output), but we don't
166-
// replace `S` with anything - this impl of course can't be
167-
// selected, and as there are hundreds of similar impls,
168-
// considering them would significantly harm performance.
169-
170-
// This depends on the set of all impls for the trait. That is
171-
// unfortunate. When we get red-green recompilation, we would like
172-
// to have a way of knowing whether the set of relevant impls
173-
// changed. The most naive
174-
// way would be to compute the Vec of relevant impls and see whether
175-
// it differs between compilations. That shouldn't be too slow by
176-
// itself - we do quite a bit of work for each relevant impl anyway.
177-
//
178-
// If we want to be faster, we could have separate queries for
179-
// blanket and non-blanket impls, and compare them separately.
162+
// Note that we're using `SimplifyParams::Yes` to query `non_blanket_impls` while using
163+
// `SimplifyParams::No` while actually adding them.
180164
//
181-
// I think we'll cross that bridge when we get to it.
182-
if let Some(simp) = fast_reject::simplify_type(self, self_ty, true) {
165+
// This way, when searching for some impl for `T: Trait`, we do not look at any impls
166+
// whose outer level is not a parameter or projection. Especially for things like
167+
// `T: Clone` this is incredibly useful as we would otherwise look at all the impls
168+
// of `Clone` for `Option<T>`, `Vec<T>`, `ConcreteType` and so on.
169+
if let Some(simp) =
170+
fast_reject::simplify_type(self, self_ty, SimplifyParams::Yes, StripReferences::No)
171+
{
183172
if let Some(impls) = impls.non_blanket_impls.get(&simp) {
184173
for &impl_def_id in impls {
185174
if let result @ Some(_) = f(impl_def_id) {
@@ -238,7 +227,9 @@ pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> Trait
238227
continue;
239228
}
240229

241-
if let Some(simplified_self_ty) = fast_reject::simplify_type(tcx, impl_self_ty, false) {
230+
if let Some(simplified_self_ty) =
231+
fast_reject::simplify_type(tcx, impl_self_ty, SimplifyParams::No, StripReferences::No)
232+
{
242233
impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
243234
} else {
244235
impls.blanket_impls.push(impl_def_id);

compiler/rustc_trait_selection/src/traits/coherence.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ use crate::traits::{
1212
self, Normalized, Obligation, ObligationCause, PredicateObligation, SelectionContext,
1313
};
1414
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
15+
use rustc_middle::ty::fast_reject::{self, SimplifyParams, StripReferences};
1516
use rustc_middle::ty::fold::TypeFoldable;
1617
use rustc_middle::ty::subst::Subst;
17-
use rustc_middle::ty::{self, fast_reject, Ty, TyCtxt};
18+
use rustc_middle::ty::{self, Ty, TyCtxt};
1819
use rustc_span::symbol::sym;
1920
use rustc_span::DUMMY_SP;
2021
use std::iter;
@@ -82,12 +83,11 @@ where
8283
impl2_ref.iter().flat_map(|tref| tref.substs.types()),
8384
)
8485
.any(|(ty1, ty2)| {
85-
let t1 = fast_reject::simplify_type(tcx, ty1, false);
86-
let t2 = fast_reject::simplify_type(tcx, ty2, false);
86+
let t1 = fast_reject::simplify_type(tcx, ty1, SimplifyParams::No, StripReferences::No);
87+
let t2 = fast_reject::simplify_type(tcx, ty2, SimplifyParams::No, StripReferences::No);
8788
if let (Some(t1), Some(t2)) = (t1, t2) {
8889
// Simplified successfully
89-
// Types cannot unify if they differ in their reference mutability or simplify to different types
90-
t1 != t2 || ty1.ref_mutability() != ty2.ref_mutability()
90+
t1 != t2
9191
} else {
9292
// Types might unify
9393
false

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

+22-4
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ use rustc_hir::Item;
2121
use rustc_hir::Node;
2222
use rustc_middle::thir::abstract_const::NotConstEvaluatable;
2323
use rustc_middle::ty::error::ExpectedFound;
24+
use rustc_middle::ty::fast_reject::{self, SimplifyParams, StripReferences};
2425
use rustc_middle::ty::fold::TypeFolder;
2526
use rustc_middle::ty::{
26-
self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
27-
TypeFoldable,
27+
self, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable,
2828
};
2929
use rustc_session::DiagnosticMessageId;
3030
use rustc_span::symbol::{kw, sym};
@@ -1440,14 +1440,32 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
14401440
&self,
14411441
trait_ref: ty::PolyTraitRef<'tcx>,
14421442
) -> Vec<ty::TraitRef<'tcx>> {
1443-
let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
1443+
// We simplify params and strip references here.
1444+
//
1445+
// This both removes a lot of unhelpful suggestions, e.g.
1446+
// when searching for `&Foo: Trait` it doesn't suggestion `impl Trait for &Bar`,
1447+
// while also suggesting impls for `&Foo` when we're looking for `Foo: Trait`.
1448+
//
1449+
// The second thing isn't necessarily always a good thing, but
1450+
// any other simple setup results in a far worse output, so 🤷
1451+
let simp = fast_reject::simplify_type(
1452+
self.tcx,
1453+
trait_ref.skip_binder().self_ty(),
1454+
SimplifyParams::Yes,
1455+
StripReferences::Yes,
1456+
);
14441457
let all_impls = self.tcx.all_impls(trait_ref.def_id());
14451458

14461459
match simp {
14471460
Some(simp) => all_impls
14481461
.filter_map(|def_id| {
14491462
let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1450-
let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
1463+
let imp_simp = fast_reject::simplify_type(
1464+
self.tcx,
1465+
imp.self_ty(),
1466+
SimplifyParams::Yes,
1467+
StripReferences::Yes,
1468+
);
14511469
if let Some(imp_simp) = imp_simp {
14521470
if simp != imp_simp {
14531471
return None;

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

+16-5
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ use rustc_infer::infer::LateBoundRegionConversionTime;
3535
use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
3636
use rustc_middle::mir::interpret::ErrorHandled;
3737
use rustc_middle::thir::abstract_const::NotConstEvaluatable;
38-
use rustc_middle::ty::fast_reject;
38+
use rustc_middle::ty::fast_reject::{self, SimplifyParams, StripReferences};
3939
use rustc_middle::ty::print::with_no_trimmed_paths;
4040
use rustc_middle::ty::relate::TypeRelation;
4141
use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
@@ -2089,10 +2089,21 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
20892089
|(obligation_arg, impl_arg)| {
20902090
match (obligation_arg.unpack(), impl_arg.unpack()) {
20912091
(GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2092-
let simplified_obligation_ty =
2093-
fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2094-
let simplified_impl_ty =
2095-
fast_reject::simplify_type(self.tcx(), impl_ty, false);
2092+
// Note, we simplify parameters for the obligation but not the
2093+
// impl so that we do not reject a blanket impl but do reject
2094+
// more concrete impls if we're searching for `T: Trait`.
2095+
let simplified_obligation_ty = fast_reject::simplify_type(
2096+
self.tcx(),
2097+
obligation_ty,
2098+
SimplifyParams::Yes,
2099+
StripReferences::No,
2100+
);
2101+
let simplified_impl_ty = fast_reject::simplify_type(
2102+
self.tcx(),
2103+
impl_ty,
2104+
SimplifyParams::No,
2105+
StripReferences::No,
2106+
);
20962107

20972108
simplified_obligation_ty.is_some()
20982109
&& simplified_impl_ty.is_some()

0 commit comments

Comments
 (0)