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