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