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