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