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.
12 use rustc::traits::{self, auto_trait as auto};
13 use rustc::ty::{self, ToPredicate, TypeFoldable};
14 use rustc::ty::subst::Subst;
15 use rustc::infer::InferOk;
17 use syntax_pos::DUMMY_SP;
19 use core::DocAccessLevels;
23 pub struct AutoTraitFinder<'a, 'tcx: 'a, 'rcx: 'a> {
24 pub cx: &'a core::DocContext<'a, 'tcx, 'rcx>,
25 pub f: auto::AutoTraitFinder<'a, 'tcx>,
28 impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> {
29 pub fn new(cx: &'a core::DocContext<'a, 'tcx, 'rcx>) -> Self {
30 let f = auto::AutoTraitFinder::new(&cx.tcx);
32 AutoTraitFinder { cx, f }
35 pub fn get_with_def_id(&self, def_id: DefId) -> Vec<Item> {
36 let ty = self.cx.tcx.type_of(def_id);
38 let def_ctor: fn(DefId) -> Def = match ty.sty {
39 ty::TyAdt(adt, _) => match adt.adt_kind() {
40 AdtKind::Struct => Def::Struct,
41 AdtKind::Enum => Def::Enum,
42 AdtKind::Union => Def::Union,
49 ty::TyChar => return self.get_auto_trait_impls(def_id, &move |_: DefId| {
51 ty::TyInt(x) => Def::PrimTy(hir::TyInt(x)),
52 ty::TyUint(x) => Def::PrimTy(hir::TyUint(x)),
53 ty::TyFloat(x) => Def::PrimTy(hir::TyFloat(x)),
54 ty::TyStr => Def::PrimTy(hir::TyStr),
55 ty::TyBool => Def::PrimTy(hir::TyBool),
56 ty::TyChar => Def::PrimTy(hir::TyChar),
61 debug!("Unexpected type {:?}", def_id);
66 self.get_auto_trait_impls(def_id, &def_ctor, None)
69 pub fn get_with_node_id(&self, id: ast::NodeId, name: String) -> Vec<Item> {
70 let item = &self.cx.tcx.hir.expect_item(id).node;
71 let did = self.cx.tcx.hir.local_def_id(id);
73 let def_ctor = match *item {
74 hir::ItemKind::Struct(_, _) => Def::Struct,
75 hir::ItemKind::Union(_, _) => Def::Union,
76 hir::ItemKind::Enum(_, _) => Def::Enum,
77 _ => panic!("Unexpected type {:?} {:?}", item, id),
80 self.get_auto_trait_impls(did, &def_ctor, Some(name))
83 fn get_real_ty<F>(&self, def_id: DefId, def_ctor: &F, real_name: &Option<Ident>,
84 generics: &ty::Generics) -> hir::Ty
85 where F: Fn(DefId) -> Def {
86 let path = get_path_for_type(self.cx.tcx, def_id, def_ctor);
87 let mut segments = path.segments.into_vec();
88 let last = segments.pop().unwrap();
90 segments.push(hir::PathSegment::new(
91 real_name.unwrap_or(last.ident),
92 self.generics_to_path_params(generics.clone()),
96 let new_path = hir::Path {
99 segments: HirVec::from_vec(segments),
103 id: ast::DUMMY_NODE_ID,
104 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
106 hir_id: hir::DUMMY_HIR_ID,
110 pub fn get_auto_trait_impls<F>(
114 name: Option<String>,
116 where F: Fn(DefId) -> Def {
124 "get_auto_trait_impls(def_id={:?}, def_ctor=...): item has doc('hidden'), \
131 let tcx = self.cx.tcx;
132 let generics = self.cx.tcx.generics_of(def_id);
134 let ty = self.cx.tcx.type_of(def_id);
135 let mut traits = Vec::new();
136 if self.cx.crate_name != Some("core".to_string()) {
137 if let ty::TyAdt(_adt, _) = ty.sty {
138 let real_name = name.clone().map(|name| Ident::from_str(&name));
139 let param_env = self.cx.tcx.param_env(def_id);
140 for &trait_def_id in self.cx.all_traits.iter() {
141 if !self.cx.access_levels.borrow().is_doc_reachable(trait_def_id) ||
142 self.cx.generated_synthetics
144 .get(&(def_id, trait_def_id))
148 self.cx.tcx.for_each_relevant_impl(trait_def_id, ty, |impl_def_id| {
149 self.cx.tcx.infer_ctxt().enter(|infcx| {
150 let generics = infcx.tcx.generics_of(impl_def_id);
151 let trait_ref = infcx.tcx.impl_trait_ref(impl_def_id).unwrap();
153 if !match infcx.tcx.type_of(impl_def_id).sty {
154 ::rustc::ty::TypeVariants::TyParam(_) => true,
160 let substs = infcx.fresh_substs_for_item(DUMMY_SP, def_id);
161 let ty2 = ty.subst(infcx.tcx, substs);
162 let param_env = param_env.subst(infcx.tcx, substs);
164 let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
165 let trait_ref = trait_ref.subst(infcx.tcx, impl_substs);
167 // Require the type the impl is implemented on to match
168 // our type, and ignore the impl if there was a mismatch.
169 let cause = traits::ObligationCause::dummy();
170 let eq_result = infcx.at(&cause, param_env)
171 .eq(trait_ref.self_ty(), ty2);
172 if let Ok(InferOk { value: (), obligations }) = eq_result {
173 // FIXME(eddyb) ignoring `obligations` might cause false positives.
176 let may_apply = infcx.predicate_may_hold(&traits::Obligation::new(
179 trait_ref.to_predicate(),
184 self.cx.generated_synthetics.borrow_mut()
185 .insert((def_id, trait_def_id));
186 let trait_ = hir::TraitRef {
187 path: get_path_for_type(infcx.tcx,
189 hir::def::Def::Trait),
190 ref_id: ast::DUMMY_NODE_ID,
192 let provided_trait_methods =
193 infcx.tcx.provided_trait_methods(impl_def_id)
195 .map(|meth| meth.ident.to_string())
198 let ty = self.get_real_ty(def_id, def_ctor, &real_name, generics);
201 source: Span::empty(),
203 attrs: Default::default(),
205 def_id: self.next_def_id(impl_def_id.krate),
208 inner: ImplItem(Impl {
209 unsafety: hir::Unsafety::Normal,
211 &tcx.predicates_of(impl_def_id)).clean(self.cx),
212 provided_trait_methods,
213 trait_: Some(trait_.clean(self.cx)),
214 for_: ty.clean(self.cx),
215 items: infcx.tcx.associated_items(impl_def_id)
222 debug!("{:?} => {}", trait_ref, may_apply);
231 "get_auto_trait_impls(def_id={:?}, def_ctor=..., generics={:?}",
234 let auto_traits: Vec<_> =
236 .and_then(|send_trait| {
237 self.get_auto_trait_impl_for(
245 .chain(self.get_auto_trait_impl_for(
250 tcx.require_lang_item(lang_items::SyncTraitLangItem),
252 .chain(traits.into_iter())
256 "get_auto_traits: type {:?} auto_traits {:?}",
262 fn get_auto_trait_impl_for<F>(
265 name: Option<String>,
266 generics: ty::Generics,
270 where F: Fn(DefId) -> Def {
272 .generated_synthetics
274 .insert((def_id, trait_def_id))
277 "get_auto_trait_impl_for(def_id={:?}, generics={:?}, def_ctor=..., \
278 trait_def_id={:?}): already generated, aborting",
279 def_id, generics, trait_def_id
284 let result = self.find_auto_trait_generics(def_id, trait_def_id, &generics);
286 if result.is_auto() {
287 let trait_ = hir::TraitRef {
288 path: get_path_for_type(self.cx.tcx, trait_def_id, hir::def::Def::Trait),
289 ref_id: ast::DUMMY_NODE_ID,
294 let new_generics = match result {
295 AutoTraitResult::PositiveImpl(new_generics) => {
299 AutoTraitResult::NegativeImpl => {
300 polarity = Some(ImplPolarity::Negative);
302 // For negative impls, we use the generic params, but *not* the predicates,
303 // from the original type. Otherwise, the displayed impl appears to be a
304 // conditional negative impl, when it's really unconditional.
306 // For example, consider the struct Foo<T: Copy>(*mut T). Using
307 // the original predicates in our impl would cause us to generate
308 // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
309 // implements Send where T is not copy.
311 // Instead, we generate `impl !Send for Foo<T>`, which better
312 // expresses the fact that `Foo<T>` never implements `Send`,
313 // regardless of the choice of `T`.
314 let real_generics = (&generics, &Default::default());
316 // Clean the generics, but ignore the '?Sized' bounds generated
317 // by the `Clean` impl
318 let clean_generics = real_generics.clean(self.cx);
321 params: clean_generics.params,
322 where_predicates: Vec::new(),
327 let real_name = name.map(|name| Ident::from_str(&name));
328 let ty = self.get_real_ty(def_id, def_ctor, &real_name, &generics);
331 source: Span::empty(),
333 attrs: Default::default(),
335 def_id: self.next_def_id(def_id.krate),
338 inner: ImplItem(Impl {
339 unsafety: hir::Unsafety::Normal,
340 generics: new_generics,
341 provided_trait_methods: FxHashSet(),
342 trait_: Some(trait_.clean(self.cx)),
343 for_: ty.clean(self.cx),
353 fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
354 let mut args = vec![];
356 for param in generics.params.iter() {
358 ty::GenericParamDefKind::Lifetime => {
359 let name = if param.name == "" {
360 hir::ParamName::Plain(keywords::StaticLifetime.ident())
362 hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
365 args.push(hir::GenericArg::Lifetime(hir::Lifetime {
366 id: ast::DUMMY_NODE_ID,
368 name: hir::LifetimeName::Param(name),
371 ty::GenericParamDefKind::Type {..} => {
372 args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
378 args: HirVec::from_vec(args),
379 bindings: HirVec::new(),
380 parenthesized: false,
384 fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
385 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
387 id: ast::DUMMY_NODE_ID,
388 node: hir::TyKind::Path(hir::QPath::Resolved(
392 def: Def::TyParam(param.def_id),
393 segments: HirVec::from_vec(vec![
394 hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
399 hir_id: hir::DUMMY_HIR_ID,
403 fn find_auto_trait_generics(
407 generics: &ty::Generics,
408 ) -> AutoTraitResult {
409 match self.f.find_auto_trait_generics(did, trait_did, generics,
411 let region_data = info.region_data;
415 .map(|name| (name.clone(), Lifetime(name)))
417 let lifetime_predicates =
418 self.handle_lifetimes(®ion_data, &names_map);
419 let new_generics = self.param_env_to_generics(
429 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): \
431 did, trait_did, generics, new_generics
436 auto::AutoTraitResult::ExplicitImpl => AutoTraitResult::ExplicitImpl,
437 auto::AutoTraitResult::NegativeImpl => AutoTraitResult::NegativeImpl,
438 auto::AutoTraitResult::PositiveImpl(res) => AutoTraitResult::PositiveImpl(res),
442 fn get_lifetime(&self, region: Region, names_map: &FxHashMap<String, Lifetime>) -> Lifetime {
443 self.region_name(region)
445 names_map.get(&name).unwrap_or_else(|| {
446 panic!("Missing lifetime with name {:?} for {:?}", name, region)
449 .unwrap_or(&Lifetime::statik())
453 fn region_name(&self, region: Region) -> Option<String> {
455 &ty::ReEarlyBound(r) => Some(r.name.to_string()),
460 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
461 // and region constraints of the form ReVar: 'a
463 // This is essentially a simplified version of lexical_region_resolve. However,
464 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
465 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
466 // with determining if a given set up constraints/predicates *are* met, given some
467 // starting conditions (e.g. user-provided code). For this reason, it's easier
468 // to perform the calculations we need on our own, rather than trying to make
469 // existing inference/solver code do what we want.
470 fn handle_lifetimes<'cx>(
472 regions: &RegionConstraintData<'cx>,
473 names_map: &FxHashMap<String, Lifetime>,
474 ) -> Vec<WherePredicate> {
475 // Our goal is to 'flatten' the list of constraints by eliminating
476 // all intermediate RegionVids. At the end, all constraints should
477 // be between Regions (aka region variables). This gives us the information
478 // we need to create the Generics.
479 let mut finished = FxHashMap();
481 let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = FxHashMap();
483 // Flattening is done in two parts. First, we insert all of the constraints
484 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
485 // to its smaller and larger regions. Note that 'larger' regions correspond
486 // to sub-regions in Rust code (e.g. in 'a: 'b, 'a is the larger region).
487 for constraint in regions.constraints.keys() {
489 &Constraint::VarSubVar(r1, r2) => {
492 .entry(RegionTarget::RegionVid(r1))
493 .or_insert_with(|| Default::default());
494 deps1.larger.insert(RegionTarget::RegionVid(r2));
498 .entry(RegionTarget::RegionVid(r2))
499 .or_insert_with(|| Default::default());
500 deps2.smaller.insert(RegionTarget::RegionVid(r1));
502 &Constraint::RegSubVar(region, vid) => {
504 .entry(RegionTarget::RegionVid(vid))
505 .or_insert_with(|| Default::default());
506 deps.smaller.insert(RegionTarget::Region(region));
508 &Constraint::VarSubReg(vid, region) => {
510 .entry(RegionTarget::RegionVid(vid))
511 .or_insert_with(|| Default::default());
512 deps.larger.insert(RegionTarget::Region(region));
514 &Constraint::RegSubReg(r1, r2) => {
515 // The constraint is already in the form that we want, so we're done with it
516 // Desired order is 'larger, smaller', so flip then
517 if self.region_name(r1) != self.region_name(r2) {
519 .entry(self.region_name(r2).unwrap())
520 .or_insert_with(|| Vec::new())
527 // Here, we 'flatten' the map one element at a time.
528 // All of the element's sub and super regions are connected
529 // to each other. For example, if we have a graph that looks like this:
531 // (A, B) - C - (D, E)
532 // Where (A, B) are subregions, and (D,E) are super-regions
534 // then after deleting 'C', the graph will look like this:
535 // ... - A - (D, E ...)
536 // ... - B - (D, E, ...)
537 // (A, B, ...) - D - ...
538 // (A, B, ...) - E - ...
540 // where '...' signifies the existing sub and super regions of an entry
541 // When two adjacent ty::Regions are encountered, we've computed a final
542 // constraint, and add it to our list. Since we make sure to never re-add
543 // deleted items, this process will always finish.
544 while !vid_map.is_empty() {
545 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
546 let deps = vid_map.remove(&target).expect("Entry somehow missing");
548 for smaller in deps.smaller.iter() {
549 for larger in deps.larger.iter() {
550 match (smaller, larger) {
551 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
552 if self.region_name(r1) != self.region_name(r2) {
554 .entry(self.region_name(r2).unwrap())
555 .or_insert_with(|| Vec::new())
556 .push(r1) // Larger, smaller
559 (&RegionTarget::RegionVid(_), &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);
566 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
567 if let Entry::Occupied(v) = vid_map.entry(*larger) {
568 let deps = v.into_mut();
569 deps.smaller.insert(*smaller);
570 deps.smaller.remove(&target);
573 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
574 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
575 let smaller_deps = v.into_mut();
576 smaller_deps.larger.insert(*larger);
577 smaller_deps.larger.remove(&target);
580 if let Entry::Occupied(v) = vid_map.entry(*larger) {
581 let larger_deps = v.into_mut();
582 larger_deps.smaller.insert(*smaller);
583 larger_deps.smaller.remove(&target);
591 let lifetime_predicates = names_map
593 .flat_map(|(name, lifetime)| {
594 let empty = Vec::new();
595 let bounds: FxHashSet<GenericBound> = finished.get(name).unwrap_or(&empty).iter()
596 .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
599 if bounds.is_empty() {
602 Some(WherePredicate::RegionPredicate {
603 lifetime: lifetime.clone(),
604 bounds: bounds.into_iter().collect(),
612 fn extract_for_generics<'b, 'c, 'd>(
614 tcx: TyCtxt<'b, 'c, 'd>,
615 pred: ty::Predicate<'d>,
616 ) -> FxHashSet<GenericParamDef> {
619 let mut regions = FxHashSet();
620 tcx.collect_regions(&t, &mut regions);
622 regions.into_iter().flat_map(|r| {
624 // We only care about late bound regions, as we need to add them
625 // to the 'for<>' section
626 &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
627 Some(GenericParamDef {
628 name: name.to_string(),
629 kind: GenericParamDefKind::Lifetime,
632 &ty::ReVar(_) | &ty::ReEarlyBound(_) => None,
633 _ => panic!("Unexpected region type {:?}", r),
640 fn make_final_bounds<'b, 'c, 'cx>(
642 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
643 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
644 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
645 ) -> Vec<WherePredicate> {
648 .flat_map(|(ty, mut bounds)| {
649 if let Some(data) = ty_to_fn.get(&ty) {
650 let (poly_trait, output) =
651 (data.0.as_ref().unwrap().clone(), data.1.as_ref().cloned());
652 let new_ty = match &poly_trait.trait_ {
653 &Type::ResolvedPath {
659 let mut new_path = path.clone();
660 let last_segment = new_path.segments.pop().unwrap();
662 let (old_input, old_output) = match last_segment.args {
663 GenericArgs::AngleBracketed { types, .. } => (types, None),
664 GenericArgs::Parenthesized { inputs, output, .. } => {
669 if old_output.is_some() && old_output != output {
671 "Output mismatch for {:?} {:?} {:?}",
672 ty, old_output, data.1
676 let new_params = GenericArgs::Parenthesized {
681 new_path.segments.push(PathSegment {
682 name: last_segment.name,
688 typarams: typarams.clone(),
690 is_generic: *is_generic,
693 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
695 bounds.insert(GenericBound::TraitBound(
698 generic_params: poly_trait.generic_params,
700 hir::TraitBoundModifier::None,
703 if bounds.is_empty() {
707 let mut bounds_vec = bounds.into_iter().collect();
708 self.sort_where_bounds(&mut bounds_vec);
710 Some(WherePredicate::BoundPredicate {
718 .filter(|&(_, ref bounds)| !bounds.is_empty())
719 .map(|(lifetime, bounds)| {
720 let mut bounds_vec = bounds.into_iter().collect();
721 self.sort_where_bounds(&mut bounds_vec);
722 WherePredicate::RegionPredicate {
731 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
732 // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
733 // so we fix them up:
735 // * Multiple bounds for the same type are coalesced into one: e.g. 'T: Copy', 'T: Debug'
736 // becomes 'T: Copy + Debug'
737 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
738 // K', we use the dedicated syntax 'T: Fn() -> K'
739 // * We explcitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
740 fn param_env_to_generics<'b, 'c, 'cx>(
742 tcx: TyCtxt<'b, 'c, 'cx>,
744 param_env: ty::ParamEnv<'cx>,
745 type_generics: ty::Generics,
746 mut existing_predicates: Vec<WherePredicate>,
747 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
750 "param_env_to_generics(did={:?}, param_env={:?}, type_generics={:?}, \
751 existing_predicates={:?})",
752 did, param_env, type_generics, existing_predicates
755 // The `Sized` trait must be handled specially, since we only only display it when
756 // it is *not* required (i.e. '?Sized')
757 let sized_trait = self.cx
759 .require_lang_item(lang_items::SizedTraitLangItem);
761 let mut replacer = RegionReplacer {
762 vid_to_region: &vid_to_region,
766 let orig_bounds: FxHashSet<_> = self.cx.tcx.param_env(did).caller_bounds.iter().collect();
767 let clean_where_predicates = param_env
771 !orig_bounds.contains(p) || match p {
772 &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
777 let replaced = p.fold_with(&mut replacer);
778 (replaced.clone(), replaced.clean(self.cx))
781 let full_generics = (&type_generics, &tcx.predicates_of(did));
783 params: mut generic_params,
785 } = full_generics.clean(self.cx);
787 let mut has_sized = FxHashSet();
788 let mut ty_to_bounds = FxHashMap();
789 let mut lifetime_to_bounds = FxHashMap();
790 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = FxHashMap();
792 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = FxHashMap();
794 for (orig_p, p) in clean_where_predicates {
796 WherePredicate::BoundPredicate { ty, mut bounds } => {
797 // Writing a projection trait bound of the form
798 // <T as Trait>::Name : ?Sized
799 // is illegal, because ?Sized bounds can only
800 // be written in the (here, nonexistant) definition
802 // Therefore, we make sure that we never add a ?Sized
803 // bound for projections
805 &Type::QPath { .. } => {
806 has_sized.insert(ty.clone());
811 if bounds.is_empty() {
815 let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
817 assert!(bounds.len() == 1);
818 let mut b = bounds.pop().unwrap();
820 if b.is_sized_bound(self.cx) {
821 has_sized.insert(ty.clone());
822 } else if !b.get_trait_type()
826 .map(|bounds| bounds.contains(&strip_type(t.clone())))
830 // If we've already added a projection bound for the same type, don't add
831 // this, as it would be a duplicate
833 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
834 // as we want to combine them with any 'Output' qpaths
837 let is_fn = match &mut b {
838 &mut GenericBound::TraitBound(ref mut p, _) => {
839 // Insert regions into the for_generics hash map first, to ensure
840 // that we don't end up with duplicate bounds (e.g. for<'b, 'b>)
841 for_generics.extend(p.generic_params.clone());
842 p.generic_params = for_generics.into_iter().collect();
843 self.is_fn_ty(&tcx, &p.trait_)
848 let poly_trait = b.get_poly_trait().unwrap();
853 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
854 .or_insert(((Some(poly_trait.clone())), None));
858 .or_insert_with(|| FxHashSet());
862 .or_insert_with(|| FxHashSet())
867 WherePredicate::RegionPredicate { lifetime, bounds } => {
870 .or_insert_with(|| FxHashSet())
873 WherePredicate::EqPredicate { lhs, rhs } => {
880 let ty = &*self_type;
883 path: ref trait_path,
888 let mut new_trait_path = trait_path.clone();
890 if self.is_fn_ty(&tcx, trait_) && left_name == FN_OUTPUT_NAME {
893 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
894 .or_insert((None, Some(rhs)));
898 // FIXME: Remove this scope when NLL lands
901 &mut new_trait_path.segments.last_mut().unwrap().args;
904 // Convert somethiung like '<T as Iterator::Item> = u8'
905 // to 'T: Iterator<Item=u8>'
906 &mut GenericArgs::AngleBracketed {
910 bindings.push(TypeBinding {
911 name: left_name.clone(),
915 &mut GenericArgs::Parenthesized { .. } => {
916 existing_predicates.push(
917 WherePredicate::EqPredicate {
922 continue; // If something other than a Fn ends up
923 // with parenthesis, leave it alone
928 let bounds = ty_to_bounds
930 .or_insert_with(|| FxHashSet());
932 bounds.insert(GenericBound::TraitBound(
934 trait_: Type::ResolvedPath {
935 path: new_trait_path,
936 typarams: typarams.clone(),
938 is_generic: *is_generic,
940 generic_params: Vec::new(),
942 hir::TraitBoundModifier::None,
945 // Remove any existing 'plain' bound (e.g. 'T: Iterator`) so
946 // that we don't see a
947 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
949 bounds.remove(&GenericBound::TraitBound(
951 trait_: *trait_.clone(),
952 generic_params: Vec::new(),
954 hir::TraitBoundModifier::None,
956 // Avoid creating any new duplicate bounds later in the outer
960 .or_insert_with(|| FxHashSet())
961 .insert(*trait_.clone());
963 _ => panic!("Unexpected trait {:?} for {:?}", trait_, did),
966 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, did),
972 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
974 existing_predicates.extend(final_bounds);
976 for param in generic_params.iter_mut() {
978 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
979 // We never want something like `impl<T=Foo>`.
981 let generic_ty = Type::Generic(param.name.clone());
982 if !has_sized.contains(&generic_ty) {
983 bounds.insert(0, GenericBound::maybe_sized(self.cx));
986 GenericParamDefKind::Lifetime => {}
990 self.sort_where_predicates(&mut existing_predicates);
993 params: generic_params,
994 where_predicates: existing_predicates,
998 // Ensure that the predicates are in a consistent order. The precise
999 // ordering doesn't actually matter, but it's important that
1000 // a given set of predicates always appears in the same order -
1001 // both for visual consistency between 'rustdoc' runs, and to
1002 // make writing tests much easier
1004 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
1005 // We should never have identical bounds - and if we do,
1006 // they're visually identical as well. Therefore, using
1007 // an unstable sort is fine.
1008 self.unstable_debug_sort(&mut predicates);
1011 // Ensure that the bounds are in a consistent order. The precise
1012 // ordering doesn't actually matter, but it's important that
1013 // a given set of bounds always appears in the same order -
1014 // both for visual consistency between 'rustdoc' runs, and to
1015 // make writing tests much easier
1017 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
1018 // We should never have identical bounds - and if we do,
1019 // they're visually identical as well. Therefore, using
1020 // an unstable sort is fine.
1021 self.unstable_debug_sort(&mut bounds);
1024 // This might look horrendously hacky, but it's actually not that bad.
1026 // For performance reasons, we use several different FxHashMaps
1027 // in the process of computing the final set of where predicates.
1028 // However, the iteration order of a HashMap is completely unspecified.
1029 // In fact, the iteration of an FxHashMap can even vary between platforms,
1030 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
1032 // Obviously, it's extremely undesireable for documentation rendering
1033 // to be depndent on the platform it's run on. Apart from being confusing
1034 // to end users, it makes writing tests much more difficult, as predicates
1035 // can appear in any order in the final result.
1037 // To solve this problem, we sort WherePredicates and GenericBounds
1038 // by their Debug string. The thing to keep in mind is that we don't really
1039 // care what the final order is - we're synthesizing an impl or bound
1040 // ourselves, so any order can be considered equally valid. By sorting the
1041 // predicates and bounds, however, we ensure that for a given codebase, all
1042 // auto-trait impls always render in exactly the same way.
1044 // Using the Debug impementation for sorting prevents us from needing to
1045 // write quite a bit of almost entirely useless code (e.g. how should two
1046 // Types be sorted relative to each other). It also allows us to solve the
1047 // problem for both WherePredicates and GenericBounds at the same time. This
1048 // approach is probably somewhat slower, but the small number of items
1049 // involved (impls rarely have more than a few bounds) means that it
1050 // shouldn't matter in practice.
1051 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
1052 vec.sort_by_cached_key(|x| format!("{:?}", x))
1055 fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {
1057 &&Type::ResolvedPath { ref did, .. } => {
1058 *did == tcx.require_lang_item(lang_items::FnTraitLangItem)
1059 || *did == tcx.require_lang_item(lang_items::FnMutTraitLangItem)
1060 || *did == tcx.require_lang_item(lang_items::FnOnceTraitLangItem)
1066 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
1067 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
1068 // registered after the AST is constructed would require storing the defid mapping in a
1069 // RefCell, decreasing the performance for normal compilation for very little gain.
1071 // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
1072 // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
1073 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
1074 fn next_def_id(&self, crate_num: CrateNum) -> DefId {
1075 let start_def_id = {
1076 let next_id = if crate_num == LOCAL_CRATE {
1082 .next_id(DefIndexAddressSpace::Low)
1086 .def_path_table(crate_num)
1087 .next_id(DefIndexAddressSpace::Low)
1096 let mut fake_ids = self.cx.fake_def_ids.borrow_mut();
1098 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
1103 index: DefIndex::from_array_index(
1104 def_id.index.as_array_index() + 1,
1105 def_id.index.address_space(),
1110 MAX_DEF_ID.with(|m| {
1112 .entry(def_id.krate.clone())
1113 .or_insert(start_def_id);
1116 self.cx.all_fake_def_ids.borrow_mut().insert(def_id);
1122 // Replaces all ReVars in a type with ty::Region's, using the provided map
1123 struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
1124 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
1125 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1128 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
1129 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
1133 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1135 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
1137 }).unwrap_or_else(|| r.super_fold_with(self))