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