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