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::errors::UnableToConstructConstantValue;
7 use crate::infer::region_constraints::{Constraint, RegionConstraintData};
8 use crate::infer::InferCtxt;
9 use crate::traits::project::ProjectAndUnifyResult;
10 use rustc_middle::mir::interpret::ErrorHandled;
11 use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
12 use rustc_middle::ty::visit::TypeVisitable;
13 use rustc_middle::ty::{PolyTraitRef, Region, RegionVid};
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
17 use std::collections::hash_map::Entry;
18 use std::collections::VecDeque;
21 // FIXME(twk): this is obviously not nice to duplicate like that
22 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
23 pub enum RegionTarget<'tcx> {
28 #[derive(Default, Debug, Clone)]
29 pub struct RegionDeps<'tcx> {
30 larger: FxIndexSet<RegionTarget<'tcx>>,
31 smaller: FxIndexSet<RegionTarget<'tcx>>,
34 pub enum AutoTraitResult<A> {
41 impl<A> AutoTraitResult<A> {
42 fn is_auto(&self) -> bool {
43 matches!(self, AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl)
47 pub struct AutoTraitInfo<'cx> {
48 pub full_user_env: ty::ParamEnv<'cx>,
49 pub region_data: RegionConstraintData<'cx>,
50 pub vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
53 pub struct AutoTraitFinder<'tcx> {
57 impl<'tcx> AutoTraitFinder<'tcx> {
58 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
59 AutoTraitFinder { tcx }
62 /// Makes a best effort to determine whether and under which conditions an auto trait is
63 /// implemented for a type. For example, if you have
66 /// struct Foo<T> { data: Box<T> }
69 /// then this might return that `Foo<T>: Send` if `T: Send` (encoded in the AutoTraitResult
70 /// type). The analysis attempts to account for custom impls as well as other complex cases.
71 /// This result is intended for use by rustdoc and other such consumers.
73 /// (Note that due to the coinductive nature of Send, the full and correct result is actually
74 /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field
75 /// types are all Send. So, in our example, we might have that `Foo<T>: Send` if `Box<T>: Send`.
76 /// But this is often not the best way to present to the user.)
78 /// Warning: The API should be considered highly unstable, and it may be refactored or removed
80 pub fn find_auto_trait_generics<A>(
83 orig_env: ty::ParamEnv<'tcx>,
85 mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
86 ) -> AutoTraitResult<A> {
89 let trait_ref = tcx.mk_trait_ref(trait_did, ty, &[]);
91 let trait_pred = ty::Binder::dummy(trait_ref);
93 let infcx = tcx.infer_ctxt().build();
94 let mut selcx = SelectionContext::new(&infcx);
96 PolyTraitRef::to_poly_trait_predicate,
97 PolyTraitRef::to_poly_trait_predicate_negative_polarity,
99 let result = selcx.select(&Obligation::new(
101 ObligationCause::dummy(),
105 if let Ok(Some(ImplSource::UserDefined(_))) = result {
107 "find_auto_trait_generics({:?}): \
108 manual impl found, bailing out",
111 // If an explicit impl exists, it always takes priority over an auto impl
112 return AutoTraitResult::ExplicitImpl;
116 let infcx = tcx.infer_ctxt().build();
117 let mut fresh_preds = FxHashSet::default();
119 // Due to the way projections are handled by SelectionContext, we need to run
120 // evaluate_predicates twice: once on the original param env, and once on the result of
121 // the first evaluate_predicates call.
123 // The problem is this: most of rustc, including SelectionContext and traits::project,
124 // are designed to work with a concrete usage of a type (e.g., Vec<u8>
125 // fn<T>() { Vec<T> }. This information will generally never change - given
126 // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
127 // If we're unable to prove that 'T' implements a particular trait, we're done -
128 // there's nothing left to do but error out.
130 // However, synthesizing an auto trait impl works differently. Here, we start out with
131 // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
132 // with - and progressively discover the conditions we need to fulfill for it to
133 // implement a certain auto trait. This ends up breaking two assumptions made by trait
134 // selection and projection:
136 // * We can always cache the result of a particular trait selection for the lifetime of
138 // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
139 // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
141 // We fix the first assumption by manually clearing out all of the InferCtxt's caches
142 // in between calls to SelectionContext.select. This allows us to keep all of the
143 // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
144 // them between calls.
146 // We fix the second assumption by reprocessing the result of our first call to
147 // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
148 // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
149 // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
150 // SelectionContext to return it back to us.
152 let Some((new_env, user_env)) = self.evaluate_predicates(
161 return AutoTraitResult::NegativeImpl;
164 let (full_env, full_user_env) = self
165 .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds, true)
167 panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env)
171 "find_auto_trait_generics({:?}): fulfilling \
175 infcx.clear_caches();
177 // At this point, we already have all of the bounds we need. FulfillmentContext is used
178 // to store all of the necessary region/lifetime bounds in the InferContext, as well as
179 // an additional sanity check.
181 super::fully_solve_bound(&infcx, ObligationCause::dummy(), full_env, ty, trait_did);
182 if !errors.is_empty() {
183 panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors);
186 infcx.process_registered_region_obligations(&Default::default(), full_env);
189 infcx.inner.borrow_mut().unwrap_region_constraints().region_constraint_data().clone();
191 let vid_to_region = self.map_vid_to_region(®ion_data);
193 let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
195 AutoTraitResult::PositiveImpl(auto_trait_callback(info))
199 impl<'tcx> AutoTraitFinder<'tcx> {
200 /// The core logic responsible for computing the bounds for our synthesized impl.
202 /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
203 /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
204 /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
205 /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
206 /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
208 /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
209 /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
210 /// user code. According, it considers all possible ways that a `Predicate` could be met, which
211 /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
212 /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
213 /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
214 /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
215 /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
217 /// ```ignore (illustrative)
218 /// impl<T> Send for Foo<T> where T: IntoIterator
220 /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
221 /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
223 /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
224 /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
225 /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
226 /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
229 /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
230 /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
231 /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
232 /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
233 /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate_predicates`, or
234 /// else `SelectionContext` will choke on the missing predicates. However, this should never
235 /// show up in the final synthesized generics: we don't want our generated docs page to contain
236 /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
237 /// separate `user_env`, which only holds the predicates that will actually be displayed to the
239 fn evaluate_predicates(
241 infcx: &InferCtxt<'tcx>,
244 param_env: ty::ParamEnv<'tcx>,
245 user_env: ty::ParamEnv<'tcx>,
246 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
247 only_projections: bool,
248 ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
251 // Don't try to process any nested obligations involving predicates
252 // that are already in the `ParamEnv` (modulo regions): we already
253 // know that they must hold.
254 for predicate in param_env.caller_bounds() {
255 fresh_preds.insert(self.clean_pred(infcx, predicate));
258 let mut select = SelectionContext::new(&infcx);
260 let mut already_visited = FxHashSet::default();
261 let mut predicates = VecDeque::new();
262 predicates.push_back(ty::Binder::dummy(ty::TraitPredicate {
263 trait_ref: infcx.tcx.mk_trait_ref(trait_did, ty, &[]),
265 constness: ty::BoundConstness::NotConst,
266 // Auto traits are positive
267 polarity: ty::ImplPolarity::Positive,
270 let computed_preds = param_env.caller_bounds().iter();
271 let mut user_computed_preds: FxIndexSet<_> = user_env.caller_bounds().iter().collect();
273 let mut new_env = param_env;
274 let dummy_cause = ObligationCause::dummy();
276 while let Some(pred) = predicates.pop_front() {
277 infcx.clear_caches();
279 if !already_visited.insert(pred) {
283 // Call `infcx.resolve_vars_if_possible` to see if we can
284 // get rid of any inference variables.
285 let obligation = infcx.resolve_vars_if_possible(Obligation::new(
291 let result = select.select(&obligation);
294 Ok(Some(ref impl_source)) => {
295 // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
296 // we immediately bail out, since it's impossible for us to continue.
298 if let ImplSource::UserDefined(ImplSourceUserDefinedData {
302 // Blame 'tidy' for the weird bracket placement.
303 if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative {
305 "evaluate_nested_obligations: found explicit negative impl\
313 let obligations = impl_source.borrow_nested_obligations().iter().cloned();
315 if !self.evaluate_nested_obligations(
318 &mut user_computed_preds,
328 Err(SelectionError::Unimplemented) => {
329 if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) {
330 already_visited.remove(&pred);
331 self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx));
332 predicates.push_back(pred);
335 "evaluate_nested_obligations: `Unimplemented` found, bailing: \
339 pred.skip_binder().trait_ref.substs
344 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
347 let normalized_preds = elaborate_predicates(
349 computed_preds.clone().chain(user_computed_preds.iter().cloned()),
351 .map(|o| o.predicate);
352 new_env = ty::ParamEnv::new(
353 tcx.mk_predicates(normalized_preds),
355 param_env.constness(),
359 let final_user_env = ty::ParamEnv::new(
360 tcx.mk_predicates(user_computed_preds.into_iter()),
362 user_env.constness(),
365 "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
367 ty, trait_did, new_env, final_user_env
370 Some((new_env, final_user_env))
373 /// This method is designed to work around the following issue:
374 /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
375 /// progressively building a `ParamEnv` based on the results we get.
376 /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
377 /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
379 /// This can lead to a corner case when dealing with region parameters.
380 /// During our selection loop in `evaluate_predicates`, we might end up with
381 /// two trait predicates that differ only in their region parameters:
382 /// one containing a HRTB lifetime parameter, and one containing a 'normal'
383 /// lifetime parameter. For example:
384 /// ```ignore (illustrative)
386 /// T as MyTrait<'static>
388 /// If we put both of these predicates in our computed `ParamEnv`, we'll
389 /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
391 /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
392 /// Our end goal is to generate a user-visible description of the conditions
393 /// under which a type implements an auto trait. A trait predicate involving
394 /// a HRTB means that the type needs to work with any choice of lifetime,
395 /// not just one specific lifetime (e.g., `'static`).
398 user_computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
399 new_pred: ty::Predicate<'tcx>,
401 let mut should_add_new = true;
402 user_computed_preds.retain(|&old_pred| {
403 if let (ty::PredicateKind::Trait(new_trait), ty::PredicateKind::Trait(old_trait)) =
404 (new_pred.kind().skip_binder(), old_pred.kind().skip_binder())
406 if new_trait.def_id() == old_trait.def_id() {
407 let new_substs = new_trait.trait_ref.substs;
408 let old_substs = old_trait.trait_ref.substs;
410 if !new_substs.types().eq(old_substs.types()) {
411 // We can't compare lifetimes if the types are different,
412 // so skip checking `old_pred`.
416 for (new_region, old_region) in
417 iter::zip(new_substs.regions(), old_substs.regions())
419 match (*new_region, *old_region) {
420 // If both predicates have an `ReLateBound` (a HRTB) in the
421 // same spot, we do nothing.
422 (ty::ReLateBound(_, _), ty::ReLateBound(_, _)) => {}
424 (ty::ReLateBound(_, _), _) | (_, ty::ReVar(_)) => {
425 // One of these is true:
426 // The new predicate has a HRTB in a spot where the old
427 // predicate does not (if they both had a HRTB, the previous
428 // match arm would have executed). A HRBT is a 'stricter'
429 // bound than anything else, so we want to keep the newer
430 // predicate (with the HRBT) in place of the old predicate.
434 // The old predicate has a region variable where the new
435 // predicate has some other kind of region. An region
436 // variable isn't something we can actually display to a user,
437 // so we choose their new predicate (which doesn't have a region
440 // In both cases, we want to remove the old predicate,
441 // from `user_computed_preds`, and replace it with the new
442 // one. Having both the old and the new
443 // predicate in a `ParamEnv` would confuse `SelectionContext`.
445 // We're currently in the predicate passed to 'retain',
446 // so we return `false` to remove the old predicate from
447 // `user_computed_preds`.
450 (_, ty::ReLateBound(_, _)) | (ty::ReVar(_), _) => {
451 // This is the opposite situation as the previous arm.
452 // One of these is true:
454 // The old predicate has a HRTB lifetime in a place where the
455 // new predicate does not.
459 // The new predicate has a region variable where the old
460 // predicate has some other type of region.
462 // We want to leave the old
463 // predicate in `user_computed_preds`, and skip adding
464 // new_pred to `user_computed_params`.
465 should_add_new = false
476 user_computed_preds.insert(new_pred);
480 /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
481 /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
482 fn map_vid_to_region<'cx>(
484 regions: &RegionConstraintData<'cx>,
485 ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
486 let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default();
487 let mut finished_map = FxHashMap::default();
489 for constraint in regions.constraints.keys() {
491 &Constraint::VarSubVar(r1, r2) => {
493 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
494 deps1.larger.insert(RegionTarget::RegionVid(r2));
497 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
498 deps2.smaller.insert(RegionTarget::RegionVid(r1));
500 &Constraint::RegSubVar(region, vid) => {
502 let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default();
503 deps1.larger.insert(RegionTarget::RegionVid(vid));
506 let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
507 deps2.smaller.insert(RegionTarget::Region(region));
509 &Constraint::VarSubReg(vid, region) => {
510 finished_map.insert(vid, region);
512 &Constraint::RegSubReg(r1, r2) => {
514 let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default();
515 deps1.larger.insert(RegionTarget::Region(r2));
518 let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default();
519 deps2.smaller.insert(RegionTarget::Region(r1));
524 while !vid_map.is_empty() {
525 let target = *vid_map.keys().next().expect("Keys somehow empty");
526 let deps = vid_map.remove(&target).expect("Entry somehow missing");
528 for smaller in deps.smaller.iter() {
529 for larger in deps.larger.iter() {
530 match (smaller, larger) {
531 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
532 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
533 let smaller_deps = v.into_mut();
534 smaller_deps.larger.insert(*larger);
535 smaller_deps.larger.remove(&target);
538 if let Entry::Occupied(v) = vid_map.entry(*larger) {
539 let larger_deps = v.into_mut();
540 larger_deps.smaller.insert(*smaller);
541 larger_deps.smaller.remove(&target);
544 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
545 finished_map.insert(v1, r1);
547 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
548 // Do nothing; we don't care about regions that are smaller than vids.
550 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
551 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
552 let smaller_deps = v.into_mut();
553 smaller_deps.larger.insert(*larger);
554 smaller_deps.larger.remove(&target);
557 if let Entry::Occupied(v) = vid_map.entry(*larger) {
558 let larger_deps = v.into_mut();
559 larger_deps.smaller.insert(*smaller);
560 larger_deps.smaller.remove(&target);
570 fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool {
571 self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types())
574 pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
576 ty::Param(_) => true,
577 ty::Projection(p) => self.is_of_param(p.self_ty()),
582 fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool {
583 if let Some(ty) = p.term().skip_binder().ty() {
584 matches!(ty.kind(), ty::Projection(proj) if proj == &p.skip_binder().projection_ty)
590 fn evaluate_nested_obligations(
593 nested: impl Iterator<Item = Obligation<'tcx, ty::Predicate<'tcx>>>,
594 computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
595 fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
596 predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>,
597 select: &mut SelectionContext<'_, 'tcx>,
598 only_projections: bool,
600 let dummy_cause = ObligationCause::dummy();
602 for obligation in nested {
604 fresh_preds.insert(self.clean_pred(select.infcx(), obligation.predicate));
606 // Resolve any inference variables that we can, to help selection succeed
607 let predicate = select.infcx().resolve_vars_if_possible(obligation.predicate);
609 // We only add a predicate as a user-displayable bound if
610 // it involves a generic parameter, and doesn't contain
611 // any inference variables.
613 // Displaying a bound involving a concrete type (instead of a generic
614 // parameter) would be pointless, since it's always true
616 // Displaying an inference variable is impossible, since they're
617 // an internal compiler detail without a defined visual representation
619 // We check this by calling is_of_param on the relevant types
620 // from the various possible predicates
622 let bound_predicate = predicate.kind();
623 match bound_predicate.skip_binder() {
624 ty::PredicateKind::Trait(p) => {
625 // Add this to `predicates` so that we end up calling `select`
626 // with it. If this predicate ends up being unimplemented,
627 // then `evaluate_predicates` will handle adding it the `ParamEnv`
629 predicates.push_back(bound_predicate.rebind(p));
631 ty::PredicateKind::Projection(p) => {
632 let p = bound_predicate.rebind(p);
634 "evaluate_nested_obligations: examining projection predicate {:?}",
638 // As described above, we only want to display
639 // bounds which include a generic parameter but don't include
640 // an inference variable.
641 // Additionally, we check if we've seen this predicate before,
642 // to avoid rendering duplicate bounds to the user.
643 if self.is_param_no_infer(p.skip_binder().projection_ty.substs)
644 && !p.term().skip_binder().has_infer_types()
648 "evaluate_nested_obligations: adding projection predicate \
649 to computed_preds: {:?}",
653 // Under unusual circumstances, we can end up with a self-referential
654 // projection predicate. For example:
655 // <T as MyType>::Value == <T as MyType>::Value
656 // Not only is displaying this to the user pointless,
657 // having it in the ParamEnv will cause an issue if we try to call
658 // poly_project_and_unify_type on the predicate, since this kind of
659 // predicate will normally never end up in a ParamEnv.
661 // For these reasons, we ignore these weird predicates,
662 // ensuring that we're able to properly synthesize an auto trait impl
663 if self.is_self_referential_projection(p) {
665 "evaluate_nested_obligations: encountered a projection
666 predicate equating a type with itself! Skipping"
669 self.add_user_pred(computed_preds, predicate);
673 // There are three possible cases when we project a predicate:
675 // 1. We encounter an error. This means that it's impossible for
676 // our current type to implement the auto trait - there's bound
677 // that we could add to our ParamEnv that would 'fix' this kind
678 // of error, as it's not caused by an unimplemented type.
680 // 2. We successfully project the predicate (Ok(Some(_))), generating
681 // some subobligations. We then process these subobligations
682 // like any other generated sub-obligations.
684 // 3. We receive an 'ambiguous' result (Ok(None))
685 // If we were actually trying to compile a crate,
686 // we would need to re-process this obligation later.
687 // However, all we care about is finding out what bounds
688 // are needed for our type to implement a particular auto trait.
689 // We've already added this obligation to our computed ParamEnv
690 // above (if it was necessary). Therefore, we don't need
691 // to do any further processing of the obligation.
693 // Note that we *must* try to project *all* projection predicates
694 // we encounter, even ones without inference variable.
695 // This ensures that we detect any projection errors,
696 // which indicate that our type can *never* implement the given
697 // auto trait. In that case, we will generate an explicit negative
698 // impl (e.g. 'impl !Send for MyType'). However, we don't
699 // try to process any of the generated subobligations -
700 // they contain no new information, since we already know
701 // that our type implements the projected-through trait,
702 // and can lead to weird region issues.
704 // Normally, we'll generate a negative impl as a result of encountering
705 // a type with an explicit negative impl of an auto trait
706 // (for example, raw pointers have !Send and !Sync impls)
707 // However, through some **interesting** manipulations of the type
708 // system, it's actually possible to write a type that never
709 // implements an auto trait due to a projection error, not a normal
710 // negative impl error. To properly handle this case, we need
711 // to ensure that we catch any potential projection errors,
712 // and turn them into an explicit negative impl for our type.
713 debug!("Projecting and unifying projection predicate {:?}", predicate);
715 match project::poly_project_and_unify_type(
717 &obligation.with(self.tcx, p),
719 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
721 "evaluate_nested_obligations: Unable to unify predicate \
722 '{:?}' '{:?}', bailing out",
727 ProjectAndUnifyResult::Recursive => {
728 debug!("evaluate_nested_obligations: recursive projection predicate");
731 ProjectAndUnifyResult::Holds(v) => {
732 // We only care about sub-obligations
733 // when we started out trying to unify
734 // some inference variables. See the comment above
735 // for more information
736 if p.term().skip_binder().has_infer_types() {
737 if !self.evaluate_nested_obligations(
750 ProjectAndUnifyResult::FailedNormalization => {
751 // It's ok not to make progress when have no inference variables -
752 // in that case, we were only performing unification to check if an
753 // error occurred (which would indicate that it's impossible for our
754 // type to implement the auto trait).
755 // However, we should always make progress (either by generating
756 // subobligations or getting an error) when we started off with
757 // inference variables
758 if p.term().skip_binder().has_infer_types() {
759 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
764 ty::PredicateKind::RegionOutlives(binder) => {
765 let binder = bound_predicate.rebind(binder);
766 select.infcx().region_outlives_predicate(&dummy_cause, binder)
768 ty::PredicateKind::TypeOutlives(binder) => {
769 let binder = bound_predicate.rebind(binder);
771 binder.no_bound_vars(),
772 binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
774 (None, Some(t_a)) => {
775 select.infcx().register_region_obligation_with_cause(
777 select.infcx().tcx.lifetimes.re_static,
781 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
782 select.infcx().register_region_obligation_with_cause(
791 ty::PredicateKind::ConstEquate(c1, c2) => {
792 let evaluate = |c: ty::Const<'tcx>| {
793 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
794 match select.infcx().const_eval_resolve(
795 obligation.param_env,
797 Some(obligation.cause.span),
799 Ok(Some(valtree)) => {
800 Ok(ty::Const::from_value(select.tcx(), valtree, c.ty()))
804 let def_id = unevaluated.def.did;
806 tcx.sess.emit_err(UnableToConstructConstantValue {
807 span: tcx.def_span(def_id),
808 unevaluated: unevaluated,
810 Err(ErrorHandled::Reported(reported))
812 Err(err) => Err(err),
819 match (evaluate(c1), evaluate(c2)) {
820 (Ok(c1), Ok(c2)) => {
823 .at(&obligation.cause, obligation.param_env)
827 Err(_) => return false,
833 // There's not really much we can do with these predicates -
834 // we start out with a `ParamEnv` with no inference variables,
835 // and these don't correspond to adding any new bounds to
837 ty::PredicateKind::WellFormed(..)
838 | ty::PredicateKind::ObjectSafe(..)
839 | ty::PredicateKind::ClosureKind(..)
840 | ty::PredicateKind::Subtype(..)
841 | ty::PredicateKind::ConstEvaluatable(..)
842 | ty::PredicateKind::Coerce(..)
843 | ty::PredicateKind::TypeWellFormedFromEnv(..) => {}
851 infcx: &InferCtxt<'tcx>,
852 p: ty::Predicate<'tcx>,
853 ) -> ty::Predicate<'tcx> {
858 // Replaces all ReVars in a type with ty::Region's, using the provided map
859 pub struct RegionReplacer<'a, 'tcx> {
860 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
864 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
865 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
869 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
871 ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
874 .unwrap_or_else(|| r.super_fold_with(self))