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