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 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};
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use std::collections::hash_map::Entry;
17 use std::collections::VecDeque;
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> {
27 #[derive(Default, Debug, Clone)]
28 pub struct RegionDeps<'tcx> {
29 larger: FxHashSet<RegionTarget<'tcx>>,
30 smaller: FxHashSet<RegionTarget<'tcx>>,
33 pub enum AutoTraitResult<A> {
40 impl<A> AutoTraitResult<A> {
41 fn is_auto(&self) -> bool {
42 matches!(self, AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl)
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>>,
52 pub struct AutoTraitFinder<'tcx> {
56 impl<'tcx> AutoTraitFinder<'tcx> {
57 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
58 AutoTraitFinder { tcx }
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
65 /// struct Foo<T> { data: Box<T> }
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.
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.)
77 /// Warning: The API should be considered highly unstable, and it may be refactored or removed
79 pub fn find_auto_trait_generics<A>(
82 orig_env: ty::ParamEnv<'tcx>,
84 mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
85 ) -> AutoTraitResult<A> {
88 let trait_ref = ty::TraitRef { def_id: trait_did, substs: tcx.mk_substs_trait(ty, &[]) };
90 let trait_pred = ty::Binder::dummy(trait_ref);
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(),
97 trait_pred.to_poly_trait_predicate(),
101 Ok(Some(ImplSource::UserDefined(_))) => {
103 "find_auto_trait_generics({:?}): \
104 manual impl found, bailing out",
112 let result = selcx.select(&Obligation::new(
113 ObligationCause::dummy(),
115 trait_pred.to_poly_trait_predicate_negative_polarity(),
119 Ok(Some(ImplSource::UserDefined(_))) => {
121 "find_auto_trait_generics({:?}): \
122 manual impl found, bailing out",
131 // If an explicit impl exists, it always takes priority over an auto impl
133 return AutoTraitResult::ExplicitImpl;
136 tcx.infer_ctxt().enter(|infcx| {
137 let mut fresh_preds = FxHashSet::default();
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.
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.
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:
156 // * We can always cache the result of a particular trait selection for the lifetime of
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'
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.
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.
172 let Some((new_env, user_env)) = self.evaluate_predicates(
181 return AutoTraitResult::NegativeImpl;
184 let (full_env, full_user_env) = self
185 .evaluate_predicates(
195 panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env)
199 "find_auto_trait_generics({:?}): fulfilling \
203 infcx.clear_caches();
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 mut fulfill = <dyn TraitEngine<'tcx>>::new(tcx);
209 fulfill.register_bound(&infcx, full_env, ty, trait_did, ObligationCause::dummy());
210 let errors = fulfill.select_all_or_error(&infcx);
212 if !errors.is_empty() {
213 panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors);
216 infcx.process_registered_region_obligations(&Default::default(), full_env);
218 let region_data = infcx
221 .unwrap_region_constraints()
222 .region_constraint_data()
225 let vid_to_region = self.map_vid_to_region(®ion_data);
227 let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
229 AutoTraitResult::PositiveImpl(auto_trait_callback(info))
234 impl<'tcx> AutoTraitFinder<'tcx> {
235 /// The core logic responsible for computing the bounds for our synthesized impl.
237 /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
238 /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
239 /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
240 /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
241 /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
243 /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
244 /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
245 /// user code. According, it considers all possible ways that a `Predicate` could be met, which
246 /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
247 /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
248 /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
249 /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
250 /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
252 /// ```ignore (illustrative)
253 /// impl<T> Send for Foo<T> where T: IntoIterator
255 /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
256 /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
258 /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
259 /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
260 /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
261 /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
264 /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
265 /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
266 /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
267 /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
268 /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate_predicates`, or
269 /// else `SelectionContext` will choke on the missing predicates. However, this should never
270 /// show up in the final synthesized generics: we don't want our generated docs page to contain
271 /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
272 /// separate `user_env`, which only holds the predicates that will actually be displayed to the
274 fn evaluate_predicates(
276 infcx: &InferCtxt<'_, 'tcx>,
279 param_env: ty::ParamEnv<'tcx>,
280 user_env: ty::ParamEnv<'tcx>,
281 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
282 only_projections: bool,
283 ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
286 // Don't try to process any nested obligations involving predicates
287 // that are already in the `ParamEnv` (modulo regions): we already
288 // know that they must hold.
289 for predicate in param_env.caller_bounds() {
290 fresh_preds.insert(self.clean_pred(infcx, predicate));
293 let mut select = SelectionContext::new(&infcx);
295 let mut already_visited = FxHashSet::default();
296 let mut predicates = VecDeque::new();
297 predicates.push_back(ty::Binder::dummy(ty::TraitPredicate {
298 trait_ref: ty::TraitRef {
300 substs: infcx.tcx.mk_substs_trait(ty, &[]),
302 constness: ty::BoundConstness::NotConst,
303 // Auto traits are positive
304 polarity: ty::ImplPolarity::Positive,
307 let computed_preds = param_env.caller_bounds().iter();
308 let mut user_computed_preds: FxHashSet<_> = user_env.caller_bounds().iter().collect();
310 let mut new_env = param_env;
311 let dummy_cause = ObligationCause::dummy();
313 while let Some(pred) = predicates.pop_front() {
314 infcx.clear_caches();
316 if !already_visited.insert(pred) {
320 // Call `infcx.resolve_vars_if_possible` to see if we can
321 // get rid of any inference variables.
323 infcx.resolve_vars_if_possible(Obligation::new(dummy_cause.clone(), new_env, pred));
324 let result = select.select(&obligation);
327 Ok(Some(ref impl_source)) => {
328 // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
329 // we immediately bail out, since it's impossible for us to continue.
331 if let ImplSource::UserDefined(ImplSourceUserDefinedData {
335 // Blame 'tidy' for the weird bracket placement.
336 if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative {
338 "evaluate_nested_obligations: found explicit negative impl\
346 let obligations = impl_source.clone().nested_obligations().into_iter();
348 if !self.evaluate_nested_obligations(
351 &mut user_computed_preds,
361 Err(SelectionError::Unimplemented) => {
362 if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) {
363 already_visited.remove(&pred);
364 self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx));
365 predicates.push_back(pred);
368 "evaluate_nested_obligations: `Unimplemented` found, bailing: \
372 pred.skip_binder().trait_ref.substs
377 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
380 let normalized_preds = elaborate_predicates(
382 computed_preds.clone().chain(user_computed_preds.iter().cloned()),
384 .map(|o| o.predicate);
385 new_env = ty::ParamEnv::new(
386 tcx.mk_predicates(normalized_preds),
388 param_env.constness(),
392 let final_user_env = ty::ParamEnv::new(
393 tcx.mk_predicates(user_computed_preds.into_iter()),
395 user_env.constness(),
398 "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
400 ty, trait_did, new_env, final_user_env
403 Some((new_env, final_user_env))
406 /// This method is designed to work around the following issue:
407 /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
408 /// progressively building a `ParamEnv` based on the results we get.
409 /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
410 /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
412 /// This can lead to a corner case when dealing with region parameters.
413 /// During our selection loop in `evaluate_predicates`, we might end up with
414 /// two trait predicates that differ only in their region parameters:
415 /// one containing a HRTB lifetime parameter, and one containing a 'normal'
416 /// lifetime parameter. For example:
417 /// ```ignore (illustrative)
419 /// T as MyTrait<'static>
421 /// If we put both of these predicates in our computed `ParamEnv`, we'll
422 /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
424 /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
425 /// Our end goal is to generate a user-visible description of the conditions
426 /// under which a type implements an auto trait. A trait predicate involving
427 /// a HRTB means that the type needs to work with any choice of lifetime,
428 /// not just one specific lifetime (e.g., `'static`).
431 user_computed_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
432 new_pred: ty::Predicate<'tcx>,
434 let mut should_add_new = true;
435 user_computed_preds.retain(|&old_pred| {
436 if let (ty::PredicateKind::Trait(new_trait), ty::PredicateKind::Trait(old_trait)) =
437 (new_pred.kind().skip_binder(), old_pred.kind().skip_binder())
439 if new_trait.def_id() == old_trait.def_id() {
440 let new_substs = new_trait.trait_ref.substs;
441 let old_substs = old_trait.trait_ref.substs;
443 if !new_substs.types().eq(old_substs.types()) {
444 // We can't compare lifetimes if the types are different,
445 // so skip checking `old_pred`.
449 for (new_region, old_region) in
450 iter::zip(new_substs.regions(), old_substs.regions())
452 match (*new_region, *old_region) {
453 // If both predicates have an `ReLateBound` (a HRTB) in the
454 // same spot, we do nothing.
455 (ty::ReLateBound(_, _), ty::ReLateBound(_, _)) => {}
457 (ty::ReLateBound(_, _), _) | (_, ty::ReVar(_)) => {
458 // One of these is true:
459 // The new predicate has a HRTB in a spot where the old
460 // predicate does not (if they both had a HRTB, the previous
461 // match arm would have executed). A HRBT is a 'stricter'
462 // bound than anything else, so we want to keep the newer
463 // predicate (with the HRBT) in place of the old predicate.
467 // The old predicate has a region variable where the new
468 // predicate has some other kind of region. An region
469 // variable isn't something we can actually display to a user,
470 // so we choose their new predicate (which doesn't have a region
473 // In both cases, we want to remove the old predicate,
474 // from `user_computed_preds`, and replace it with the new
475 // one. Having both the old and the new
476 // predicate in a `ParamEnv` would confuse `SelectionContext`.
478 // We're currently in the predicate passed to 'retain',
479 // so we return `false` to remove the old predicate from
480 // `user_computed_preds`.
483 (_, ty::ReLateBound(_, _)) | (ty::ReVar(_), _) => {
484 // This is the opposite situation as the previous arm.
485 // One of these is true:
487 // The old predicate has a HRTB lifetime in a place where the
488 // new predicate does not.
492 // The new predicate has a region variable where the old
493 // predicate has some other type of region.
495 // We want to leave the old
496 // predicate in `user_computed_preds`, and skip adding
497 // new_pred to `user_computed_params`.
498 should_add_new = false
509 user_computed_preds.insert(new_pred);
513 /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
514 /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
515 fn map_vid_to_region<'cx>(
517 regions: &RegionConstraintData<'cx>,
518 ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
519 let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default();
520 let mut finished_map = FxHashMap::default();
522 for constraint in regions.constraints.keys() {
524 &Constraint::VarSubVar(r1, r2) => {
526 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
527 deps1.larger.insert(RegionTarget::RegionVid(r2));
530 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
531 deps2.smaller.insert(RegionTarget::RegionVid(r1));
533 &Constraint::RegSubVar(region, vid) => {
535 let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default();
536 deps1.larger.insert(RegionTarget::RegionVid(vid));
539 let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
540 deps2.smaller.insert(RegionTarget::Region(region));
542 &Constraint::VarSubReg(vid, region) => {
543 finished_map.insert(vid, region);
545 &Constraint::RegSubReg(r1, r2) => {
547 let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default();
548 deps1.larger.insert(RegionTarget::Region(r2));
551 let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default();
552 deps2.smaller.insert(RegionTarget::Region(r1));
557 while !vid_map.is_empty() {
558 let target = *vid_map.keys().next().expect("Keys somehow empty");
559 let deps = vid_map.remove(&target).expect("Entry somehow missing");
561 for smaller in deps.smaller.iter() {
562 for larger in deps.larger.iter() {
563 match (smaller, larger) {
564 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
565 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
566 let smaller_deps = v.into_mut();
567 smaller_deps.larger.insert(*larger);
568 smaller_deps.larger.remove(&target);
571 if let Entry::Occupied(v) = vid_map.entry(*larger) {
572 let larger_deps = v.into_mut();
573 larger_deps.smaller.insert(*smaller);
574 larger_deps.smaller.remove(&target);
577 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
578 finished_map.insert(v1, r1);
580 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
581 // Do nothing; we don't care about regions that are smaller than vids.
583 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
584 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
585 let smaller_deps = v.into_mut();
586 smaller_deps.larger.insert(*larger);
587 smaller_deps.larger.remove(&target);
590 if let Entry::Occupied(v) = vid_map.entry(*larger) {
591 let larger_deps = v.into_mut();
592 larger_deps.smaller.insert(*smaller);
593 larger_deps.smaller.remove(&target);
603 fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool {
604 self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types())
607 pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
609 ty::Param(_) => true,
610 ty::Projection(p) => self.is_of_param(p.self_ty()),
615 fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool {
616 if let Term::Ty(ty) = p.term().skip_binder() {
617 matches!(ty.kind(), ty::Projection(proj) if proj == &p.skip_binder().projection_ty)
623 fn evaluate_nested_obligations(
626 nested: impl Iterator<Item = Obligation<'tcx, ty::Predicate<'tcx>>>,
627 computed_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
628 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
629 predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>,
630 select: &mut SelectionContext<'_, 'tcx>,
631 only_projections: bool,
633 let dummy_cause = ObligationCause::dummy();
635 for obligation in nested {
637 fresh_preds.insert(self.clean_pred(select.infcx(), obligation.predicate));
639 // Resolve any inference variables that we can, to help selection succeed
640 let predicate = select.infcx().resolve_vars_if_possible(obligation.predicate);
642 // We only add a predicate as a user-displayable bound if
643 // it involves a generic parameter, and doesn't contain
644 // any inference variables.
646 // Displaying a bound involving a concrete type (instead of a generic
647 // parameter) would be pointless, since it's always true
649 // Displaying an inference variable is impossible, since they're
650 // an internal compiler detail without a defined visual representation
652 // We check this by calling is_of_param on the relevant types
653 // from the various possible predicates
655 let bound_predicate = predicate.kind();
656 match bound_predicate.skip_binder() {
657 ty::PredicateKind::Trait(p) => {
658 // Add this to `predicates` so that we end up calling `select`
659 // with it. If this predicate ends up being unimplemented,
660 // then `evaluate_predicates` will handle adding it the `ParamEnv`
662 predicates.push_back(bound_predicate.rebind(p));
664 ty::PredicateKind::Projection(p) => {
665 let p = bound_predicate.rebind(p);
667 "evaluate_nested_obligations: examining projection predicate {:?}",
671 // As described above, we only want to display
672 // bounds which include a generic parameter but don't include
673 // an inference variable.
674 // Additionally, we check if we've seen this predicate before,
675 // to avoid rendering duplicate bounds to the user.
676 if self.is_param_no_infer(p.skip_binder().projection_ty.substs)
677 && !p.term().skip_binder().has_infer_types()
681 "evaluate_nested_obligations: adding projection predicate \
682 to computed_preds: {:?}",
686 // Under unusual circumstances, we can end up with a self-referential
687 // projection predicate. For example:
688 // <T as MyType>::Value == <T as MyType>::Value
689 // Not only is displaying this to the user pointless,
690 // having it in the ParamEnv will cause an issue if we try to call
691 // poly_project_and_unify_type on the predicate, since this kind of
692 // predicate will normally never end up in a ParamEnv.
694 // For these reasons, we ignore these weird predicates,
695 // ensuring that we're able to properly synthesize an auto trait impl
696 if self.is_self_referential_projection(p) {
698 "evaluate_nested_obligations: encountered a projection
699 predicate equating a type with itself! Skipping"
702 self.add_user_pred(computed_preds, predicate);
706 // There are three possible cases when we project a predicate:
708 // 1. We encounter an error. This means that it's impossible for
709 // our current type to implement the auto trait - there's bound
710 // that we could add to our ParamEnv that would 'fix' this kind
711 // of error, as it's not caused by an unimplemented type.
713 // 2. We successfully project the predicate (Ok(Some(_))), generating
714 // some subobligations. We then process these subobligations
715 // like any other generated sub-obligations.
717 // 3. We receive an 'ambiguous' result (Ok(None))
718 // If we were actually trying to compile a crate,
719 // we would need to re-process this obligation later.
720 // However, all we care about is finding out what bounds
721 // are needed for our type to implement a particular auto trait.
722 // We've already added this obligation to our computed ParamEnv
723 // above (if it was necessary). Therefore, we don't need
724 // to do any further processing of the obligation.
726 // Note that we *must* try to project *all* projection predicates
727 // we encounter, even ones without inference variable.
728 // This ensures that we detect any projection errors,
729 // which indicate that our type can *never* implement the given
730 // auto trait. In that case, we will generate an explicit negative
731 // impl (e.g. 'impl !Send for MyType'). However, we don't
732 // try to process any of the generated subobligations -
733 // they contain no new information, since we already know
734 // that our type implements the projected-through trait,
735 // and can lead to weird region issues.
737 // Normally, we'll generate a negative impl as a result of encountering
738 // a type with an explicit negative impl of an auto trait
739 // (for example, raw pointers have !Send and !Sync impls)
740 // However, through some **interesting** manipulations of the type
741 // system, it's actually possible to write a type that never
742 // implements an auto trait due to a projection error, not a normal
743 // negative impl error. To properly handle this case, we need
744 // to ensure that we catch any potential projection errors,
745 // and turn them into an explicit negative impl for our type.
746 debug!("Projecting and unifying projection predicate {:?}", predicate);
748 match project::poly_project_and_unify_type(select, &obligation.with(p)) {
749 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
751 "evaluate_nested_obligations: Unable to unify predicate \
752 '{:?}' '{:?}', bailing out",
757 ProjectAndUnifyResult::Recursive => {
758 debug!("evaluate_nested_obligations: recursive projection predicate");
761 ProjectAndUnifyResult::Holds(v) => {
762 // We only care about sub-obligations
763 // when we started out trying to unify
764 // some inference variables. See the comment above
765 // for more information
766 if p.term().skip_binder().has_infer_types() {
767 if !self.evaluate_nested_obligations(
780 ProjectAndUnifyResult::FailedNormalization => {
781 // It's ok not to make progress when have no inference variables -
782 // in that case, we were only performing unification to check if an
783 // error occurred (which would indicate that it's impossible for our
784 // type to implement the auto trait).
785 // However, we should always make progress (either by generating
786 // subobligations or getting an error) when we started off with
787 // inference variables
788 if p.term().skip_binder().has_infer_types() {
789 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
794 ty::PredicateKind::RegionOutlives(binder) => {
795 let binder = bound_predicate.rebind(binder);
796 select.infcx().region_outlives_predicate(&dummy_cause, binder)
798 ty::PredicateKind::TypeOutlives(binder) => {
799 let binder = bound_predicate.rebind(binder);
801 binder.no_bound_vars(),
802 binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
804 (None, Some(t_a)) => {
805 select.infcx().register_region_obligation_with_cause(
807 select.infcx().tcx.lifetimes.re_static,
811 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
812 select.infcx().register_region_obligation_with_cause(
821 ty::PredicateKind::ConstEquate(c1, c2) => {
822 let evaluate = |c: ty::Const<'tcx>| {
823 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
824 match select.infcx().const_eval_resolve(
825 obligation.param_env,
827 Some(obligation.cause.span),
829 Ok(Some(valtree)) => {
830 Ok(ty::Const::from_value(select.tcx(), valtree, c.ty()))
834 let def_id = unevaluated.def.did;
835 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();
837 Err(ErrorHandled::Reported(reported))
839 Err(err) => Err(err),
846 match (evaluate(c1), evaluate(c2)) {
847 (Ok(c1), Ok(c2)) => {
850 .at(&obligation.cause, obligation.param_env)
854 Err(_) => return false,
860 // There's not really much we can do with these predicates -
861 // we start out with a `ParamEnv` with no inference variables,
862 // and these don't correspond to adding any new bounds to
864 ty::PredicateKind::WellFormed(..)
865 | ty::PredicateKind::ObjectSafe(..)
866 | ty::PredicateKind::ClosureKind(..)
867 | ty::PredicateKind::Subtype(..)
868 | ty::PredicateKind::ConstEvaluatable(..)
869 | ty::PredicateKind::Coerce(..)
870 | ty::PredicateKind::TypeWellFormedFromEnv(..) => {}
878 infcx: &InferCtxt<'_, 'tcx>,
879 p: ty::Predicate<'tcx>,
880 ) -> ty::Predicate<'tcx> {
885 // Replaces all ReVars in a type with ty::Region's, using the provided map
886 pub struct RegionReplacer<'a, 'tcx> {
887 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
891 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
892 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
896 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
898 ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
901 .unwrap_or_else(|| r.super_fold_with(self))