1 //! Support code for rustdoc and external tools.
2 //! You really don't want to be using this unless you need to.
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};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use std::collections::hash_map::Entry;
14 use std::collections::VecDeque;
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> {
24 #[derive(Default, Debug, Clone)]
25 pub struct RegionDeps<'tcx> {
26 larger: FxHashSet<RegionTarget<'tcx>>,
27 smaller: FxHashSet<RegionTarget<'tcx>>,
30 pub enum AutoTraitResult<A> {
37 impl<A> AutoTraitResult<A> {
38 fn is_auto(&self) -> bool {
39 matches!(self, AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl)
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>>,
49 pub struct AutoTraitFinder<'tcx> {
53 impl<'tcx> AutoTraitFinder<'tcx> {
54 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
55 AutoTraitFinder { tcx }
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
62 /// struct Foo<T> { data: Box<T> }
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.
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.)
74 /// Warning: The API should be considered highly unstable, and it may be refactored or removed
76 pub fn find_auto_trait_generics<A>(
79 orig_env: ty::ParamEnv<'tcx>,
81 mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
82 ) -> AutoTraitResult<A> {
85 let trait_ref = ty::TraitRef { def_id: trait_did, substs: tcx.mk_substs_trait(ty, &[]) };
87 let trait_pred = ty::Binder::dummy(trait_ref);
89 let bail_out = tcx.infer_ctxt().enter(|infcx| {
90 let mut selcx = SelectionContext::new(&infcx);
91 let result = selcx.select(&Obligation::new(
92 ObligationCause::dummy(),
94 trait_pred.to_poly_trait_predicate(),
98 Ok(Some(ImplSource::UserDefined(_))) => {
100 "find_auto_trait_generics({:?}): \
101 manual impl found, bailing out",
109 let result = selcx.select(&Obligation::new(
110 ObligationCause::dummy(),
112 trait_pred.to_poly_trait_predicate_negative_polarity(),
116 Ok(Some(ImplSource::UserDefined(_))) => {
118 "find_auto_trait_generics({:?}): \
119 manual impl found, bailing out",
128 // If an explicit impl exists, it always takes priority over an auto impl
130 return AutoTraitResult::ExplicitImpl;
133 tcx.infer_ctxt().enter(|infcx| {
134 let mut fresh_preds = FxHashSet::default();
136 // Due to the way projections are handled by SelectionContext, we need to run
137 // evaluate_predicates twice: once on the original param env, and once on the result of
138 // the first evaluate_predicates call.
140 // The problem is this: most of rustc, including SelectionContext and traits::project,
141 // are designed to work with a concrete usage of a type (e.g., Vec<u8>
142 // fn<T>() { Vec<T> }. This information will generally never change - given
143 // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
144 // If we're unable to prove that 'T' implements a particular trait, we're done -
145 // there's nothing left to do but error out.
147 // However, synthesizing an auto trait impl works differently. Here, we start out with
148 // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
149 // with - and progressively discover the conditions we need to fulfill for it to
150 // implement a certain auto trait. This ends up breaking two assumptions made by trait
151 // selection and projection:
153 // * We can always cache the result of a particular trait selection for the lifetime of
155 // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
156 // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
158 // We fix the first assumption by manually clearing out all of the InferCtxt's caches
159 // in between calls to SelectionContext.select. This allows us to keep all of the
160 // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
161 // them between calls.
163 // We fix the second assumption by reprocessing the result of our first call to
164 // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
165 // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
166 // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
167 // SelectionContext to return it back to us.
169 let Some((new_env, user_env)) = self.evaluate_predicates(
178 return AutoTraitResult::NegativeImpl;
181 let (full_env, full_user_env) = self
182 .evaluate_predicates(
192 panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env)
196 "find_auto_trait_generics({:?}): fulfilling \
200 infcx.clear_caches();
202 // At this point, we already have all of the bounds we need. FulfillmentContext is used
203 // to store all of the necessary region/lifetime bounds in the InferContext, as well as
204 // an additional sanity check.
205 let mut fulfill = FulfillmentContext::new();
206 fulfill.register_bound(&infcx, full_env, ty, trait_did, ObligationCause::dummy());
207 let errors = fulfill.select_all_or_error(&infcx);
209 if !errors.is_empty() {
210 panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors);
213 let body_id_map: FxHashMap<_, _> = infcx
216 .region_obligations()
218 .map(|&(id, _)| (id, vec![]))
221 infcx.process_registered_region_obligations(&body_id_map, None, full_env);
223 let region_data = infcx
226 .unwrap_region_constraints()
227 .region_constraint_data()
230 let vid_to_region = self.map_vid_to_region(®ion_data);
232 let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
234 AutoTraitResult::PositiveImpl(auto_trait_callback(info))
239 impl<'tcx> AutoTraitFinder<'tcx> {
240 /// The core logic responsible for computing the bounds for our synthesized impl.
242 /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
243 /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
244 /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
245 /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
246 /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
248 /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
249 /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
250 /// user code. According, it considers all possible ways that a `Predicate` could be met, which
251 /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
252 /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
253 /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
254 /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
255 /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
258 /// impl<T> Send for Foo<T> where T: IntoIterator
260 /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
261 /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
263 /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
264 /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
265 /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
266 /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
269 /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
270 /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
271 /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
272 /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
273 /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate_predicates`, or
274 /// else `SelectionContext` will choke on the missing predicates. However, this should never
275 /// show up in the final synthesized generics: we don't want our generated docs page to contain
276 /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
277 /// separate `user_env`, which only holds the predicates that will actually be displayed to the
279 fn evaluate_predicates(
281 infcx: &InferCtxt<'_, 'tcx>,
284 param_env: ty::ParamEnv<'tcx>,
285 user_env: ty::ParamEnv<'tcx>,
286 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
287 only_projections: bool,
288 ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
291 // Don't try to process any nested obligations involving predicates
292 // that are already in the `ParamEnv` (modulo regions): we already
293 // know that they must hold.
294 for predicate in param_env.caller_bounds() {
295 fresh_preds.insert(self.clean_pred(infcx, predicate));
298 let mut select = SelectionContext::new(&infcx);
300 let mut already_visited = FxHashSet::default();
301 let mut predicates = VecDeque::new();
302 predicates.push_back(ty::Binder::dummy(ty::TraitPredicate {
303 trait_ref: ty::TraitRef {
305 substs: infcx.tcx.mk_substs_trait(ty, &[]),
307 constness: ty::BoundConstness::NotConst,
308 // Auto traits are positive
309 polarity: ty::ImplPolarity::Positive,
312 let computed_preds = param_env.caller_bounds().iter();
313 let mut user_computed_preds: FxHashSet<_> = user_env.caller_bounds().iter().collect();
315 let mut new_env = param_env;
316 let dummy_cause = ObligationCause::dummy();
318 while let Some(pred) = predicates.pop_front() {
319 infcx.clear_caches();
321 if !already_visited.insert(pred) {
325 // Call `infcx.resolve_vars_if_possible` to see if we can
326 // get rid of any inference variables.
328 infcx.resolve_vars_if_possible(Obligation::new(dummy_cause.clone(), new_env, pred));
329 let result = select.select(&obligation);
332 Ok(Some(ref impl_source)) => {
333 // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
334 // we immediately bail out, since it's impossible for us to continue.
336 if let ImplSource::UserDefined(ImplSourceUserDefinedData {
340 // Blame 'tidy' for the weird bracket placement.
341 if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative {
343 "evaluate_nested_obligations: found explicit negative impl\
351 let obligations = impl_source.clone().nested_obligations().into_iter();
353 if !self.evaluate_nested_obligations(
356 &mut user_computed_preds,
366 Err(SelectionError::Unimplemented) => {
367 if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) {
368 already_visited.remove(&pred);
369 self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx));
370 predicates.push_back(pred);
373 "evaluate_nested_obligations: `Unimplemented` found, bailing: \
377 pred.skip_binder().trait_ref.substs
382 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
385 let normalized_preds = elaborate_predicates(
387 computed_preds.clone().chain(user_computed_preds.iter().cloned()),
389 .map(|o| o.predicate);
390 new_env = ty::ParamEnv::new(
391 tcx.mk_predicates(normalized_preds),
393 param_env.constness(),
397 let final_user_env = ty::ParamEnv::new(
398 tcx.mk_predicates(user_computed_preds.into_iter()),
400 user_env.constness(),
403 "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
405 ty, trait_did, new_env, final_user_env
408 Some((new_env, final_user_env))
411 /// This method is designed to work around the following issue:
412 /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
413 /// progressively building a `ParamEnv` based on the results we get.
414 /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
415 /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
417 /// This can lead to a corner case when dealing with region parameters.
418 /// During our selection loop in `evaluate_predicates`, we might end up with
419 /// two trait predicates that differ only in their region parameters:
420 /// one containing a HRTB lifetime parameter, and one containing a 'normal'
421 /// lifetime parameter. For example:
424 /// T as MyTrait<'static>
426 /// If we put both of these predicates in our computed `ParamEnv`, we'll
427 /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
429 /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
430 /// Our end goal is to generate a user-visible description of the conditions
431 /// under which a type implements an auto trait. A trait predicate involving
432 /// a HRTB means that the type needs to work with any choice of lifetime,
433 /// not just one specific lifetime (e.g., `'static`).
436 user_computed_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
437 new_pred: ty::Predicate<'tcx>,
439 let mut should_add_new = true;
440 user_computed_preds.retain(|&old_pred| {
441 if let (ty::PredicateKind::Trait(new_trait), ty::PredicateKind::Trait(old_trait)) =
442 (new_pred.kind().skip_binder(), old_pred.kind().skip_binder())
444 if new_trait.def_id() == old_trait.def_id() {
445 let new_substs = new_trait.trait_ref.substs;
446 let old_substs = old_trait.trait_ref.substs;
448 if !new_substs.types().eq(old_substs.types()) {
449 // We can't compare lifetimes if the types are different,
450 // so skip checking `old_pred`.
454 for (new_region, old_region) in
455 iter::zip(new_substs.regions(), old_substs.regions())
457 match (*new_region, *old_region) {
458 // If both predicates have an `ReLateBound` (a HRTB) in the
459 // same spot, we do nothing.
460 (ty::ReLateBound(_, _), ty::ReLateBound(_, _)) => {}
462 (ty::ReLateBound(_, _), _) | (_, ty::ReVar(_)) => {
463 // One of these is true:
464 // The new predicate has a HRTB in a spot where the old
465 // predicate does not (if they both had a HRTB, the previous
466 // match arm would have executed). A HRBT is a 'stricter'
467 // bound than anything else, so we want to keep the newer
468 // predicate (with the HRBT) in place of the old predicate.
472 // The old predicate has a region variable where the new
473 // predicate has some other kind of region. An region
474 // variable isn't something we can actually display to a user,
475 // so we choose their new predicate (which doesn't have a region
478 // In both cases, we want to remove the old predicate,
479 // from `user_computed_preds`, and replace it with the new
480 // one. Having both the old and the new
481 // predicate in a `ParamEnv` would confuse `SelectionContext`.
483 // We're currently in the predicate passed to 'retain',
484 // so we return `false` to remove the old predicate from
485 // `user_computed_preds`.
488 (_, ty::ReLateBound(_, _)) | (ty::ReVar(_), _) => {
489 // This is the opposite situation as the previous arm.
490 // One of these is true:
492 // The old predicate has a HRTB lifetime in a place where the
493 // new predicate does not.
497 // The new predicate has a region variable where the old
498 // predicate has some other type of region.
500 // We want to leave the old
501 // predicate in `user_computed_preds`, and skip adding
502 // new_pred to `user_computed_params`.
503 should_add_new = false
514 user_computed_preds.insert(new_pred);
518 /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
519 /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
520 fn map_vid_to_region<'cx>(
522 regions: &RegionConstraintData<'cx>,
523 ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
524 let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default();
525 let mut finished_map = FxHashMap::default();
527 for constraint in regions.constraints.keys() {
529 &Constraint::VarSubVar(r1, r2) => {
531 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
532 deps1.larger.insert(RegionTarget::RegionVid(r2));
535 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
536 deps2.smaller.insert(RegionTarget::RegionVid(r1));
538 &Constraint::RegSubVar(region, vid) => {
540 let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default();
541 deps1.larger.insert(RegionTarget::RegionVid(vid));
544 let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
545 deps2.smaller.insert(RegionTarget::Region(region));
547 &Constraint::VarSubReg(vid, region) => {
548 finished_map.insert(vid, region);
550 &Constraint::RegSubReg(r1, r2) => {
552 let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default();
553 deps1.larger.insert(RegionTarget::Region(r2));
556 let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default();
557 deps2.smaller.insert(RegionTarget::Region(r1));
562 while !vid_map.is_empty() {
563 let target = *vid_map.keys().next().expect("Keys somehow empty");
564 let deps = vid_map.remove(&target).expect("Entry somehow missing");
566 for smaller in deps.smaller.iter() {
567 for larger in deps.larger.iter() {
568 match (smaller, larger) {
569 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
570 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
571 let smaller_deps = v.into_mut();
572 smaller_deps.larger.insert(*larger);
573 smaller_deps.larger.remove(&target);
576 if let Entry::Occupied(v) = vid_map.entry(*larger) {
577 let larger_deps = v.into_mut();
578 larger_deps.smaller.insert(*smaller);
579 larger_deps.smaller.remove(&target);
582 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
583 finished_map.insert(v1, r1);
585 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
586 // Do nothing; we don't care about regions that are smaller than vids.
588 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
589 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
590 let smaller_deps = v.into_mut();
591 smaller_deps.larger.insert(*larger);
592 smaller_deps.larger.remove(&target);
595 if let Entry::Occupied(v) = vid_map.entry(*larger) {
596 let larger_deps = v.into_mut();
597 larger_deps.smaller.insert(*smaller);
598 larger_deps.smaller.remove(&target);
608 fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool {
609 self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types())
612 pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
614 ty::Param(_) => true,
615 ty::Projection(p) => self.is_of_param(p.self_ty()),
620 fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool {
621 if let Term::Ty(ty) = p.term().skip_binder() {
622 matches!(ty.kind(), ty::Projection(proj) if proj == &p.skip_binder().projection_ty)
628 fn evaluate_nested_obligations(
631 nested: impl Iterator<Item = Obligation<'tcx, ty::Predicate<'tcx>>>,
632 computed_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
633 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
634 predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>,
635 select: &mut SelectionContext<'_, 'tcx>,
636 only_projections: bool,
638 let dummy_cause = ObligationCause::dummy();
640 for obligation in nested {
642 fresh_preds.insert(self.clean_pred(select.infcx(), obligation.predicate));
644 // Resolve any inference variables that we can, to help selection succeed
645 let predicate = select.infcx().resolve_vars_if_possible(obligation.predicate);
647 // We only add a predicate as a user-displayable bound if
648 // it involves a generic parameter, and doesn't contain
649 // any inference variables.
651 // Displaying a bound involving a concrete type (instead of a generic
652 // parameter) would be pointless, since it's always true
654 // Displaying an inference variable is impossible, since they're
655 // an internal compiler detail without a defined visual representation
657 // We check this by calling is_of_param on the relevant types
658 // from the various possible predicates
660 let bound_predicate = predicate.kind();
661 match bound_predicate.skip_binder() {
662 ty::PredicateKind::Trait(p) => {
663 // Add this to `predicates` so that we end up calling `select`
664 // with it. If this predicate ends up being unimplemented,
665 // then `evaluate_predicates` will handle adding it the `ParamEnv`
667 predicates.push_back(bound_predicate.rebind(p));
669 ty::PredicateKind::Projection(p) => {
670 let p = bound_predicate.rebind(p);
672 "evaluate_nested_obligations: examining projection predicate {:?}",
676 // As described above, we only want to display
677 // bounds which include a generic parameter but don't include
678 // an inference variable.
679 // Additionally, we check if we've seen this predicate before,
680 // to avoid rendering duplicate bounds to the user.
681 if self.is_param_no_infer(p.skip_binder().projection_ty.substs)
682 && !p.term().skip_binder().has_infer_types()
686 "evaluate_nested_obligations: adding projection predicate \
687 to computed_preds: {:?}",
691 // Under unusual circumstances, we can end up with a self-referential
692 // projection predicate. For example:
693 // <T as MyType>::Value == <T as MyType>::Value
694 // Not only is displaying this to the user pointless,
695 // having it in the ParamEnv will cause an issue if we try to call
696 // poly_project_and_unify_type on the predicate, since this kind of
697 // predicate will normally never end up in a ParamEnv.
699 // For these reasons, we ignore these weird predicates,
700 // ensuring that we're able to properly synthesize an auto trait impl
701 if self.is_self_referential_projection(p) {
703 "evaluate_nested_obligations: encountered a projection
704 predicate equating a type with itself! Skipping"
707 self.add_user_pred(computed_preds, predicate);
711 // There are three possible cases when we project a predicate:
713 // 1. We encounter an error. This means that it's impossible for
714 // our current type to implement the auto trait - there's bound
715 // that we could add to our ParamEnv that would 'fix' this kind
716 // of error, as it's not caused by an unimplemented type.
718 // 2. We successfully project the predicate (Ok(Some(_))), generating
719 // some subobligations. We then process these subobligations
720 // like any other generated sub-obligations.
722 // 3. We receive an 'ambiguous' result (Ok(None))
723 // If we were actually trying to compile a crate,
724 // we would need to re-process this obligation later.
725 // However, all we care about is finding out what bounds
726 // are needed for our type to implement a particular auto trait.
727 // We've already added this obligation to our computed ParamEnv
728 // above (if it was necessary). Therefore, we don't need
729 // to do any further processing of the obligation.
731 // Note that we *must* try to project *all* projection predicates
732 // we encounter, even ones without inference variable.
733 // This ensures that we detect any projection errors,
734 // which indicate that our type can *never* implement the given
735 // auto trait. In that case, we will generate an explicit negative
736 // impl (e.g. 'impl !Send for MyType'). However, we don't
737 // try to process any of the generated subobligations -
738 // they contain no new information, since we already know
739 // that our type implements the projected-through trait,
740 // and can lead to weird region issues.
742 // Normally, we'll generate a negative impl as a result of encountering
743 // a type with an explicit negative impl of an auto trait
744 // (for example, raw pointers have !Send and !Sync impls)
745 // However, through some **interesting** manipulations of the type
746 // system, it's actually possible to write a type that never
747 // implements an auto trait due to a projection error, not a normal
748 // negative impl error. To properly handle this case, we need
749 // to ensure that we catch any potential projection errors,
750 // and turn them into an explicit negative impl for our type.
751 debug!("Projecting and unifying projection predicate {:?}", predicate);
753 match project::poly_project_and_unify_type(select, &obligation.with(p)) {
756 "evaluate_nested_obligations: Unable to unify predicate \
757 '{:?}' '{:?}', bailing out",
762 Ok(Err(project::InProgress)) => {
763 debug!("evaluate_nested_obligations: recursive projection predicate");
767 // We only care about sub-obligations
768 // when we started out trying to unify
769 // some inference variables. See the comment above
770 // for more information
771 if p.term().skip_binder().has_infer_types() {
772 if !self.evaluate_nested_obligations(
786 // It's ok not to make progress when have no inference variables -
787 // in that case, we were only performing unification to check if an
788 // error occurred (which would indicate that it's impossible for our
789 // type to implement the auto trait).
790 // However, we should always make progress (either by generating
791 // subobligations or getting an error) when we started off with
792 // inference variables
793 if p.term().skip_binder().has_infer_types() {
794 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
799 ty::PredicateKind::RegionOutlives(binder) => {
800 let binder = bound_predicate.rebind(binder);
801 if select.infcx().region_outlives_predicate(&dummy_cause, binder).is_err() {
805 ty::PredicateKind::TypeOutlives(binder) => {
806 let binder = bound_predicate.rebind(binder);
808 binder.no_bound_vars(),
809 binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
811 (None, Some(t_a)) => {
812 select.infcx().register_region_obligation_with_cause(
814 select.infcx().tcx.lifetimes.re_static,
818 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
819 select.infcx().register_region_obligation_with_cause(
828 ty::PredicateKind::ConstEquate(c1, c2) => {
829 let evaluate = |c: ty::Const<'tcx>| {
830 if let ty::ConstKind::Unevaluated(unevaluated) = c.val() {
831 match select.infcx().const_eval_resolve(
832 obligation.param_env,
834 Some(obligation.cause.span),
836 Ok(val) => Ok(ty::Const::from_value(select.tcx(), val, c.ty())),
837 Err(err) => Err(err),
844 match (evaluate(c1), evaluate(c2)) {
845 (Ok(c1), Ok(c2)) => {
848 .at(&obligation.cause, obligation.param_env)
852 Err(_) => return false,
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
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(..) => {}
876 infcx: &InferCtxt<'_, 'tcx>,
877 p: ty::Predicate<'tcx>,
878 ) -> ty::Predicate<'tcx> {
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>>,
889 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
890 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
894 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
896 ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
899 .unwrap_or_else(|| r.super_fold_with(self))