1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Support code for rustdoc and external tools . You really don't
12 //! want to be using this unless you need to.
16 use std::collections::hash_map::Entry;
17 use std::collections::VecDeque;
19 use infer::region_constraints::{Constraint, RegionConstraintData};
21 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use ty::fold::TypeFolder;
24 use ty::{Region, RegionVid};
26 // FIXME(twk): this is obviously not nice to duplicate like that
27 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
28 pub enum RegionTarget<'tcx> {
33 #[derive(Default, Debug, Clone)]
34 pub struct RegionDeps<'tcx> {
35 larger: FxHashSet<RegionTarget<'tcx>>,
36 smaller: FxHashSet<RegionTarget<'tcx>>,
39 pub enum AutoTraitResult<A> {
45 impl<A> AutoTraitResult<A> {
46 fn is_auto(&self) -> bool {
48 AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl => true,
54 pub struct AutoTraitInfo<'cx> {
55 pub full_user_env: ty::ParamEnv<'cx>,
56 pub region_data: RegionConstraintData<'cx>,
57 pub names_map: FxHashSet<String>,
58 pub vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
61 pub struct AutoTraitFinder<'a, 'tcx: 'a> {
62 tcx: &'a TyCtxt<'a, 'tcx, 'tcx>,
65 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
66 pub fn new(tcx: &'a TyCtxt<'a, 'tcx, 'tcx>) -> Self {
67 AutoTraitFinder { tcx }
70 /// Make a best effort to determine whether and under which conditions an auto trait is
71 /// implemented for a type. For example, if you have
74 /// struct Foo<T> { data: Box<T> }
77 /// then this might return that Foo<T>: Send if T: Send (encoded in the AutoTraitResult type).
78 /// The analysis attempts to account for custom impls as well as other complex cases. This
79 /// result is intended for use by rustdoc and other such consumers.
81 /// (Note that due to the coinductive nature of Send, the full and correct result is actually
82 /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field
83 /// types are all Send. So, in our example, we might have that Foo<T>: Send if Box<T>: Send.
84 /// But this is often not the best way to present to the user.)
86 /// Warning: The API should be considered highly unstable, and it may be refactored or removed
88 pub fn find_auto_trait_generics<A>(
92 generics: &ty::Generics,
93 auto_trait_callback: impl for<'i> Fn(&InferCtxt<'_, 'tcx, 'i>, AutoTraitInfo<'i>) -> A,
94 ) -> AutoTraitResult<A> {
96 let ty = self.tcx.type_of(did);
98 let orig_params = tcx.param_env(did);
100 let trait_ref = ty::TraitRef {
102 substs: tcx.mk_substs_trait(ty, &[]),
105 let trait_pred = ty::Binder::bind(trait_ref);
107 let bail_out = tcx.infer_ctxt().enter(|infcx| {
108 let mut selcx = SelectionContext::with_negative(&infcx, true);
109 let result = selcx.select(&Obligation::new(
110 ObligationCause::dummy(),
112 trait_pred.to_poly_trait_predicate(),
116 Ok(Some(Vtable::VtableImpl(_))) => {
118 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): \
119 manual impl found, bailing out",
120 did, trait_did, generics
128 // If an explicit impl exists, it always takes priority over an auto impl
130 return AutoTraitResult::ExplicitImpl;
133 return tcx.infer_ctxt().enter(|mut infcx| {
134 let mut fresh_preds = FxHashSet::default();
136 // Due to the way projections are handled by SelectionContext, we need to run
137 // evaluate_predicates twice: once on the original param env, and once on the result of
138 // the first evaluate_predicates call.
140 // The problem is this: most of rustc, including SelectionContext and traits::project,
141 // are designed to work with a concrete usage of a type (e.g. Vec<u8>
142 // fn<T>() { Vec<T> }. This information will generally never change - given
143 // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
144 // If we're unable to prove that 'T' implements a particular trait, we're done -
145 // there's nothing left to do but error out.
147 // However, synthesizing an auto trait impl works differently. Here, we start out with
148 // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
149 // with - and progressively discover the conditions we need to fulfill for it to
150 // implement a certain auto trait. This ends up breaking two assumptions made by trait
151 // selection and projection:
153 // * We can always cache the result of a particular trait selection for the lifetime of
155 // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
156 // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
158 // We fix the first assumption by manually clearing out all of the InferCtxt's caches
159 // in between calls to SelectionContext.select. This allows us to keep all of the
160 // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
161 // them between calls.
163 // We fix the second assumption by reprocessing the result of our first call to
164 // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
165 // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
166 // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
167 // SelectionContext to return it back to us.
169 let (new_env, user_env) = match self.evaluate_predicates(
180 None => return AutoTraitResult::NegativeImpl,
183 let (full_env, full_user_env) = self.evaluate_predicates(
192 ).unwrap_or_else(|| {
194 "Failed to fully process: {:?} {:?} {:?}",
195 ty, trait_did, orig_params
200 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): fulfilling \
202 did, trait_did, generics, full_env
204 infcx.clear_caches();
206 // At this point, we already have all of the bounds we need. FulfillmentContext is used
207 // to store all of the necessary region/lifetime bounds in the InferContext, as well as
208 // an additional sanity check.
209 let mut fulfill = FulfillmentContext::new();
210 fulfill.register_bound(
215 ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
217 fulfill.select_all_or_error(&infcx).unwrap_or_else(|e| {
219 "Unable to fulfill trait {:?} for '{:?}': {:?}",
224 let names_map: FxHashSet<String> = generics
227 .filter_map(|param| match param.kind {
228 ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
233 let body_id_map: FxHashMap<_, _> = infcx
237 .map(|&(id, _)| (id, vec![]))
240 infcx.process_registered_region_obligations(&body_id_map, None, full_env.clone());
242 let region_data = infcx
243 .borrow_region_constraints()
244 .region_constraint_data()
247 let vid_to_region = self.map_vid_to_region(®ion_data);
249 let info = AutoTraitInfo {
256 return AutoTraitResult::PositiveImpl(auto_trait_callback(&infcx, info));
261 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
262 // The core logic responsible for computing the bounds for our synthesized impl.
264 // To calculate the bounds, we call SelectionContext.select in a loop. Like FulfillmentContext,
265 // we recursively select the nested obligations of predicates we encounter. However, whenever we
266 // encounter an UnimplementedError involving a type parameter, we add it to our ParamEnv. Since
267 // our goal is to determine when a particular type implements an auto trait, Unimplemented
268 // errors tell us what conditions need to be met.
270 // This method ends up working somewhat similarly to FulfillmentContext, but with a few key
271 // differences. FulfillmentContext works under the assumption that it's dealing with concrete
272 // user code. According, it considers all possible ways that a Predicate could be met - which
273 // isn't always what we want for a synthesized impl. For example, given the predicate 'T:
274 // Iterator', FulfillmentContext can end up reporting an Unimplemented error for T:
275 // IntoIterator - since there's an implementation of Iteratpr where T: IntoIterator,
276 // FulfillmentContext will drive SelectionContext to consider that impl before giving up. If we
277 // were to rely on FulfillmentContext's decision, we might end up synthesizing an impl like
279 // 'impl<T> Send for Foo<T> where T: IntoIterator'
281 // While it might be technically true that Foo implements Send where T: IntoIterator,
282 // the bound is overly restrictive - it's really only necessary that T: Iterator.
284 // For this reason, evaluate_predicates handles predicates with type variables specially. When
285 // we encounter an Unimplemented error for a bound such as 'T: Iterator', we immediately add it
286 // to our ParamEnv, and add it to our stack for recursive evaluation. When we later select it,
287 // we'll pick up any nested bounds, without ever inferring that 'T: IntoIterator' needs to
290 // One additional consideration is supertrait bounds. Normally, a ParamEnv is only ever
291 // constructed once for a given type. As part of the construction process, the ParamEnv will
292 // have any supertrait bounds normalized - e.g. if we have a type 'struct Foo<T: Copy>', the
293 // ParamEnv will contain 'T: Copy' and 'T: Clone', since 'Copy: Clone'. When we construct our
294 // own ParamEnv, we need to do this ourselves, through traits::elaborate_predicates, or else
295 // SelectionContext will choke on the missing predicates. However, this should never show up in
296 // the final synthesized generics: we don't want our generated docs page to contain something
297 // like 'T: Copy + Clone', as that's redundant. Therefore, we keep track of a separate
298 // 'user_env', which only holds the predicates that will actually be displayed to the user.
299 pub fn evaluate_predicates<'b, 'gcx, 'c>(
301 infcx: &InferCtxt<'b, 'tcx, 'c>,
305 param_env: ty::ParamEnv<'c>,
306 user_env: ty::ParamEnv<'c>,
307 fresh_preds: &mut FxHashSet<ty::Predicate<'c>>,
308 only_projections: bool,
309 ) -> Option<(ty::ParamEnv<'c>, ty::ParamEnv<'c>)> {
312 let mut select = SelectionContext::new(&infcx);
314 let mut already_visited = FxHashSet::default();
315 let mut predicates = VecDeque::new();
316 predicates.push_back(ty::Binder::bind(ty::TraitPredicate {
317 trait_ref: ty::TraitRef {
319 substs: infcx.tcx.mk_substs_trait(ty, &[]),
323 let mut computed_preds: FxHashSet<_> = param_env.caller_bounds.iter().cloned().collect();
324 let mut user_computed_preds: FxHashSet<_> =
325 user_env.caller_bounds.iter().cloned().collect();
327 let mut new_env = param_env.clone();
328 let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID);
330 while let Some(pred) = predicates.pop_front() {
331 infcx.clear_caches();
333 if !already_visited.insert(pred.clone()) {
337 let result = select.select(&Obligation::new(dummy_cause.clone(), new_env, pred));
340 &Ok(Some(ref vtable)) => {
341 let obligations = vtable.clone().nested_obligations().into_iter();
343 if !self.evaluate_nested_obligations(
346 &mut user_computed_preds,
356 &Err(SelectionError::Unimplemented) => {
357 if self.is_of_param(pred.skip_binder().trait_ref.substs) {
358 already_visited.remove(&pred);
360 &mut user_computed_preds,
361 ty::Predicate::Trait(pred.clone()),
363 predicates.push_back(pred);
366 "evaluate_nested_obligations: Unimplemented found, bailing: \
370 pred.skip_binder().trait_ref.substs
375 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
378 computed_preds.extend(user_computed_preds.iter().cloned());
379 let normalized_preds =
380 elaborate_predicates(tcx, computed_preds.clone().into_iter().collect());
381 new_env = ty::ParamEnv::new(tcx.mk_predicates(normalized_preds), param_env.reveal);
384 let final_user_env = ty::ParamEnv::new(
385 tcx.mk_predicates(user_computed_preds.into_iter()),
389 "evaluate_nested_obligations(ty_did={:?}, trait_did={:?}): succeeded with '{:?}' \
391 ty_did, trait_did, new_env, final_user_env
394 return Some((new_env, final_user_env));
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.
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:
410 // T as MyTrait<'static>
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.
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>(
422 user_computed_preds: &mut FxHashSet<ty::Predicate<'c>>,
423 new_pred: ty::Predicate<'c>,
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;
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
439 for (new_region, old_region) in
440 new_substs.regions().zip(old_substs.regions())
442 match (new_region, old_region) {
443 // If both predicates have an 'ReLateBound' (a HRTB) in the
444 // same spot, we do nothing
446 ty::RegionKind::ReLateBound(_, _),
447 ty::RegionKind::ReLateBound(_, _),
450 (ty::RegionKind::ReLateBound(_, _), _) => {
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
453 // match arm would have executed).
455 // The means we want to remove the older predicate from
456 // user_computed_preds, since having both it and the new
457 // predicate in a ParamEnv would confuse SelectionContext
458 // We're currently in the predicate passed to 'retain',
459 // so we return 'false' to remove the old predicate from
460 // user_computed_preds
463 (_, ty::RegionKind::ReLateBound(_, _)) => {
464 // This is the opposite situation as the previous arm - the
465 // old predicate has a HRTB lifetime in a place where the
466 // new predicate does not. We want to leave the old
467 // predicate in user_computed_preds, and skip adding
468 // new_pred to user_computed_params.
469 should_add_new = false
482 user_computed_preds.insert(new_pred);
486 pub fn region_name(&self, region: Region<'_>) -> Option<String> {
488 &ty::ReEarlyBound(r) => Some(r.name.to_string()),
493 pub fn get_lifetime(&self, region: Region<'_>,
494 names_map: &FxHashMap<String, String>) -> String {
495 self.region_name(region)
497 names_map.get(&name).unwrap_or_else(||
498 panic!("Missing lifetime with name {:?} for {:?}", name, region)
502 .unwrap_or_else(|| "'static".to_owned())
505 // This is very similar to handle_lifetimes. However, instead of matching ty::Region's
506 // to each other, we match ty::RegionVid's to ty::Region's
507 pub fn map_vid_to_region<'cx>(
509 regions: &RegionConstraintData<'cx>,
510 ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
511 let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default();
512 let mut finished_map = FxHashMap::default();
514 for constraint in regions.constraints.keys() {
516 &Constraint::VarSubVar(r1, r2) => {
518 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
519 deps1.larger.insert(RegionTarget::RegionVid(r2));
522 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
523 deps2.smaller.insert(RegionTarget::RegionVid(r1));
525 &Constraint::RegSubVar(region, vid) => {
527 let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default();
528 deps1.larger.insert(RegionTarget::RegionVid(vid));
531 let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
532 deps2.smaller.insert(RegionTarget::Region(region));
534 &Constraint::VarSubReg(vid, region) => {
535 finished_map.insert(vid, region);
537 &Constraint::RegSubReg(r1, r2) => {
539 let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default();
540 deps1.larger.insert(RegionTarget::Region(r2));
543 let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default();
544 deps2.smaller.insert(RegionTarget::Region(r1));
549 while !vid_map.is_empty() {
550 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
551 let deps = vid_map.remove(&target).expect("Entry somehow missing");
553 for smaller in deps.smaller.iter() {
554 for larger in deps.larger.iter() {
555 match (smaller, larger) {
556 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
557 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
558 let smaller_deps = v.into_mut();
559 smaller_deps.larger.insert(*larger);
560 smaller_deps.larger.remove(&target);
563 if let Entry::Occupied(v) = vid_map.entry(*larger) {
564 let larger_deps = v.into_mut();
565 larger_deps.smaller.insert(*smaller);
566 larger_deps.smaller.remove(&target);
569 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
570 finished_map.insert(v1, r1);
572 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
573 // Do nothing - we don't care about regions that are smaller than vids
575 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
576 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
577 let smaller_deps = v.into_mut();
578 smaller_deps.larger.insert(*larger);
579 smaller_deps.larger.remove(&target);
582 if let Entry::Occupied(v) = vid_map.entry(*larger) {
583 let larger_deps = v.into_mut();
584 larger_deps.smaller.insert(*smaller);
585 larger_deps.smaller.remove(&target);
595 pub fn is_of_param(&self, substs: &Substs<'_>) -> bool {
596 if substs.is_noop() {
600 return match substs.type_at(0).sty {
601 ty::Param(_) => true,
602 ty::Projection(p) => self.is_of_param(p.substs),
607 pub fn evaluate_nested_obligations<
612 T: Iterator<Item = Obligation<'cx, ty::Predicate<'cx>>>,
617 computed_preds: &'b mut FxHashSet<ty::Predicate<'cx>>,
618 fresh_preds: &'b mut FxHashSet<ty::Predicate<'cx>>,
619 predicates: &'b mut VecDeque<ty::PolyTraitPredicate<'cx>>,
620 select: &mut SelectionContext<'c, 'd, 'cx>,
621 only_projections: bool,
623 let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID);
625 for (obligation, predicate) in nested
626 .filter(|o| o.recursion_depth == 1)
627 .map(|o| (o.clone(), o.predicate.clone()))
630 fresh_preds.insert(self.clean_pred(select.infcx(), predicate.clone()));
633 &ty::Predicate::Trait(ref p) => {
634 let substs = &p.skip_binder().trait_ref.substs;
636 if self.is_of_param(substs) && !only_projections && is_new_pred {
637 self.add_user_pred(computed_preds, predicate);
639 predicates.push_back(p.clone());
641 &ty::Predicate::Projection(p) => {
642 // If the projection isn't all type vars, then
643 // we don't want to add it as a bound
644 if self.is_of_param(p.skip_binder().projection_ty.substs) && is_new_pred {
645 self.add_user_pred(computed_preds, predicate);
647 match poly_project_and_unify_type(select, &obligation.with(p.clone())) {
650 "evaluate_nested_obligations: Unable to unify predicate \
651 '{:?}' '{:?}', bailing out",
657 if !self.evaluate_nested_obligations(
659 v.clone().iter().cloned(),
670 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
675 &ty::Predicate::RegionOutlives(ref binder) => {
678 .region_outlives_predicate(&dummy_cause, binder)
684 &ty::Predicate::TypeOutlives(ref binder) => {
686 binder.no_late_bound_regions(),
687 binder.map_bound_ref(|pred| pred.0).no_late_bound_regions(),
689 (None, Some(t_a)) => {
690 select.infcx().register_region_obligation_with_cause(
692 select.infcx().tcx.types.re_static,
696 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
697 select.infcx().register_region_obligation_with_cause(
706 _ => panic!("Unexpected predicate {:?} {:?}", ty, predicate),
712 pub fn clean_pred<'c, 'd, 'cx>(
714 infcx: &InferCtxt<'c, 'd, 'cx>,
715 p: ty::Predicate<'cx>,
716 ) -> ty::Predicate<'cx> {
721 // Replaces all ReVars in a type with ty::Region's, using the provided map
722 pub struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
723 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
724 tcx: TyCtxt<'a, 'gcx, 'tcx>,
727 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
728 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
732 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
734 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
736 }).unwrap_or_else(|| r.super_fold_with(self))