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 use rustc::ty::TypeFoldable;
16 pub struct AutoTraitFinder<'a, 'tcx: 'a, 'rcx: 'a> {
17 pub cx: &'a core::DocContext<'a, 'tcx, 'rcx>,
20 impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> {
21 pub fn get_with_def_id(&self, def_id: DefId) -> Vec<Item> {
22 let ty = self.cx.tcx.type_of(def_id);
24 let def_ctor: fn(DefId) -> Def = match ty.sty {
25 ty::TyAdt(adt, _) => match adt.adt_kind() {
26 AdtKind::Struct => Def::Struct,
27 AdtKind::Enum => Def::Enum,
28 AdtKind::Union => Def::Union,
30 _ => panic!("Unexpected type {:?}", def_id),
33 self.get_auto_trait_impls(def_id, def_ctor, None)
36 pub fn get_with_node_id(&self, id: ast::NodeId, name: String) -> Vec<Item> {
37 let item = &self.cx.tcx.hir.expect_item(id).node;
38 let did = self.cx.tcx.hir.local_def_id(id);
40 let def_ctor = match *item {
41 hir::ItemStruct(_, _) => Def::Struct,
42 hir::ItemUnion(_, _) => Def::Union,
43 hir::ItemEnum(_, _) => Def::Enum,
44 _ => panic!("Unexpected type {:?} {:?}", item, id),
47 self.get_auto_trait_impls(did, def_ctor, Some(name))
50 pub fn get_auto_trait_impls(
53 def_ctor: fn(DefId) -> Def,
63 "get_auto_trait_impls(def_id={:?}, def_ctor={:?}): item has doc('hidden'), \
70 let tcx = self.cx.tcx;
71 let generics = self.cx.tcx.generics_of(def_id);
74 "get_auto_trait_impls(def_id={:?}, def_ctor={:?}, generics={:?}",
75 def_id, def_ctor, generics
77 let auto_traits: Vec<_> = self.cx
79 .and_then(|send_trait| {
80 self.get_auto_trait_impl_for(
89 .chain(self.get_auto_trait_impl_for(
94 tcx.require_lang_item(lang_items::SyncTraitLangItem),
99 "get_auto_traits: type {:?} auto_traits {:?}",
105 fn get_auto_trait_impl_for(
108 name: Option<String>,
109 generics: ty::Generics,
110 def_ctor: fn(DefId) -> Def,
114 .generated_synthetics
116 .insert((def_id, trait_def_id))
119 "get_auto_trait_impl_for(def_id={:?}, generics={:?}, def_ctor={:?}, \
120 trait_def_id={:?}): already generated, aborting",
121 def_id, generics, def_ctor, trait_def_id
126 let result = self.find_auto_trait_generics(def_id, trait_def_id, &generics);
128 if result.is_auto() {
129 let trait_ = hir::TraitRef {
130 path: get_path_for_type(self.cx.tcx, trait_def_id, hir::def::Def::Trait),
131 ref_id: ast::DUMMY_NODE_ID,
136 let new_generics = match result {
137 AutoTraitResult::PositiveImpl(new_generics) => {
141 AutoTraitResult::NegativeImpl => {
142 polarity = Some(ImplPolarity::Negative);
144 // For negative impls, we use the generic params, but *not* the predicates,
145 // from the original type. Otherwise, the displayed impl appears to be a
146 // conditional negative impl, when it's really unconditional.
148 // For example, consider the struct Foo<T: Copy>(*mut T). Using
149 // the original predicates in our impl would cause us to generate
150 // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
151 // implements Send where T is not copy.
153 // Instead, we generate `impl !Send for Foo<T>`, which better
154 // expresses the fact that `Foo<T>` never implements `Send`,
155 // regardless of the choice of `T`.
156 let real_generics = (&generics, &Default::default());
158 // Clean the generics, but ignore the '?Sized' bounds generated
159 // by the `Clean` impl
160 let clean_generics = real_generics.clean(self.cx);
163 params: clean_generics.params,
164 where_predicates: Vec::new(),
170 let path = get_path_for_type(self.cx.tcx, def_id, def_ctor);
171 let mut segments = path.segments.into_vec();
172 let last = segments.pop().unwrap();
174 let real_name = name.map(|name| Symbol::intern(&name));
176 segments.push(hir::PathSegment::new(
177 real_name.unwrap_or(last.name),
178 self.generics_to_path_params(generics.clone()),
182 let new_path = hir::Path {
185 segments: HirVec::from_vec(segments),
189 id: ast::DUMMY_NODE_ID,
190 node: hir::Ty_::TyPath(hir::QPath::Resolved(None, P(new_path))),
192 hir_id: hir::DUMMY_HIR_ID,
196 source: Span::empty(),
198 attrs: Default::default(),
200 def_id: self.next_def_id(def_id.krate),
203 inner: ImplItem(Impl {
204 unsafety: hir::Unsafety::Normal,
205 generics: new_generics,
206 provided_trait_methods: FxHashSet(),
207 trait_: Some(trait_.clean(self.cx)),
208 for_: ty.clean(self.cx),
218 fn generics_to_path_params(&self, generics: ty::Generics) -> hir::PathParameters {
219 let lifetimes = HirVec::from_vec(
224 let name = if p.name == "" {
225 hir::LifetimeName::Static
227 hir::LifetimeName::Name(p.name)
231 id: ast::DUMMY_NODE_ID,
238 let types = HirVec::from_vec(
242 .map(|p| P(self.ty_param_to_ty(p.clone())))
246 hir::PathParameters {
247 lifetimes: lifetimes,
249 bindings: HirVec::new(),
250 parenthesized: false,
254 fn ty_param_to_ty(&self, param: ty::TypeParameterDef) -> hir::Ty {
255 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
257 id: ast::DUMMY_NODE_ID,
258 node: hir::Ty_::TyPath(hir::QPath::Resolved(
262 def: Def::TyParam(param.def_id),
263 segments: HirVec::from_vec(vec![hir::PathSegment::from_name(param.name)]),
267 hir_id: hir::DUMMY_HIR_ID,
271 fn find_auto_trait_generics(
275 generics: &ty::Generics,
276 ) -> AutoTraitResult {
277 let tcx = self.cx.tcx;
278 let ty = self.cx.tcx.type_of(did);
280 let orig_params = tcx.param_env(did);
282 let trait_ref = ty::TraitRef {
284 substs: tcx.mk_substs_trait(ty, &[]),
287 let trait_pred = ty::Binder(trait_ref);
289 let bail_out = tcx.infer_ctxt().enter(|infcx| {
290 let mut selcx = SelectionContext::with_negative(&infcx, true);
291 let result = selcx.select(&Obligation::new(
292 ObligationCause::dummy(),
294 trait_pred.to_poly_trait_predicate(),
297 Ok(Some(Vtable::VtableImpl(_))) => {
299 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): \
300 manual impl found, bailing out",
301 did, trait_did, generics
309 // If an explicit impl exists, it always takes priority over an auto impl
311 return AutoTraitResult::ExplicitImpl;
314 return tcx.infer_ctxt().enter(|mut infcx| {
315 let mut fresh_preds = FxHashSet();
317 // Due to the way projections are handled by SelectionContext, we need to run
318 // evaluate_predicates twice: once on the original param env, and once on the result of
319 // the first evaluate_predicates call.
321 // The problem is this: most of rustc, including SelectionContext and traits::project,
322 // are designed to work with a concrete usage of a type (e.g. Vec<u8>
323 // fn<T>() { Vec<T> }. This information will generally never change - given
324 // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
325 // If we're unable to prove that 'T' implements a particular trait, we're done -
326 // there's nothing left to do but error out.
328 // However, synthesizing an auto trait impl works differently. Here, we start out with
329 // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
330 // with - and progressively discover the conditions we need to fulfill for it to
331 // implement a certain auto trait. This ends up breaking two assumptions made by trait
332 // selection and projection:
334 // * We can always cache the result of a particular trait selection for the lifetime of
336 // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
337 // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
339 // We fix the first assumption by manually clearing out all of the InferCtxt's caches
340 // in between calls to SelectionContext.select. This allows us to keep all of the
341 // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
342 // them between calls.
344 // We fix the second assumption by reprocessing the result of our first call to
345 // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
346 // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
347 // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
348 // SelectionContext to return it back to us.
350 let (new_env, user_env) = match self.evaluate_predicates(
361 None => return AutoTraitResult::NegativeImpl,
364 let (full_env, full_user_env) = self.evaluate_predicates(
373 ).unwrap_or_else(|| {
375 "Failed to fully process: {:?} {:?} {:?}",
376 ty, trait_did, orig_params
381 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): fulfilling \
383 did, trait_did, generics, full_env
385 infcx.clear_caches();
387 // At this point, we already have all of the bounds we need. FulfillmentContext is used
388 // to store all of the necessary region/lifetime bounds in the InferContext, as well as
389 // an additional sanity check.
390 let mut fulfill = FulfillmentContext::new();
391 fulfill.register_bound(
396 ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
398 fulfill.select_all_or_error(&infcx).unwrap_or_else(|e| {
400 "Unable to fulfill trait {:?} for '{:?}': {:?}",
405 let names_map: FxHashMap<String, Lifetime> = generics
408 .map(|l| (l.name.as_str().to_string(), l.clean(self.cx)))
411 let body_ids: FxHashSet<_> = infcx
419 infcx.process_registered_region_obligations(&[], None, full_env.clone(), id);
422 let region_data = infcx
423 .borrow_region_constraints()
424 .region_constraint_data()
427 let lifetime_predicates = self.handle_lifetimes(®ion_data, &names_map);
428 let vid_to_region = self.map_vid_to_region(®ion_data);
431 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): computed \
432 lifetime information '{:?}' '{:?}'",
433 did, trait_did, generics, lifetime_predicates, vid_to_region
436 let new_generics = self.param_env_to_generics(
445 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): finished with \
447 did, trait_did, generics, new_generics
449 return AutoTraitResult::PositiveImpl(new_generics);
453 fn clean_pred<'c, 'd, 'cx>(
455 infcx: &InferCtxt<'c, 'd, 'cx>,
456 p: ty::Predicate<'cx>,
457 ) -> ty::Predicate<'cx> {
461 fn evaluate_nested_obligations<'b, 'c, 'd, 'cx,
462 T: Iterator<Item = Obligation<'cx, ty::Predicate<'cx>>>>(
466 computed_preds: &'b mut FxHashSet<ty::Predicate<'cx>>,
467 fresh_preds: &'b mut FxHashSet<ty::Predicate<'cx>>,
468 predicates: &'b mut VecDeque<ty::PolyTraitPredicate<'cx>>,
469 select: &mut traits::SelectionContext<'c, 'd, 'cx>,
470 only_projections: bool,
472 let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID);
474 for (obligation, predicate) in nested
475 .filter(|o| o.recursion_depth == 1)
476 .map(|o| (o.clone(), o.predicate.clone()))
479 fresh_preds.insert(self.clean_pred(select.infcx(), predicate.clone()));
482 &ty::Predicate::Trait(ref p) => {
483 let substs = &p.skip_binder().trait_ref.substs;
485 if self.is_of_param(substs) && !only_projections && is_new_pred {
486 computed_preds.insert(predicate);
488 predicates.push_back(p.clone());
490 &ty::Predicate::Projection(p) => {
491 // If the projection isn't all type vars, then
492 // we don't want to add it as a bound
493 if self.is_of_param(p.skip_binder().projection_ty.substs) && is_new_pred {
494 computed_preds.insert(predicate);
496 match traits::poly_project_and_unify_type(
498 &obligation.with(p.clone()),
502 "evaluate_nested_obligations: Unable to unify predicate \
503 '{:?}' '{:?}', bailing out",
509 if !self.evaluate_nested_obligations(
511 v.clone().iter().cloned(),
522 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
527 &ty::Predicate::RegionOutlives(ref binder) => {
528 if let Err(_) = select
530 .region_outlives_predicate(&dummy_cause, binder)
535 &ty::Predicate::TypeOutlives(ref binder) => {
537 binder.no_late_bound_regions(),
538 binder.map_bound_ref(|pred| pred.0).no_late_bound_regions(),
540 (None, Some(t_a)) => {
541 select.infcx().register_region_obligation(
545 sub_region: select.infcx().tcx.types.re_static,
546 cause: dummy_cause.clone(),
550 (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
551 select.infcx().register_region_obligation(
556 cause: dummy_cause.clone(),
563 _ => panic!("Unexpected predicate {:?} {:?}", ty, predicate),
569 // The core logic responsible for computing the bounds for our synthesized impl.
571 // To calculate the bounds, we call SelectionContext.select in a loop. Like FulfillmentContext,
572 // we recursively select the nested obligations of predicates we encounter. However, whenver we
573 // encounter an UnimplementedError involving a type parameter, we add it to our ParamEnv. Since
574 // our goal is to determine when a particular type implements an auto trait, Unimplemented
575 // errors tell us what conditions need to be met.
577 // This method ends up working somewhat similary to FulfillmentContext, but with a few key
578 // differences. FulfillmentContext works under the assumption that it's dealing with concrete
579 // user code. According, it considers all possible ways that a Predicate could be met - which
580 // isn't always what we want for a synthesized impl. For example, given the predicate 'T:
581 // Iterator', FulfillmentContext can end up reporting an Unimplemented error for T:
582 // IntoIterator - since there's an implementation of Iteratpr where T: IntoIterator,
583 // FulfillmentContext will drive SelectionContext to consider that impl before giving up. If we
584 // were to rely on FulfillmentContext's decision, we might end up synthesizing an impl like
586 // 'impl<T> Send for Foo<T> where T: IntoIterator'
588 // While it might be technically true that Foo implements Send where T: IntoIterator,
589 // the bound is overly restrictive - it's really only necessary that T: Iterator.
591 // For this reason, evaluate_predicates handles predicates with type variables specially. When
592 // we encounter an Unimplemented error for a bound such as 'T: Iterator', we immediately add it
593 // to our ParamEnv, and add it to our stack for recursive evaluation. When we later select it,
594 // we'll pick up any nested bounds, without ever inferring that 'T: IntoIterator' needs to
597 // One additonal consideration is supertrait bounds. Normally, a ParamEnv is only ever
598 // consutrcted once for a given type. As part of the construction process, the ParamEnv will
599 // have any supertrait bounds normalized - e.g. if we have a type 'struct Foo<T: Copy>', the
600 // ParamEnv will contain 'T: Copy' and 'T: Clone', since 'Copy: Clone'. When we construct our
601 // own ParamEnv, we need to do this outselves, through traits::elaborate_predicates, or else
602 // SelectionContext will choke on the missing predicates. However, this should never show up in
603 // the final synthesized generics: we don't want our generated docs page to contain something
604 // like 'T: Copy + Clone', as that's redundant. Therefore, we keep track of a separate
605 // 'user_env', which only holds the predicates that will actually be displayed to the user.
606 fn evaluate_predicates<'b, 'gcx, 'c>(
608 infcx: &mut InferCtxt<'b, 'tcx, 'c>,
612 param_env: ty::ParamEnv<'c>,
613 user_env: ty::ParamEnv<'c>,
614 fresh_preds: &mut FxHashSet<ty::Predicate<'c>>,
615 only_projections: bool,
616 ) -> Option<(ty::ParamEnv<'c>, ty::ParamEnv<'c>)> {
619 let mut select = traits::SelectionContext::new(&infcx);
621 let mut already_visited = FxHashSet();
622 let mut predicates = VecDeque::new();
623 predicates.push_back(ty::Binder(ty::TraitPredicate {
624 trait_ref: ty::TraitRef {
626 substs: infcx.tcx.mk_substs_trait(ty, &[]),
630 let mut computed_preds: FxHashSet<_> = param_env.caller_bounds.iter().cloned().collect();
631 let mut user_computed_preds: FxHashSet<_> =
632 user_env.caller_bounds.iter().cloned().collect();
634 let mut new_env = param_env.clone();
635 let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID);
637 while let Some(pred) = predicates.pop_front() {
638 infcx.clear_caches();
640 if !already_visited.insert(pred.clone()) {
644 let result = select.select(&Obligation::new(dummy_cause.clone(), new_env, pred));
647 &Ok(Some(ref vtable)) => {
648 let obligations = vtable.clone().nested_obligations().into_iter();
650 if !self.evaluate_nested_obligations(
653 &mut user_computed_preds,
663 &Err(SelectionError::Unimplemented) => {
664 if self.is_of_param(pred.skip_binder().trait_ref.substs) {
665 already_visited.remove(&pred);
666 user_computed_preds.insert(ty::Predicate::Trait(pred.clone()));
667 predicates.push_back(pred);
670 "evaluate_nested_obligations: Unimplemented found, bailing: {:?} {:?} \
674 pred.skip_binder().trait_ref.substs
679 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
682 computed_preds.extend(user_computed_preds.iter().cloned());
683 let normalized_preds =
684 traits::elaborate_predicates(tcx, computed_preds.clone().into_iter().collect());
685 new_env = ty::ParamEnv::new(
686 tcx.mk_predicates(normalized_preds),
691 let final_user_env = ty::ParamEnv::new(
692 tcx.mk_predicates(user_computed_preds.into_iter()),
696 "evaluate_nested_obligations(ty_did={:?}, trait_did={:?}): succeeded with '{:?}' \
698 ty_did, trait_did, new_env, final_user_env
701 return Some((new_env, final_user_env));
704 fn is_of_param(&self, substs: &Substs) -> bool {
705 if substs.is_noop() {
709 return match substs.type_at(0).sty {
710 ty::TyParam(_) => true,
711 ty::TyProjection(p) => self.is_of_param(p.substs),
716 fn get_lifetime(&self, region: Region, names_map: &FxHashMap<String, Lifetime>) -> Lifetime {
717 self.region_name(region)
719 names_map.get(&name).unwrap_or_else(|| {
720 panic!("Missing lifetime with name {:?} for {:?}", name, region)
723 .unwrap_or(&Lifetime::statik())
727 fn region_name(&self, region: Region) -> Option<String> {
729 &ty::ReEarlyBound(r) => Some(r.name.as_str().to_string()),
734 // This is very similar to handle_lifetimes. However, instead of matching ty::Region's
735 // to each other, we match ty::RegionVid's to ty::Region's
736 fn map_vid_to_region<'cx>(
738 regions: &RegionConstraintData<'cx>,
739 ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
740 let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap();
741 let mut finished_map = FxHashMap();
743 for constraint in regions.constraints.keys() {
745 &Constraint::VarSubVar(r1, r2) => {
748 .entry(RegionTarget::RegionVid(r1))
749 .or_insert_with(|| Default::default());
750 deps1.larger.insert(RegionTarget::RegionVid(r2));
754 .entry(RegionTarget::RegionVid(r2))
755 .or_insert_with(|| Default::default());
756 deps2.smaller.insert(RegionTarget::RegionVid(r1));
758 &Constraint::RegSubVar(region, vid) => {
761 .entry(RegionTarget::Region(region))
762 .or_insert_with(|| Default::default());
763 deps1.larger.insert(RegionTarget::RegionVid(vid));
767 .entry(RegionTarget::RegionVid(vid))
768 .or_insert_with(|| Default::default());
769 deps2.smaller.insert(RegionTarget::Region(region));
771 &Constraint::VarSubReg(vid, region) => {
772 finished_map.insert(vid, region);
774 &Constraint::RegSubReg(r1, r2) => {
777 .entry(RegionTarget::Region(r1))
778 .or_insert_with(|| Default::default());
779 deps1.larger.insert(RegionTarget::Region(r2));
783 .entry(RegionTarget::Region(r2))
784 .or_insert_with(|| Default::default());
785 deps2.smaller.insert(RegionTarget::Region(r1));
790 while !vid_map.is_empty() {
791 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
792 let deps = vid_map.remove(&target).expect("Entry somehow missing");
794 for smaller in deps.smaller.iter() {
795 for larger in deps.larger.iter() {
796 match (smaller, larger) {
797 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
798 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
799 let smaller_deps = v.into_mut();
800 smaller_deps.larger.insert(*larger);
801 smaller_deps.larger.remove(&target);
804 if let Entry::Occupied(v) = vid_map.entry(*larger) {
805 let larger_deps = v.into_mut();
806 larger_deps.smaller.insert(*smaller);
807 larger_deps.smaller.remove(&target);
810 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
811 finished_map.insert(v1, r1);
813 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
814 // Do nothing - we don't care about regions that are smaller than vids
816 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
817 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
818 let smaller_deps = v.into_mut();
819 smaller_deps.larger.insert(*larger);
820 smaller_deps.larger.remove(&target);
823 if let Entry::Occupied(v) = vid_map.entry(*larger) {
824 let larger_deps = v.into_mut();
825 larger_deps.smaller.insert(*smaller);
826 larger_deps.smaller.remove(&target);
836 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
837 // and region constraints of the form ReVar: 'a
839 // This is essentially a simplified version of lexical_region_resolve. However,
840 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
841 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
842 // with determining if a given set up constraints/predicates *are* met, given some
843 // starting conditions (e.g. user-provided code). For this reason, it's easier
844 // to perform the calculations we need on our own, rather than trying to make
845 // existing inference/solver code do what we want.
846 fn handle_lifetimes<'cx>(
848 regions: &RegionConstraintData<'cx>,
849 names_map: &FxHashMap<String, Lifetime>,
850 ) -> Vec<WherePredicate> {
851 // Our goal is to 'flatten' the list of constraints by eliminating
852 // all intermediate RegionVids. At the end, all constraints should
853 // be between Regions (aka region variables). This gives us the information
854 // we need to create the Generics.
855 let mut finished = FxHashMap();
857 let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = FxHashMap();
859 // Flattening is done in two parts. First, we insert all of the constraints
860 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
861 // to its smaller and larger regions. Note that 'larger' regions correspond
862 // to sub-regions in Rust code (e.g. in 'a: 'b, 'a is the larger region).
863 for constraint in regions.constraints.keys() {
865 &Constraint::VarSubVar(r1, r2) => {
868 .entry(RegionTarget::RegionVid(r1))
869 .or_insert_with(|| Default::default());
870 deps1.larger.insert(RegionTarget::RegionVid(r2));
874 .entry(RegionTarget::RegionVid(r2))
875 .or_insert_with(|| Default::default());
876 deps2.smaller.insert(RegionTarget::RegionVid(r1));
878 &Constraint::RegSubVar(region, vid) => {
880 .entry(RegionTarget::RegionVid(vid))
881 .or_insert_with(|| Default::default());
882 deps.smaller.insert(RegionTarget::Region(region));
884 &Constraint::VarSubReg(vid, region) => {
886 .entry(RegionTarget::RegionVid(vid))
887 .or_insert_with(|| Default::default());
888 deps.larger.insert(RegionTarget::Region(region));
890 &Constraint::RegSubReg(r1, r2) => {
891 // The constraint is already in the form that we want, so we're done with it
892 // Desired order is 'larger, smaller', so flip then
893 if self.region_name(r1) != self.region_name(r2) {
895 .entry(self.region_name(r2).unwrap())
896 .or_insert_with(|| Vec::new())
903 // Here, we 'flatten' the map one element at a time.
904 // All of the element's sub and super regions are connected
905 // to each other. For example, if we have a graph that looks like this:
907 // (A, B) - C - (D, E)
908 // Where (A, B) are subregions, and (D,E) are super-regions
910 // then after deleting 'C', the graph will look like this:
911 // ... - A - (D, E ...)
912 // ... - B - (D, E, ...)
913 // (A, B, ...) - D - ...
914 // (A, B, ...) - E - ...
916 // where '...' signifies the existing sub and super regions of an entry
917 // When two adjacent ty::Regions are encountered, we've computed a final
918 // constraint, and add it to our list. Since we make sure to never re-add
919 // deleted items, this process will always finish.
920 while !vid_map.is_empty() {
921 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
922 let deps = vid_map.remove(&target).expect("Entry somehow missing");
924 for smaller in deps.smaller.iter() {
925 for larger in deps.larger.iter() {
926 match (smaller, larger) {
927 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
928 if self.region_name(r1) != self.region_name(r2) {
930 .entry(self.region_name(r2).unwrap())
931 .or_insert_with(|| Vec::new())
932 .push(r1) // Larger, smaller
935 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
936 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
937 let smaller_deps = v.into_mut();
938 smaller_deps.larger.insert(*larger);
939 smaller_deps.larger.remove(&target);
942 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
943 if let Entry::Occupied(v) = vid_map.entry(*larger) {
944 let deps = v.into_mut();
945 deps.smaller.insert(*smaller);
946 deps.smaller.remove(&target);
949 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
950 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
951 let smaller_deps = v.into_mut();
952 smaller_deps.larger.insert(*larger);
953 smaller_deps.larger.remove(&target);
956 if let Entry::Occupied(v) = vid_map.entry(*larger) {
957 let larger_deps = v.into_mut();
958 larger_deps.smaller.insert(*smaller);
959 larger_deps.smaller.remove(&target);
967 let lifetime_predicates = names_map
969 .flat_map(|(name, lifetime)| {
970 let empty = Vec::new();
971 let bounds: FxHashSet<Lifetime> = finished
975 .map(|region| self.get_lifetime(region, names_map))
978 if bounds.is_empty() {
981 Some(WherePredicate::RegionPredicate {
982 lifetime: lifetime.clone(),
983 bounds: bounds.into_iter().collect(),
991 fn extract_for_generics<'b, 'c, 'd>(
993 tcx: TyCtxt<'b, 'c, 'd>,
994 pred: ty::Predicate<'d>,
995 ) -> FxHashSet<GenericParam> {
998 let mut regions = FxHashSet();
999 tcx.collect_regions(&t, &mut regions);
1001 regions.into_iter().flat_map(|r| {
1003 // We only care about late bound regions, as we need to add them
1004 // to the 'for<>' section
1005 &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
1006 Some(GenericParam::Lifetime(Lifetime(name.as_str().to_string())))
1008 &ty::ReVar(_) | &ty::ReEarlyBound(_) => None,
1009 _ => panic!("Unexpected region type {:?}", r),
1016 fn make_final_bounds<'b, 'c, 'cx>(
1018 ty_to_bounds: FxHashMap<Type, FxHashSet<TyParamBound>>,
1019 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
1020 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<Lifetime>>,
1021 ) -> Vec<WherePredicate> {
1024 .flat_map(|(ty, mut bounds)| {
1025 if let Some(data) = ty_to_fn.get(&ty) {
1026 let (poly_trait, output) =
1027 (data.0.as_ref().unwrap().clone(), data.1.as_ref().cloned());
1028 let new_ty = match &poly_trait.trait_ {
1029 &Type::ResolvedPath {
1035 let mut new_path = path.clone();
1036 let last_segment = new_path.segments.pop().unwrap();
1038 let (old_input, old_output) = match last_segment.params {
1039 PathParameters::AngleBracketed { types, .. } => (types, None),
1040 PathParameters::Parenthesized { inputs, output, .. } => {
1045 if old_output.is_some() && old_output != output {
1047 "Output mismatch for {:?} {:?} {:?}",
1048 ty, old_output, data.1
1052 let new_params = PathParameters::Parenthesized {
1057 new_path.segments.push(PathSegment {
1058 name: last_segment.name,
1062 Type::ResolvedPath {
1064 typarams: typarams.clone(),
1066 is_generic: *is_generic,
1069 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
1071 bounds.insert(TyParamBound::TraitBound(
1074 generic_params: poly_trait.generic_params,
1076 hir::TraitBoundModifier::None,
1079 if bounds.is_empty() {
1083 let mut bounds_vec = bounds.into_iter().collect();
1084 self.sort_where_bounds(&mut bounds_vec);
1086 Some(WherePredicate::BoundPredicate {
1094 .filter(|&(_, ref bounds)| !bounds.is_empty())
1095 .map(|(lifetime, bounds)| {
1096 let mut bounds_vec = bounds.into_iter().collect();
1097 self.sort_where_lifetimes(&mut bounds_vec);
1098 WherePredicate::RegionPredicate {
1107 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
1108 // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
1109 // so we fix them up:
1111 // * Multiple bounds for the same type are coalesced into one: e.g. 'T: Copy', 'T: Debug'
1112 // becomes 'T: Copy + Debug'
1113 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
1114 // K', we use the dedicated syntax 'T: Fn() -> K'
1115 // * We explcitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
1116 fn param_env_to_generics<'b, 'c, 'cx>(
1118 tcx: TyCtxt<'b, 'c, 'cx>,
1120 param_env: ty::ParamEnv<'cx>,
1121 type_generics: ty::Generics,
1122 mut existing_predicates: Vec<WherePredicate>,
1123 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
1126 "param_env_to_generics(did={:?}, param_env={:?}, type_generics={:?}, \
1127 existing_predicates={:?})",
1128 did, param_env, type_generics, existing_predicates
1131 // The `Sized` trait must be handled specially, since we only only display it when
1132 // it is *not* required (i.e. '?Sized')
1133 let sized_trait = self.cx
1135 .require_lang_item(lang_items::SizedTraitLangItem);
1137 let mut replacer = RegionReplacer {
1138 vid_to_region: &vid_to_region,
1142 let orig_bounds: FxHashSet<_> = self.cx.tcx.param_env(did).caller_bounds.iter().collect();
1143 let clean_where_predicates = param_env
1147 !orig_bounds.contains(p) || match p {
1148 &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
1153 let replaced = p.fold_with(&mut replacer);
1154 (replaced.clone(), replaced.clean(self.cx))
1157 let full_generics = (&type_generics, &tcx.predicates_of(did));
1159 params: mut generic_params,
1161 } = full_generics.clean(self.cx);
1163 let mut has_sized = FxHashSet();
1164 let mut ty_to_bounds = FxHashMap();
1165 let mut lifetime_to_bounds = FxHashMap();
1166 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = FxHashMap();
1168 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = FxHashMap();
1170 for (orig_p, p) in clean_where_predicates {
1172 WherePredicate::BoundPredicate { ty, mut bounds } => {
1173 // Writing a projection trait bound of the form
1174 // <T as Trait>::Name : ?Sized
1175 // is illegal, because ?Sized bounds can only
1176 // be written in the (here, nonexistant) definition
1178 // Therefore, we make sure that we never add a ?Sized
1179 // bound for projections
1181 &Type::QPath { .. } => {
1182 has_sized.insert(ty.clone());
1187 if bounds.is_empty() {
1191 let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
1193 assert!(bounds.len() == 1);
1194 let mut b = bounds.pop().unwrap();
1196 if b.is_sized_bound(self.cx) {
1197 has_sized.insert(ty.clone());
1198 } else if !b.get_trait_type()
1202 .map(|bounds| bounds.contains(&strip_type(t.clone())))
1206 // If we've already added a projection bound for the same type, don't add
1207 // this, as it would be a duplicate
1209 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
1210 // as we want to combine them with any 'Output' qpaths
1213 let is_fn = match &mut b {
1214 &mut TyParamBound::TraitBound(ref mut p, _) => {
1215 // Insert regions into the for_generics hash map first, to ensure
1216 // that we don't end up with duplicate bounds (e.g. for<'b, 'b>)
1217 for_generics.extend(p.generic_params.clone());
1218 p.generic_params = for_generics.into_iter().collect();
1219 self.is_fn_ty(&tcx, &p.trait_)
1224 let poly_trait = b.get_poly_trait().unwrap();
1229 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
1230 .or_insert(((Some(poly_trait.clone())), None));
1234 .or_insert_with(|| FxHashSet());
1238 .or_insert_with(|| FxHashSet())
1243 WherePredicate::RegionPredicate { lifetime, bounds } => {
1246 .or_insert_with(|| FxHashSet())
1249 WherePredicate::EqPredicate { lhs, rhs } => {
1252 name: ref left_name,
1256 let ty = &*self_type;
1258 Type::ResolvedPath {
1259 path: ref trait_path,
1264 let mut new_trait_path = trait_path.clone();
1266 if self.is_fn_ty(&tcx, trait_) && left_name == FN_OUTPUT_NAME {
1269 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
1270 .or_insert((None, Some(rhs)));
1274 // FIXME: Remove this scope when NLL lands
1277 &mut new_trait_path.segments.last_mut().unwrap().params;
1280 // Convert somethiung like '<T as Iterator::Item> = u8'
1281 // to 'T: Iterator<Item=u8>'
1282 &mut PathParameters::AngleBracketed {
1286 bindings.push(TypeBinding {
1287 name: left_name.clone(),
1291 &mut PathParameters::Parenthesized { .. } => {
1292 existing_predicates.push(
1293 WherePredicate::EqPredicate {
1298 continue; // If something other than a Fn ends up
1299 // with parenthesis, leave it alone
1304 let bounds = ty_to_bounds
1306 .or_insert_with(|| FxHashSet());
1308 bounds.insert(TyParamBound::TraitBound(
1310 trait_: Type::ResolvedPath {
1311 path: new_trait_path,
1312 typarams: typarams.clone(),
1314 is_generic: *is_generic,
1316 generic_params: Vec::new(),
1318 hir::TraitBoundModifier::None,
1321 // Remove any existing 'plain' bound (e.g. 'T: Iterator`) so
1322 // that we don't see a
1323 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
1324 // on the docs page.
1325 bounds.remove(&TyParamBound::TraitBound(
1327 trait_: *trait_.clone(),
1328 generic_params: Vec::new(),
1330 hir::TraitBoundModifier::None,
1332 // Avoid creating any new duplicate bounds later in the outer
1336 .or_insert_with(|| FxHashSet())
1337 .insert(*trait_.clone());
1339 _ => panic!("Unexpected trait {:?} for {:?}", trait_, did),
1342 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, did),
1348 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
1350 existing_predicates.extend(final_bounds);
1352 for p in generic_params.iter_mut() {
1354 &mut GenericParam::Type(ref mut ty) => {
1355 // We never want something like 'impl<T=Foo>'
1358 let generic_ty = Type::Generic(ty.name.clone());
1360 if !has_sized.contains(&generic_ty) {
1361 ty.bounds.insert(0, TyParamBound::maybe_sized(self.cx));
1368 self.sort_where_predicates(&mut existing_predicates);
1371 params: generic_params,
1372 where_predicates: existing_predicates,
1376 // Ensure that the predicates are in a consistent order. The precise
1377 // ordering doesn't actually matter, but it's important that
1378 // a given set of predicates always appears in the same order -
1379 // both for visual consistency between 'rustdoc' runs, and to
1380 // make writing tests much easier
1382 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
1383 // We should never have identical bounds - and if we do,
1384 // they're visually identical as well. Therefore, using
1385 // an unstable sort is fine.
1386 self.unstable_debug_sort(&mut predicates);
1389 // Ensure that the bounds are in a consistent order. The precise
1390 // ordering doesn't actually matter, but it's important that
1391 // a given set of bounds always appears in the same order -
1392 // both for visual consistency between 'rustdoc' runs, and to
1393 // make writing tests much easier
1395 fn sort_where_bounds(&self, mut bounds: &mut Vec<TyParamBound>) {
1396 // We should never have identical bounds - and if we do,
1397 // they're visually identical as well. Therefore, using
1398 // an unstable sort is fine.
1399 self.unstable_debug_sort(&mut bounds);
1403 fn sort_where_lifetimes(&self, mut bounds: &mut Vec<Lifetime>) {
1404 // We should never have identical bounds - and if we do,
1405 // they're visually identical as well. Therefore, using
1406 // an unstable sort is fine.
1407 self.unstable_debug_sort(&mut bounds);
1410 // This might look horrendously hacky, but it's actually not that bad.
1412 // For performance reasons, we use several different FxHashMaps
1413 // in the process of computing the final set of where predicates.
1414 // However, the iteration order of a HashMap is completely unspecified.
1415 // In fact, the iteration of an FxHashMap can even vary between platforms,
1416 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
1418 // Obviously, it's extremely undesireable for documentation rendering
1419 // to be depndent on the platform it's run on. Apart from being confusing
1420 // to end users, it makes writing tests much more difficult, as predicates
1421 // can appear in any order in the final result.
1423 // To solve this problem, we sort WherePredicates and TyParamBounds
1424 // by their Debug string. The thing to keep in mind is that we don't really
1425 // care what the final order is - we're synthesizing an impl or bound
1426 // ourselves, so any order can be considered equally valid. By sorting the
1427 // predicates and bounds, however, we ensure that for a given codebase, all
1428 // auto-trait impls always render in exactly the same way.
1430 // Using the Debug impementation for sorting prevents us from needing to
1431 // write quite a bit of almost entirely useless code (e.g. how should two
1432 // Types be sorted relative to each other). It also allows us to solve the
1433 // problem for both WherePredicates and TyParamBounds at the same time. This
1434 // approach is probably somewhat slower, but the small number of items
1435 // involved (impls rarely have more than a few bounds) means that it
1436 // shouldn't matter in practice.
1437 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
1438 vec.sort_unstable_by(|first, second| {
1439 format!("{:?}", first).cmp(&format!("{:?}", second))
1443 fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {
1445 &&Type::ResolvedPath { ref did, .. } => {
1446 *did == tcx.require_lang_item(lang_items::FnTraitLangItem)
1447 || *did == tcx.require_lang_item(lang_items::FnMutTraitLangItem)
1448 || *did == tcx.require_lang_item(lang_items::FnOnceTraitLangItem)
1454 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
1455 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
1456 // registered after the AST is constructed would require storing the defid mapping in a
1457 // RefCell, decreasing the performance for normal compilation for very little gain.
1459 // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
1460 // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
1461 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
1462 fn next_def_id(&self, crate_num: CrateNum) -> DefId {
1463 let start_def_id = {
1464 let next_id = if crate_num == LOCAL_CRATE {
1470 .next_id(DefIndexAddressSpace::Low)
1474 .def_path_table(crate_num)
1475 .next_id(DefIndexAddressSpace::Low)
1484 let mut fake_ids = self.cx.fake_def_ids.borrow_mut();
1486 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
1491 index: DefIndex::from_array_index(
1492 def_id.index.as_array_index() + 1,
1493 def_id.index.address_space(),
1498 MAX_DEF_ID.with(|m| {
1500 .entry(def_id.krate.clone())
1501 .or_insert(start_def_id);
1504 self.cx.all_fake_def_ids.borrow_mut().insert(def_id);
1510 // Replaces all ReVars in a type with ty::Region's, using the provided map
1511 struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
1512 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
1513 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1516 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
1517 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
1521 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1523 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
1525 }).unwrap_or_else(|| r.super_fold_with(self))