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