]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_trait_selection/src/traits/auto_trait.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / auto_trait.rs
CommitLineData
60c5eb7d
XL
1//! Support code for rustdoc and external tools.
2//! You really don't want to be using this unless you need to.
94b46f34
XL
3
4use super::*;
5
f2b60f7d 6use crate::errors::UnableToConstructConstantValue;
9fa01778
XL
7use crate::infer::region_constraints::{Constraint, RegionConstraintData};
8use crate::infer::InferCtxt;
5e7ed085 9use crate::traits::project::ProjectAndUnifyResult;
353b0b11 10use rustc_infer::infer::DefineOpaqueTypes;
923072b8 11use rustc_middle::mir::interpret::ErrorHandled;
9ffffee4 12use rustc_middle::ty::visit::TypeVisitableExt;
487cf647 13use rustc_middle::ty::{ImplPolarity, Region, RegionVid};
94b46f34 14
487cf647 15use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
60c5eb7d
XL
16
17use std::collections::hash_map::Entry;
18use std::collections::VecDeque;
cdc7bbd5 19use std::iter;
60c5eb7d 20
94b46f34
XL
21// FIXME(twk): this is obviously not nice to duplicate like that
22#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
23pub enum RegionTarget<'tcx> {
24 Region(Region<'tcx>),
25 RegionVid(RegionVid),
26}
27
28#[derive(Default, Debug, Clone)]
29pub struct RegionDeps<'tcx> {
487cf647
FG
30 larger: FxIndexSet<RegionTarget<'tcx>>,
31 smaller: FxIndexSet<RegionTarget<'tcx>>,
94b46f34
XL
32}
33
34pub enum AutoTraitResult<A> {
35 ExplicitImpl,
36 PositiveImpl(A),
37 NegativeImpl,
38}
39
1b1a35ee 40#[allow(dead_code)]
94b46f34
XL
41impl<A> AutoTraitResult<A> {
42 fn is_auto(&self) -> bool {
5869c6ff 43 matches!(self, AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl)
94b46f34
XL
44 }
45}
46
47pub struct AutoTraitInfo<'cx> {
48 pub full_user_env: ty::ParamEnv<'cx>,
49 pub region_data: RegionConstraintData<'cx>,
94b46f34
XL
50 pub vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
51}
52
dc9dc135
XL
53pub struct AutoTraitFinder<'tcx> {
54 tcx: TyCtxt<'tcx>,
94b46f34
XL
55}
56
dc9dc135
XL
57impl<'tcx> AutoTraitFinder<'tcx> {
58 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
94b46f34
XL
59 AutoTraitFinder { tcx }
60 }
61
9fa01778 62 /// Makes a best effort to determine whether and under which conditions an auto trait is
94b46f34
XL
63 /// implemented for a type. For example, if you have
64 ///
65 /// ```
66 /// struct Foo<T> { data: Box<T> }
67 /// ```
0bf4aa26 68 ///
2b03887a
FG
69 /// then this might return that `Foo<T>: Send` if `T: Send` (encoded in the AutoTraitResult
70 /// type). The analysis attempts to account for custom impls as well as other complex cases.
71 /// This result is intended for use by rustdoc and other such consumers.
0bf4aa26 72 ///
94b46f34
XL
73 /// (Note that due to the coinductive nature of Send, the full and correct result is actually
74 /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field
2b03887a 75 /// types are all Send. So, in our example, we might have that `Foo<T>: Send` if `Box<T>: Send`.
94b46f34 76 /// But this is often not the best way to present to the user.)
0bf4aa26 77 ///
94b46f34
XL
78 /// Warning: The API should be considered highly unstable, and it may be refactored or removed
79 /// in the future.
80 pub fn find_auto_trait_generics<A>(
81 &self,
48663c56
XL
82 ty: Ty<'tcx>,
83 orig_env: ty::ParamEnv<'tcx>,
94b46f34 84 trait_did: DefId,
6a06907d 85 mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
94b46f34
XL
86 ) -> AutoTraitResult<A> {
87 let tcx = self.tcx;
94b46f34 88
49aad941 89 let trait_ref = ty::TraitRef::new(tcx, trait_did, [ty]);
94b46f34 90
2b03887a
FG
91 let infcx = tcx.infer_ctxt().build();
92 let mut selcx = SelectionContext::new(&infcx);
487cf647
FG
93 for polarity in [true, false] {
94 let result = selcx.select(&Obligation::new(
95 tcx,
96 ObligationCause::dummy(),
97 orig_env,
98 ty::Binder::dummy(ty::TraitPredicate {
99 trait_ref,
100 constness: ty::BoundConstness::NotConst,
101 polarity: if polarity {
102 ImplPolarity::Positive
103 } else {
104 ImplPolarity::Negative
105 },
106 }),
107 ));
2b03887a
FG
108 if let Ok(Some(ImplSource::UserDefined(_))) = result {
109 debug!(
110 "find_auto_trait_generics({:?}): \
111 manual impl found, bailing out",
112 trait_ref
113 );
114 // If an explicit impl exists, it always takes priority over an auto impl
115 return AutoTraitResult::ExplicitImpl;
5e7ed085 116 }
94b46f34
XL
117 }
118
2b03887a
FG
119 let infcx = tcx.infer_ctxt().build();
120 let mut fresh_preds = FxHashSet::default();
121
122 // Due to the way projections are handled by SelectionContext, we need to run
123 // evaluate_predicates twice: once on the original param env, and once on the result of
124 // the first evaluate_predicates call.
125 //
126 // The problem is this: most of rustc, including SelectionContext and traits::project,
127 // are designed to work with a concrete usage of a type (e.g., Vec<u8>
128 // fn<T>() { Vec<T> }. This information will generally never change - given
129 // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
130 // If we're unable to prove that 'T' implements a particular trait, we're done -
131 // there's nothing left to do but error out.
132 //
133 // However, synthesizing an auto trait impl works differently. Here, we start out with
134 // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
135 // with - and progressively discover the conditions we need to fulfill for it to
136 // implement a certain auto trait. This ends up breaking two assumptions made by trait
137 // selection and projection:
138 //
139 // * We can always cache the result of a particular trait selection for the lifetime of
140 // an InfCtxt
141 // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
142 // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
143 //
144 // We fix the first assumption by manually clearing out all of the InferCtxt's caches
145 // in between calls to SelectionContext.select. This allows us to keep all of the
146 // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
147 // them between calls.
148 //
149 // We fix the second assumption by reprocessing the result of our first call to
150 // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
151 // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
152 // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
153 // SelectionContext to return it back to us.
154
155 let Some((new_env, user_env)) = self.evaluate_predicates(
156 &infcx,
157 trait_did,
158 ty,
159 orig_env,
160 orig_env,
161 &mut fresh_preds,
2b03887a
FG
162 ) else {
163 return AutoTraitResult::NegativeImpl;
164 };
165
166 let (full_env, full_user_env) = self
9c376795 167 .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds)
2b03887a
FG
168 .unwrap_or_else(|| {
169 panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env)
170 });
94b46f34 171
2b03887a
FG
172 debug!(
173 "find_auto_trait_generics({:?}): fulfilling \
174 with {:?}",
175 trait_ref, full_env
176 );
177 infcx.clear_caches();
178
179 // At this point, we already have all of the bounds we need. FulfillmentContext is used
180 // to store all of the necessary region/lifetime bounds in the InferContext, as well as
181 // an additional sanity check.
353b0b11
FG
182 let ocx = ObligationCtxt::new(&infcx);
183 ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did);
184 let errors = ocx.select_all_or_error();
2b03887a
FG
185 if !errors.is_empty() {
186 panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors);
187 }
94b46f34 188
353b0b11
FG
189 let outlives_env = OutlivesEnvironment::new(full_env);
190 infcx.process_registered_region_obligations(&outlives_env);
94b46f34 191
2b03887a
FG
192 let region_data =
193 infcx.inner.borrow_mut().unwrap_region_constraints().region_constraint_data().clone();
94b46f34 194
2b03887a 195 let vid_to_region = self.map_vid_to_region(&region_data);
94b46f34 196
2b03887a 197 let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
94b46f34 198
2b03887a 199 AutoTraitResult::PositiveImpl(auto_trait_callback(info))
94b46f34
XL
200 }
201}
202
a2a8927a 203impl<'tcx> AutoTraitFinder<'tcx> {
60c5eb7d
XL
204 /// The core logic responsible for computing the bounds for our synthesized impl.
205 ///
206 /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
207 /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
208 /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
209 /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
210 /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
211 ///
212 /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
213 /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
214 /// user code. According, it considers all possible ways that a `Predicate` could be met, which
215 /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
216 /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
217 /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
218 /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
219 /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
220 /// like this:
04454e1e
FG
221 /// ```ignore (illustrative)
222 /// impl<T> Send for Foo<T> where T: IntoIterator
223 /// ```
60c5eb7d
XL
224 /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
225 /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
226 ///
227 /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
228 /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
229 /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
230 /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
231 /// needs to hold.
232 ///
233 /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
234 /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
235 /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
236 /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
353b0b11 237 /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate`, or
60c5eb7d
XL
238 /// else `SelectionContext` will choke on the missing predicates. However, this should never
239 /// show up in the final synthesized generics: we don't want our generated docs page to contain
240 /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
241 /// separate `user_env`, which only holds the predicates that will actually be displayed to the
242 /// user.
dc9dc135 243 fn evaluate_predicates(
94b46f34 244 &self,
2b03887a 245 infcx: &InferCtxt<'tcx>,
94b46f34 246 trait_did: DefId,
dc9dc135
XL
247 ty: Ty<'tcx>,
248 param_env: ty::ParamEnv<'tcx>,
249 user_env: ty::ParamEnv<'tcx>,
250 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
dc9dc135 251 ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
94b46f34
XL
252 let tcx = infcx.tcx;
253
5e7ed085 254 // Don't try to process any nested obligations involving predicates
3dfed10e
XL
255 // that are already in the `ParamEnv` (modulo regions): we already
256 // know that they must hold.
257 for predicate in param_env.caller_bounds() {
258 fresh_preds.insert(self.clean_pred(infcx, predicate));
259 }
260
5e7ed085 261 let mut select = SelectionContext::new(&infcx);
94b46f34 262
0bf4aa26 263 let mut already_visited = FxHashSet::default();
94b46f34 264 let mut predicates = VecDeque::new();
cdc7bbd5 265 predicates.push_back(ty::Binder::dummy(ty::TraitPredicate {
49aad941 266 trait_ref: ty::TraitRef::new(infcx.tcx, trait_did, [ty]),
487cf647 267
94222f64 268 constness: ty::BoundConstness::NotConst,
3c0e092e
XL
269 // Auto traits are positive
270 polarity: ty::ImplPolarity::Positive,
94b46f34
XL
271 }));
272
f035d41b 273 let computed_preds = param_env.caller_bounds().iter();
487cf647 274 let mut user_computed_preds: FxIndexSet<_> = user_env.caller_bounds().iter().collect();
94b46f34 275
48663c56 276 let mut new_env = param_env;
ba9703b0 277 let dummy_cause = ObligationCause::dummy();
94b46f34
XL
278
279 while let Some(pred) = predicates.pop_front() {
280 infcx.clear_caches();
281
48663c56 282 if !already_visited.insert(pred) {
94b46f34
XL
283 continue;
284 }
285
60c5eb7d 286 // Call `infcx.resolve_vars_if_possible` to see if we can
69743fb6 287 // get rid of any inference variables.
487cf647
FG
288 let obligation = infcx.resolve_vars_if_possible(Obligation::new(
289 tcx,
290 dummy_cause.clone(),
291 new_env,
292 pred,
293 ));
69743fb6 294 let result = select.select(&obligation);
94b46f34 295
5869c6ff
XL
296 match result {
297 Ok(Some(ref impl_source)) => {
60c5eb7d 298 // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
a1dfa0c6 299 // we immediately bail out, since it's impossible for us to continue.
ba9703b0 300
1b1a35ee
XL
301 if let ImplSource::UserDefined(ImplSourceUserDefinedData {
302 impl_def_id, ..
f035d41b
XL
303 }) = impl_source
304 {
ba9703b0
XL
305 // Blame 'tidy' for the weird bracket placement.
306 if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative {
307 debug!(
308 "evaluate_nested_obligations: found explicit negative impl\
dfeec247 309 {:?}, bailing out",
ba9703b0
XL
310 impl_def_id
311 );
312 return None;
dfeec247 313 }
a1dfa0c6
XL
314 }
315
f2b60f7d 316 let obligations = impl_source.borrow_nested_obligations().iter().cloned();
94b46f34
XL
317
318 if !self.evaluate_nested_obligations(
319 ty,
320 obligations,
321 &mut user_computed_preds,
322 fresh_preds,
323 &mut predicates,
324 &mut select,
94b46f34
XL
325 ) {
326 return None;
327 }
328 }
5869c6ff
XL
329 Ok(None) => {}
330 Err(SelectionError::Unimplemented) => {
69743fb6 331 if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) {
94b46f34 332 already_visited.remove(&pred);
94222f64 333 self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx));
94b46f34
XL
334 predicates.push_back(pred);
335 } else {
336 debug!(
60c5eb7d 337 "evaluate_nested_obligations: `Unimplemented` found, bailing: \
94b46f34
XL
338 {:?} {:?} {:?}",
339 ty,
340 pred,
341 pred.skip_binder().trait_ref.substs
342 );
343 return None;
344 }
345 }
346 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
347 };
348
353b0b11
FG
349 let normalized_preds =
350 elaborate(tcx, computed_preds.clone().chain(user_computed_preds.iter().cloned()));
a2a8927a 351 new_env = ty::ParamEnv::new(
9ffffee4 352 tcx.mk_predicates_from_iter(normalized_preds),
a2a8927a
XL
353 param_env.reveal(),
354 param_env.constness(),
355 );
94b46f34
XL
356 }
357
358 let final_user_env = ty::ParamEnv::new(
9ffffee4 359 tcx.mk_predicates_from_iter(user_computed_preds.into_iter()),
f035d41b 360 user_env.reveal(),
a2a8927a 361 user_env.constness(),
94b46f34
XL
362 );
363 debug!(
48663c56 364 "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
94b46f34 365 '{:?}'",
48663c56 366 ty, trait_did, new_env, final_user_env
94b46f34
XL
367 );
368
ba9703b0 369 Some((new_env, final_user_env))
94b46f34
XL
370 }
371
60c5eb7d
XL
372 /// This method is designed to work around the following issue:
373 /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
374 /// progressively building a `ParamEnv` based on the results we get.
375 /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
376 /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
377 ///
378 /// This can lead to a corner case when dealing with region parameters.
379 /// During our selection loop in `evaluate_predicates`, we might end up with
380 /// two trait predicates that differ only in their region parameters:
381 /// one containing a HRTB lifetime parameter, and one containing a 'normal'
382 /// lifetime parameter. For example:
04454e1e
FG
383 /// ```ignore (illustrative)
384 /// T as MyTrait<'a>
385 /// T as MyTrait<'static>
386 /// ```
60c5eb7d
XL
387 /// If we put both of these predicates in our computed `ParamEnv`, we'll
388 /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
389 ///
390 /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
391 /// Our end goal is to generate a user-visible description of the conditions
392 /// under which a type implements an auto trait. A trait predicate involving
393 /// a HRTB means that the type needs to work with any choice of lifetime,
394 /// not just one specific lifetime (e.g., `'static`).
3dfed10e 395 fn add_user_pred(
0bf4aa26 396 &self,
487cf647 397 user_computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
3dfed10e 398 new_pred: ty::Predicate<'tcx>,
0bf4aa26 399 ) {
b7449926
XL
400 let mut should_add_new = true;
401 user_computed_preds.retain(|&old_pred| {
487cf647
FG
402 if let (
403 ty::PredicateKind::Clause(ty::Clause::Trait(new_trait)),
404 ty::PredicateKind::Clause(ty::Clause::Trait(old_trait)),
405 ) = (new_pred.kind().skip_binder(), old_pred.kind().skip_binder())
ba9703b0
XL
406 {
407 if new_trait.def_id() == old_trait.def_id() {
3dfed10e
XL
408 let new_substs = new_trait.trait_ref.substs;
409 let old_substs = old_trait.trait_ref.substs;
ba9703b0
XL
410
411 if !new_substs.types().eq(old_substs.types()) {
412 // We can't compare lifetimes if the types are different,
413 // so skip checking `old_pred`.
414 return true;
415 }
b7449926 416
cdc7bbd5
XL
417 for (new_region, old_region) in
418 iter::zip(new_substs.regions(), old_substs.regions())
419 {
5099ac24 420 match (*new_region, *old_region) {
ba9703b0
XL
421 // If both predicates have an `ReLateBound` (a HRTB) in the
422 // same spot, we do nothing.
5099ac24 423 (ty::ReLateBound(_, _), ty::ReLateBound(_, _)) => {}
ba9703b0 424
5099ac24 425 (ty::ReLateBound(_, _), _) | (_, ty::ReVar(_)) => {
ba9703b0
XL
426 // One of these is true:
427 // The new predicate has a HRTB in a spot where the old
428 // predicate does not (if they both had a HRTB, the previous
429 // match arm would have executed). A HRBT is a 'stricter'
430 // bound than anything else, so we want to keep the newer
431 // predicate (with the HRBT) in place of the old predicate.
432 //
433 // OR
434 //
435 // The old predicate has a region variable where the new
436 // predicate has some other kind of region. An region
437 // variable isn't something we can actually display to a user,
438 // so we choose their new predicate (which doesn't have a region
439 // variable).
440 //
441 // In both cases, we want to remove the old predicate,
442 // from `user_computed_preds`, and replace it with the new
443 // one. Having both the old and the new
444 // predicate in a `ParamEnv` would confuse `SelectionContext`.
445 //
446 // We're currently in the predicate passed to 'retain',
447 // so we return `false` to remove the old predicate from
448 // `user_computed_preds`.
449 return false;
b7449926 450 }
5099ac24 451 (_, ty::ReLateBound(_, _)) | (ty::ReVar(_), _) => {
ba9703b0
XL
452 // This is the opposite situation as the previous arm.
453 // One of these is true:
454 //
455 // The old predicate has a HRTB lifetime in a place where the
456 // new predicate does not.
457 //
458 // OR
459 //
460 // The new predicate has a region variable where the old
461 // predicate has some other type of region.
462 //
463 // We want to leave the old
464 // predicate in `user_computed_preds`, and skip adding
465 // new_pred to `user_computed_params`.
466 should_add_new = false
467 }
468 _ => {}
b7449926
XL
469 }
470 }
0bf4aa26 471 }
b7449926 472 }
ba9703b0 473 true
b7449926
XL
474 });
475
476 if should_add_new {
477 user_computed_preds.insert(new_pred);
478 }
479 }
480
60c5eb7d
XL
481 /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
482 /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
48663c56 483 fn map_vid_to_region<'cx>(
94b46f34
XL
484 &self,
485 regions: &RegionConstraintData<'cx>,
486 ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
0bf4aa26
XL
487 let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default();
488 let mut finished_map = FxHashMap::default();
94b46f34
XL
489
490 for constraint in regions.constraints.keys() {
491 match constraint {
492 &Constraint::VarSubVar(r1, r2) => {
493 {
0bf4aa26 494 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
94b46f34
XL
495 deps1.larger.insert(RegionTarget::RegionVid(r2));
496 }
497
0bf4aa26 498 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
94b46f34
XL
499 deps2.smaller.insert(RegionTarget::RegionVid(r1));
500 }
501 &Constraint::RegSubVar(region, vid) => {
502 {
0bf4aa26 503 let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default();
94b46f34
XL
504 deps1.larger.insert(RegionTarget::RegionVid(vid));
505 }
506
0bf4aa26 507 let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
94b46f34
XL
508 deps2.smaller.insert(RegionTarget::Region(region));
509 }
510 &Constraint::VarSubReg(vid, region) => {
511 finished_map.insert(vid, region);
512 }
513 &Constraint::RegSubReg(r1, r2) => {
514 {
0bf4aa26 515 let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default();
94b46f34
XL
516 deps1.larger.insert(RegionTarget::Region(r2));
517 }
518
0bf4aa26 519 let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default();
94b46f34
XL
520 deps2.smaller.insert(RegionTarget::Region(r1));
521 }
522 }
523 }
524
525 while !vid_map.is_empty() {
dfeec247 526 let target = *vid_map.keys().next().expect("Keys somehow empty");
94b46f34
XL
527 let deps = vid_map.remove(&target).expect("Entry somehow missing");
528
529 for smaller in deps.smaller.iter() {
530 for larger in deps.larger.iter() {
531 match (smaller, larger) {
532 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
533 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
534 let smaller_deps = v.into_mut();
535 smaller_deps.larger.insert(*larger);
536 smaller_deps.larger.remove(&target);
537 }
538
539 if let Entry::Occupied(v) = vid_map.entry(*larger) {
540 let larger_deps = v.into_mut();
541 larger_deps.smaller.insert(*smaller);
542 larger_deps.smaller.remove(&target);
543 }
544 }
545 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
546 finished_map.insert(v1, r1);
547 }
548 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
60c5eb7d 549 // Do nothing; we don't care about regions that are smaller than vids.
94b46f34
XL
550 }
551 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
552 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
553 let smaller_deps = v.into_mut();
554 smaller_deps.larger.insert(*larger);
555 smaller_deps.larger.remove(&target);
556 }
557
558 if let Entry::Occupied(v) = vid_map.entry(*larger) {
559 let larger_deps = v.into_mut();
560 larger_deps.smaller.insert(*smaller);
561 larger_deps.smaller.remove(&target);
562 }
563 }
564 }
565 }
566 }
567 }
568 finished_map
569 }
570
532ac7d7 571 fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool {
ba9703b0 572 self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types())
69743fb6 573 }
94b46f34 574
69743fb6 575 pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
1b1a35ee 576 match ty.kind() {
b7449926 577 ty::Param(_) => true,
9c376795 578 ty::Alias(ty::Projection, p) => self.is_of_param(p.self_ty()),
94b46f34 579 _ => false,
ba9703b0 580 }
94b46f34
XL
581 }
582
69743fb6 583 fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool {
f2b60f7d 584 if let Some(ty) = p.term().skip_binder().ty() {
9c376795 585 matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_ty)
5099ac24
FG
586 } else {
587 false
588 }
69743fb6
XL
589 }
590
dc9dc135 591 fn evaluate_nested_obligations(
94b46f34 592 &self,
48663c56 593 ty: Ty<'_>,
49aad941 594 nested: impl Iterator<Item = PredicateObligation<'tcx>>,
487cf647 595 computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
dc9dc135
XL
596 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
597 predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>,
487cf647 598 selcx: &mut SelectionContext<'_, 'tcx>,
94b46f34 599 ) -> bool {
ba9703b0 600 let dummy_cause = ObligationCause::dummy();
94b46f34 601
3dfed10e
XL
602 for obligation in nested {
603 let is_new_pred =
487cf647 604 fresh_preds.insert(self.clean_pred(selcx.infcx, obligation.predicate));
94b46f34 605
69743fb6 606 // Resolve any inference variables that we can, to help selection succeed
487cf647 607 let predicate = selcx.infcx.resolve_vars_if_possible(obligation.predicate);
69743fb6
XL
608
609 // We only add a predicate as a user-displayable bound if
610 // it involves a generic parameter, and doesn't contain
611 // any inference variables.
612 //
613 // Displaying a bound involving a concrete type (instead of a generic
614 // parameter) would be pointless, since it's always true
615 // (e.g. u8: Copy)
616 // Displaying an inference variable is impossible, since they're
617 // an internal compiler detail without a defined visual representation
618 //
619 // We check this by calling is_of_param on the relevant types
620 // from the various possible predicates
3dfed10e 621
5869c6ff 622 let bound_predicate = predicate.kind();
29967ef6 623 match bound_predicate.skip_binder() {
487cf647 624 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => {
5869c6ff
XL
625 // Add this to `predicates` so that we end up calling `select`
626 // with it. If this predicate ends up being unimplemented,
627 // then `evaluate_predicates` will handle adding it the `ParamEnv`
628 // if possible.
29967ef6 629 predicates.push_back(bound_predicate.rebind(p));
94b46f34 630 }
487cf647 631 ty::PredicateKind::Clause(ty::Clause::Projection(p)) => {
29967ef6 632 let p = bound_predicate.rebind(p);
dfeec247
XL
633 debug!(
634 "evaluate_nested_obligations: examining projection predicate {:?}",
635 predicate
636 );
69743fb6
XL
637
638 // As described above, we only want to display
639 // bounds which include a generic parameter but don't include
640 // an inference variable.
641 // Additionally, we check if we've seen this predicate before,
642 // to avoid rendering duplicate bounds to the user.
643 if self.is_param_no_infer(p.skip_binder().projection_ty.substs)
5099ac24 644 && !p.term().skip_binder().has_infer_types()
dfeec247
XL
645 && is_new_pred
646 {
647 debug!(
5e7ed085 648 "evaluate_nested_obligations: adding projection predicate \
dfeec247
XL
649 to computed_preds: {:?}",
650 predicate
651 );
652
5e7ed085 653 // Under unusual circumstances, we can end up with a self-referential
dfeec247
XL
654 // projection predicate. For example:
655 // <T as MyType>::Value == <T as MyType>::Value
656 // Not only is displaying this to the user pointless,
657 // having it in the ParamEnv will cause an issue if we try to call
658 // poly_project_and_unify_type on the predicate, since this kind of
659 // predicate will normally never end up in a ParamEnv.
660 //
661 // For these reasons, we ignore these weird predicates,
662 // ensuring that we're able to properly synthesize an auto trait impl
663 if self.is_self_referential_projection(p) {
664 debug!(
665 "evaluate_nested_obligations: encountered a projection
666 predicate equating a type with itself! Skipping"
667 );
668 } else {
669 self.add_user_pred(computed_preds, predicate);
670 }
69743fb6
XL
671 }
672
dc9dc135
XL
673 // There are three possible cases when we project a predicate:
674 //
675 // 1. We encounter an error. This means that it's impossible for
676 // our current type to implement the auto trait - there's bound
677 // that we could add to our ParamEnv that would 'fix' this kind
678 // of error, as it's not caused by an unimplemented type.
679 //
60c5eb7d 680 // 2. We successfully project the predicate (Ok(Some(_))), generating
dc9dc135
XL
681 // some subobligations. We then process these subobligations
682 // like any other generated sub-obligations.
683 //
74b04a01 684 // 3. We receive an 'ambiguous' result (Ok(None))
dc9dc135
XL
685 // If we were actually trying to compile a crate,
686 // we would need to re-process this obligation later.
687 // However, all we care about is finding out what bounds
688 // are needed for our type to implement a particular auto trait.
689 // We've already added this obligation to our computed ParamEnv
690 // above (if it was necessary). Therefore, we don't need
691 // to do any further processing of the obligation.
692 //
693 // Note that we *must* try to project *all* projection predicates
694 // we encounter, even ones without inference variable.
695 // This ensures that we detect any projection errors,
696 // which indicate that our type can *never* implement the given
697 // auto trait. In that case, we will generate an explicit negative
698 // impl (e.g. 'impl !Send for MyType'). However, we don't
699 // try to process any of the generated subobligations -
700 // they contain no new information, since we already know
701 // that our type implements the projected-through trait,
702 // and can lead to weird region issues.
703 //
704 // Normally, we'll generate a negative impl as a result of encountering
705 // a type with an explicit negative impl of an auto trait
706 // (for example, raw pointers have !Send and !Sync impls)
707 // However, through some **interesting** manipulations of the type
708 // system, it's actually possible to write a type that never
709 // implements an auto trait due to a projection error, not a normal
710 // negative impl error. To properly handle this case, we need
711 // to ensure that we catch any potential projection errors,
712 // and turn them into an explicit negative impl for our type.
dfeec247 713 debug!("Projecting and unifying projection predicate {:?}", predicate);
dc9dc135 714
487cf647
FG
715 match project::poly_project_and_unify_type(selcx, &obligation.with(self.tcx, p))
716 {
5e7ed085 717 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
dc9dc135
XL
718 debug!(
719 "evaluate_nested_obligations: Unable to unify predicate \
720 '{:?}' '{:?}', bailing out",
721 ty, e
722 );
723 return false;
724 }
5e7ed085 725 ProjectAndUnifyResult::Recursive => {
f9652781
XL
726 debug!("evaluate_nested_obligations: recursive projection predicate");
727 return false;
728 }
5e7ed085 729 ProjectAndUnifyResult::Holds(v) => {
dc9dc135
XL
730 // We only care about sub-obligations
731 // when we started out trying to unify
732 // some inference variables. See the comment above
5e7ed085 733 // for more information
5099ac24 734 if p.term().skip_binder().has_infer_types() {
94b46f34
XL
735 if !self.evaluate_nested_obligations(
736 ty,
ba9703b0 737 v.into_iter(),
94b46f34
XL
738 computed_preds,
739 fresh_preds,
740 predicates,
487cf647 741 selcx,
94b46f34
XL
742 ) {
743 return false;
744 }
745 }
dc9dc135 746 }
5e7ed085 747 ProjectAndUnifyResult::FailedNormalization => {
f9652781 748 // It's ok not to make progress when have no inference variables -
5e7ed085 749 // in that case, we were only performing unification to check if an
60c5eb7d 750 // error occurred (which would indicate that it's impossible for our
dc9dc135
XL
751 // type to implement the auto trait).
752 // However, we should always make progress (either by generating
753 // subobligations or getting an error) when we started off with
754 // inference variables
5099ac24 755 if p.term().skip_binder().has_infer_types() {
94b46f34
XL
756 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
757 }
758 }
759 }
760 }
487cf647 761 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(binder)) => {
29967ef6 762 let binder = bound_predicate.rebind(binder);
487cf647 763 selcx.infcx.region_outlives_predicate(&dummy_cause, binder)
94b46f34 764 }
487cf647 765 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(binder)) => {
29967ef6 766 let binder = bound_predicate.rebind(binder);
94b46f34 767 match (
a1dfa0c6
XL
768 binder.no_bound_vars(),
769 binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
94b46f34
XL
770 ) {
771 (None, Some(t_a)) => {
487cf647 772 selcx.infcx.register_region_obligation_with_cause(
0bf4aa26 773 t_a,
487cf647 774 selcx.infcx.tcx.lifetimes.re_static,
0bf4aa26 775 &dummy_cause,
94b46f34
XL
776 );
777 }
778 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
487cf647 779 selcx.infcx.register_region_obligation_with_cause(
0bf4aa26
XL
780 t_a,
781 r_b,
782 &dummy_cause,
94b46f34
XL
783 );
784 }
785 _ => {}
786 };
787 }
5869c6ff 788 ty::PredicateKind::ConstEquate(c1, c2) => {
5099ac24 789 let evaluate = |c: ty::Const<'tcx>| {
923072b8 790 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
487cf647 791 match selcx.infcx.const_eval_resolve(
3dfed10e 792 obligation.param_env,
cdc7bbd5 793 unevaluated,
3dfed10e
XL
794 Some(obligation.cause.span),
795 ) {
487cf647 796 Ok(Some(valtree)) => Ok(selcx.tcx().mk_const(valtree, c.ty())),
923072b8
FG
797 Ok(None) => {
798 let tcx = self.tcx;
f2b60f7d
FG
799 let reported =
800 tcx.sess.emit_err(UnableToConstructConstantValue {
49aad941 801 span: tcx.def_span(unevaluated.def),
2b03887a 802 unevaluated: unevaluated,
f2b60f7d 803 });
49aad941 804 Err(ErrorHandled::Reported(reported.into()))
923072b8 805 }
3dfed10e
XL
806 Err(err) => Err(err),
807 }
808 } else {
809 Ok(c)
810 }
811 };
812
813 match (evaluate(c1), evaluate(c2)) {
814 (Ok(c1), Ok(c2)) => {
353b0b11 815 match selcx.infcx.at(&obligation.cause, obligation.param_env).eq(DefineOpaqueTypes::No,c1, c2)
3dfed10e
XL
816 {
817 Ok(_) => (),
818 Err(_) => return false,
819 }
820 }
821 _ => return false,
822 }
823 }
9ffffee4 824
a2a8927a
XL
825 // There's not really much we can do with these predicates -
826 // we start out with a `ParamEnv` with no inference variables,
827 // and these don't correspond to adding any new bounds to
828 // the `ParamEnv`.
829 ty::PredicateKind::WellFormed(..)
9ffffee4 830 | ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(..))
353b0b11 831 | ty::PredicateKind::AliasRelate(..)
a2a8927a
XL
832 | ty::PredicateKind::ObjectSafe(..)
833 | ty::PredicateKind::ClosureKind(..)
834 | ty::PredicateKind::Subtype(..)
9ffffee4 835 // FIXME(generic_const_exprs): you can absolutely add this as a where clauses
a2a8927a 836 | ty::PredicateKind::ConstEvaluatable(..)
49aad941
FG
837 | ty::PredicateKind::Coerce(..) => {}
838 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
839 bug!("predicate should only exist in the environment: {bound_predicate:?}")
840 }
487cf647 841 ty::PredicateKind::Ambiguous => return false,
94b46f34
XL
842 };
843 }
ba9703b0 844 true
94b46f34
XL
845 }
846
dc9dc135 847 pub fn clean_pred(
94b46f34 848 &self,
2b03887a 849 infcx: &InferCtxt<'tcx>,
dc9dc135
XL
850 p: ty::Predicate<'tcx>,
851 ) -> ty::Predicate<'tcx> {
94b46f34
XL
852 infcx.freshen(p)
853 }
854}