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::{ConstraintKind, 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.kind(), old_region.kind()) {
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 (c, _) in ®ions.constraints {
456 match c.kind {
457 ConstraintKind::VarSubVar => {
458 let sub_vid = c.sub.as_var();
459 let sup_vid = c.sup.as_var();
460 {
461 let deps1 = vid_map.entry(RegionTarget::RegionVid(sub_vid)).or_default();
462 deps1.larger.insert(RegionTarget::RegionVid(sup_vid));
463 }
464
465 let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default();
466 deps2.smaller.insert(RegionTarget::RegionVid(sub_vid));
467 }
468 ConstraintKind::RegSubVar => {
469 let sup_vid = c.sup.as_var();
470 {
471 let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default();
472 deps1.larger.insert(RegionTarget::RegionVid(sup_vid));
473 }
474
475 let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default();
476 deps2.smaller.insert(RegionTarget::Region(c.sub));
477 }
478 ConstraintKind::VarSubReg => {
479 let sub_vid = c.sub.as_var();
480 finished_map.insert(sub_vid, c.sup);
481 }
482 ConstraintKind::RegSubReg => {
483 {
484 let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default();
485 deps1.larger.insert(RegionTarget::Region(c.sup));
486 }
487
488 let deps2 = vid_map.entry(RegionTarget::Region(c.sup)).or_default();
489 deps2.smaller.insert(RegionTarget::Region(c.sub));
490 }
491 }
492 }
493
494 while !vid_map.is_empty() {
495 let target = *vid_map.keys().next().unwrap();
496 let deps = vid_map.swap_remove(&target).unwrap();
497
498 for smaller in deps.smaller.iter() {
499 for larger in deps.larger.iter() {
500 match (smaller, larger) {
501 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
502 if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) {
503 let smaller_deps = v.into_mut();
504 smaller_deps.larger.insert(*larger);
505 smaller_deps.larger.swap_remove(&target);
506 }
507
508 if let IndexEntry::Occupied(v) = vid_map.entry(*larger) {
509 let larger_deps = v.into_mut();
510 larger_deps.smaller.insert(*smaller);
511 larger_deps.smaller.swap_remove(&target);
512 }
513 }
514 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
515 finished_map.insert(v1, r1);
516 }
517 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
518 // Do nothing; we don't care about regions that are smaller than vids.
519 }
520 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
521 if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) {
522 let smaller_deps = v.into_mut();
523 smaller_deps.larger.insert(*larger);
524 smaller_deps.larger.swap_remove(&target);
525 }
526
527 if let IndexEntry::Occupied(v) = vid_map.entry(*larger) {
528 let larger_deps = v.into_mut();
529 larger_deps.smaller.insert(*smaller);
530 larger_deps.smaller.swap_remove(&target);
531 }
532 }
533 }
534 }
535 }
536 }
537
538 finished_map
539 }
540
541 fn is_param_no_infer(&self, args: GenericArgsRef<'tcx>) -> bool {
542 self.is_of_param(args.type_at(0)) && !args.types().any(|t| t.has_infer_types())
543 }
544
545 pub fn is_of_param(&self, ty: Ty<'tcx>) -> bool {
546 match ty.kind() {
547 ty::Param(_) => true,
548 ty::Alias(ty::Projection, p) => self.is_of_param(p.self_ty()),
549 _ => false,
550 }
551 }
552
553 fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'tcx>) -> bool {
554 if let Some(ty) = p.term().skip_binder().as_type() {
555 matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_term.expect_ty(self.tcx))
556 } else {
557 false
558 }
559 }
560
561 fn evaluate_nested_obligations(
562 &self,
563 ty: Ty<'_>,
564 nested: impl Iterator<Item = PredicateObligation<'tcx>>,
565 computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
566 fresh_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
567 predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>,
568 selcx: &mut SelectionContext<'_, 'tcx>,
569 ) -> bool {
570 let dummy_cause = ObligationCause::dummy();
571
572 for obligation in nested {
573 let is_new_pred =
574 fresh_preds.insert(self.clean_pred(selcx.infcx, obligation.predicate));
575
576 // Resolve any inference variables that we can, to help selection succeed
577 let predicate = selcx.infcx.resolve_vars_if_possible(obligation.predicate);
578
579 // We only add a predicate as a user-displayable bound if
580 // it involves a generic parameter, and doesn't contain
581 // any inference variables.
582 //
583 // Displaying a bound involving a concrete type (instead of a generic
584 // parameter) would be pointless, since it's always true
585 // (e.g. u8: Copy)
586 // Displaying an inference variable is impossible, since they're
587 // an internal compiler detail without a defined visual representation
588 //
589 // We check this by calling is_of_param on the relevant types
590 // from the various possible predicates
591
592 let bound_predicate = predicate.kind();
593 match bound_predicate.skip_binder() {
594 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => {
595 // Add this to `predicates` so that we end up calling `select`
596 // with it. If this predicate ends up being unimplemented,
597 // then `evaluate_predicates` will handle adding it the `ParamEnv`
598 // if possible.
599 predicates.push_back(bound_predicate.rebind(p));
600 }
601 ty::PredicateKind::Clause(ty::ClauseKind::Projection(p)) => {
602 let p = bound_predicate.rebind(p);
603 debug!(
604 "evaluate_nested_obligations: examining projection predicate {:?}",
605 predicate
606 );
607
608 // As described above, we only want to display
609 // bounds which include a generic parameter but don't include
610 // an inference variable.
611 // Additionally, we check if we've seen this predicate before,
612 // to avoid rendering duplicate bounds to the user.
613 if self.is_param_no_infer(p.skip_binder().projection_term.args)
614 && !p.term().skip_binder().has_infer_types()
615 && is_new_pred
616 {
617 debug!(
618 "evaluate_nested_obligations: adding projection predicate \
619 to computed_preds: {:?}",
620 predicate
621 );
622
623 // Under unusual circumstances, we can end up with a self-referential
624 // projection predicate. For example:
625 // <T as MyType>::Value == <T as MyType>::Value
626 // Not only is displaying this to the user pointless,
627 // having it in the ParamEnv will cause an issue if we try to call
628 // poly_project_and_unify_type on the predicate, since this kind of
629 // predicate will normally never end up in a ParamEnv.
630 //
631 // For these reasons, we ignore these weird predicates,
632 // ensuring that we're able to properly synthesize an auto trait impl
633 if self.is_self_referential_projection(p) {
634 debug!(
635 "evaluate_nested_obligations: encountered a projection
636 predicate equating a type with itself! Skipping"
637 );
638 } else {
639 self.add_user_pred(computed_preds, predicate);
640 }
641 }
642
643 // There are three possible cases when we project a predicate:
644 //
645 // 1. We encounter an error. This means that it's impossible for
646 // our current type to implement the auto trait - there's bound
647 // that we could add to our ParamEnv that would 'fix' this kind
648 // of error, as it's not caused by an unimplemented type.
649 //
650 // 2. We successfully project the predicate (Ok(Some(_))), generating
651 // some subobligations. We then process these subobligations
652 // like any other generated sub-obligations.
653 //
654 // 3. We receive an 'ambiguous' result (Ok(None))
655 // If we were actually trying to compile a crate,
656 // we would need to re-process this obligation later.
657 // However, all we care about is finding out what bounds
658 // are needed for our type to implement a particular auto trait.
659 // We've already added this obligation to our computed ParamEnv
660 // above (if it was necessary). Therefore, we don't need
661 // to do any further processing of the obligation.
662 //
663 // Note that we *must* try to project *all* projection predicates
664 // we encounter, even ones without inference variable.
665 // This ensures that we detect any projection errors,
666 // which indicate that our type can *never* implement the given
667 // auto trait. In that case, we will generate an explicit negative
668 // impl (e.g. 'impl !Send for MyType'). However, we don't
669 // try to process any of the generated subobligations -
670 // they contain no new information, since we already know
671 // that our type implements the projected-through trait,
672 // and can lead to weird region issues.
673 //
674 // Normally, we'll generate a negative impl as a result of encountering
675 // a type with an explicit negative impl of an auto trait
676 // (for example, raw pointers have !Send and !Sync impls)
677 // However, through some **interesting** manipulations of the type
678 // system, it's actually possible to write a type that never
679 // implements an auto trait due to a projection error, not a normal
680 // negative impl error. To properly handle this case, we need
681 // to ensure that we catch any potential projection errors,
682 // and turn them into an explicit negative impl for our type.
683 debug!("Projecting and unifying projection predicate {:?}", predicate);
684
685 match project::poly_project_and_unify_term(selcx, &obligation.with(self.tcx, p))
686 {
687 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
688 debug!(
689 "evaluate_nested_obligations: Unable to unify predicate \
690 '{:?}' '{:?}', bailing out",
691 ty, e
692 );
693 return false;
694 }
695 ProjectAndUnifyResult::Recursive => {
696 debug!("evaluate_nested_obligations: recursive projection predicate");
697 return false;
698 }
699 ProjectAndUnifyResult::Holds(v) => {
700 // We only care about sub-obligations
701 // when we started out trying to unify
702 // some inference variables. See the comment above
703 // for more information
704 if p.term().skip_binder().has_infer_types() {
705 if !self.evaluate_nested_obligations(
706 ty,
707 v.into_iter(),
708 computed_preds,
709 fresh_preds,
710 predicates,
711 selcx,
712 ) {
713 return false;
714 }
715 }
716 }
717 ProjectAndUnifyResult::FailedNormalization => {
718 // It's ok not to make progress when have no inference variables -
719 // in that case, we were only performing unification to check if an
720 // error occurred (which would indicate that it's impossible for our
721 // type to implement the auto trait).
722 // However, we should always make progress (either by generating
723 // subobligations or getting an error) when we started off with
724 // inference variables
725 if p.term().skip_binder().has_infer_types() {
726 panic!("Unexpected result when selecting {ty:?} {obligation:?}")
727 }
728 }
729 }
730 }
731 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(binder)) => {
732 let binder = bound_predicate.rebind(binder);
733 selcx.infcx.enter_forall(binder, |pred| {
734 selcx.infcx.register_region_outlives_constraint(pred, &dummy_cause);
735 });
736 }
737 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(binder)) => {
738 let binder = bound_predicate.rebind(binder);
739 match (
740 binder.no_bound_vars(),
741 binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
742 ) {
743 (None, Some(t_a)) => {
744 selcx.infcx.register_type_outlives_constraint(
745 t_a,
746 selcx.infcx.tcx.lifetimes.re_static,
747 &dummy_cause,
748 );
749 }
750 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
751 selcx.infcx.register_type_outlives_constraint(
752 t_a,
753 r_b,
754 &dummy_cause,
755 );
756 }
757 _ => {}
758 };
759 }
760 ty::PredicateKind::ConstEquate(c1, c2) => {
761 let evaluate = |c: ty::Const<'tcx>| {
762 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
763 let ct = super::try_evaluate_const(
764 selcx.infcx,
765 c,
766 obligation.param_env,
767 );
768
769 if let Err(EvaluateConstErr::InvalidConstParamTy(_)) = ct {
770 self.tcx.dcx().emit_err(UnableToConstructConstantValue {
771 span: self.tcx.def_span(unevaluated.def),
772 unevaluated,
773 });
774 }
775
776 ct
777 } else {
778 Ok(c)
779 }
780 };
781
782 match (evaluate(c1), evaluate(c2)) {
783 (Ok(c1), Ok(c2)) => {
784 match selcx.infcx.at(&obligation.cause, obligation.param_env).eq(DefineOpaqueTypes::Yes,c1, c2)
785 {
786 Ok(_) => (),
787 Err(_) => return false,
788 }
789 }
790 _ => return false,
791 }
792 }
793
794 // There's not really much we can do with these predicates -
795 // we start out with a `ParamEnv` with no inference variables,
796 // and these don't correspond to adding any new bounds to
797 // the `ParamEnv`.
798 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(..))
799 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
800 | ty::PredicateKind::NormalizesTo(..)
801 | ty::PredicateKind::AliasRelate(..)
802 | ty::PredicateKind::DynCompatible(..)
803 | ty::PredicateKind::Subtype(..)
804 // FIXME(generic_const_exprs): you can absolutely add this as a where clauses
805 | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
806 | ty::PredicateKind::Coerce(..)
807 | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_))
808 | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => {}
809 ty::PredicateKind::Ambiguous => return false,
810 };
811 }
812 true
813 }
814
815 pub fn clean_pred(
816 &self,
817 infcx: &InferCtxt<'tcx>,
818 p: ty::Predicate<'tcx>,
819 ) -> ty::Predicate<'tcx> {
820 infcx.freshen(p)
821 }
822}