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::{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 pub fn get_auto_trait_impls<F>(
89 where F: Fn(DefId) -> Def {
97 "get_auto_trait_impls(def_id={:?}, def_ctor=...): item has doc('hidden'), \
104 let tcx = self.cx.tcx;
105 let generics = self.cx.tcx.generics_of(def_id);
107 let ty = self.cx.tcx.type_of(def_id);
108 let mut traits = FxHashMap();
109 if self.cx.crate_name != Some("core".to_string()) {
110 if let ty::TyAdt(_adt, _) = ty.sty {
111 let param_env = self.cx.tcx.param_env(def_id);
112 for &trait_def_id in self.cx.all_traits.iter() {
113 if traits.get(&trait_def_id).is_some() ||
114 !self.cx.access_levels.borrow().is_doc_reachable(trait_def_id) {
117 let t_name = self.cx.tcx.item_name(trait_def_id).to_string();
118 self.cx.tcx.for_each_relevant_impl(trait_def_id, ty, |impl_def_id| {
119 self.cx.tcx.infer_ctxt().enter(|infcx| {
120 let generics = infcx.tcx.generics_of(impl_def_id);
121 let trait_ref = infcx.tcx.impl_trait_ref(impl_def_id).unwrap();
123 if !match infcx.tcx.type_of(impl_def_id).sty {
124 ::rustc::ty::TypeVariants::TyParam(_) => true,
130 let substs = infcx.fresh_substs_for_item(DUMMY_SP, def_id);
131 let ty2 = ty.subst(infcx.tcx, substs);
132 let param_env = param_env.subst(infcx.tcx, substs);
134 let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
135 let trait_ref = trait_ref.subst(infcx.tcx, impl_substs);
137 // Require the type the impl is implemented on to match
138 // our type, and ignore the impl if there was a mismatch.
139 let cause = traits::ObligationCause::dummy();
140 let eq_result = infcx.at(&cause, param_env).eq(trait_ref.self_ty(), ty2);
141 if let Ok(InferOk { value: (), obligations }) = eq_result {
142 // FIXME(eddyb) ignoring `obligations` might cause false positives.
145 let may_apply = infcx.predicate_may_hold(&traits::Obligation::new(
148 trait_ref.to_predicate(),
151 if traits.get(&trait_def_id).is_none() {
152 let trait_ = hir::TraitRef {
153 path: get_path_for_type(infcx.tcx, trait_def_id, hir::def::Def::Trait),
154 ref_id: ast::DUMMY_NODE_ID,
156 let provided_trait_methods = infcx.tcx.provided_trait_methods(impl_def_id)
158 .map(|meth| meth.ident.to_string())
160 traits.insert(trait_def_id, Item {
161 source: Span::empty(),
163 attrs: Default::default(),
165 def_id: self.next_def_id(impl_def_id.krate),
168 inner: ImplItem(Impl {
169 unsafety: hir::Unsafety::Normal,
171 &tcx.predicates_of(impl_def_id)).clean(self.cx),
172 provided_trait_methods,
173 trait_: Some(trait_.clean(self.cx)),
174 for_: ty.clean(self.cx),
175 items: infcx.tcx.associated_items(impl_def_id).collect::<Vec<_>>().clean(self.cx),
182 debug!("{:?} => {}", trait_ref, may_apply);
191 "get_auto_trait_impls(def_id={:?}, def_ctor=..., generics={:?}",
194 let auto_traits: Vec<_> =
196 .and_then(|send_trait| {
197 self.get_auto_trait_impl_for(
205 .chain(self.get_auto_trait_impl_for(
210 tcx.require_lang_item(lang_items::SyncTraitLangItem),
212 .chain(traits.into_iter().map(|(_, v)| v))
216 "get_auto_traits: type {:?} auto_traits {:?}",
222 fn get_auto_trait_impl_for<F>(
225 name: Option<String>,
226 generics: ty::Generics,
230 where F: Fn(DefId) -> Def {
232 .generated_synthetics
234 .insert((def_id, trait_def_id))
237 "get_auto_trait_impl_for(def_id={:?}, generics={:?}, def_ctor=..., \
238 trait_def_id={:?}): already generated, aborting",
239 def_id, generics, trait_def_id
244 let result = self.find_auto_trait_generics(def_id, trait_def_id, &generics);
246 if result.is_auto() {
247 let trait_ = hir::TraitRef {
248 path: get_path_for_type(self.cx.tcx, trait_def_id, hir::def::Def::Trait),
249 ref_id: ast::DUMMY_NODE_ID,
254 let new_generics = match result {
255 AutoTraitResult::PositiveImpl(new_generics) => {
259 AutoTraitResult::NegativeImpl => {
260 polarity = Some(ImplPolarity::Negative);
262 // For negative impls, we use the generic params, but *not* the predicates,
263 // from the original type. Otherwise, the displayed impl appears to be a
264 // conditional negative impl, when it's really unconditional.
266 // For example, consider the struct Foo<T: Copy>(*mut T). Using
267 // the original predicates in our impl would cause us to generate
268 // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
269 // implements Send where T is not copy.
271 // Instead, we generate `impl !Send for Foo<T>`, which better
272 // expresses the fact that `Foo<T>` never implements `Send`,
273 // regardless of the choice of `T`.
274 let real_generics = (&generics, &Default::default());
276 // Clean the generics, but ignore the '?Sized' bounds generated
277 // by the `Clean` impl
278 let clean_generics = real_generics.clean(self.cx);
281 params: clean_generics.params,
282 where_predicates: Vec::new(),
288 let path = get_path_for_type(self.cx.tcx, def_id, def_ctor);
289 let mut segments = path.segments.into_vec();
290 let last = segments.pop().unwrap();
292 let real_name = name.map(|name| Ident::from_str(&name));
294 segments.push(hir::PathSegment::new(
295 real_name.unwrap_or(last.ident),
296 self.generics_to_path_params(generics.clone()),
300 let new_path = hir::Path {
303 segments: HirVec::from_vec(segments),
307 id: ast::DUMMY_NODE_ID,
308 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
310 hir_id: hir::DUMMY_HIR_ID,
314 source: Span::empty(),
316 attrs: Default::default(),
318 def_id: self.next_def_id(def_id.krate),
321 inner: ImplItem(Impl {
322 unsafety: hir::Unsafety::Normal,
323 generics: new_generics,
324 provided_trait_methods: FxHashSet(),
325 trait_: Some(trait_.clean(self.cx)),
326 for_: ty.clean(self.cx),
336 fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
337 let mut args = vec![];
339 for param in generics.params.iter() {
341 ty::GenericParamDefKind::Lifetime => {
342 let name = if param.name == "" {
343 hir::ParamName::Plain(keywords::StaticLifetime.ident())
345 hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
348 args.push(hir::GenericArg::Lifetime(hir::Lifetime {
349 id: ast::DUMMY_NODE_ID,
351 name: hir::LifetimeName::Param(name),
354 ty::GenericParamDefKind::Type {..} => {
355 args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
361 args: HirVec::from_vec(args),
362 bindings: HirVec::new(),
363 parenthesized: false,
367 fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
368 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
370 id: ast::DUMMY_NODE_ID,
371 node: hir::TyKind::Path(hir::QPath::Resolved(
375 def: Def::TyParam(param.def_id),
376 segments: HirVec::from_vec(vec![
377 hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
382 hir_id: hir::DUMMY_HIR_ID,
386 fn find_auto_trait_generics(
390 generics: &ty::Generics,
391 ) -> AutoTraitResult {
392 match self.f.find_auto_trait_generics(did, trait_did, generics,
394 let region_data = info.region_data;
398 .map(|name| (name.clone(), Lifetime(name)))
400 let lifetime_predicates =
401 self.handle_lifetimes(®ion_data, &names_map);
402 let new_generics = self.param_env_to_generics(
412 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): \
414 did, trait_did, generics, new_generics
419 auto::AutoTraitResult::ExplicitImpl => AutoTraitResult::ExplicitImpl,
420 auto::AutoTraitResult::NegativeImpl => AutoTraitResult::NegativeImpl,
421 auto::AutoTraitResult::PositiveImpl(res) => AutoTraitResult::PositiveImpl(res),
425 fn get_lifetime(&self, region: Region, names_map: &FxHashMap<String, Lifetime>) -> Lifetime {
426 self.region_name(region)
428 names_map.get(&name).unwrap_or_else(|| {
429 panic!("Missing lifetime with name {:?} for {:?}", name, region)
432 .unwrap_or(&Lifetime::statik())
436 fn region_name(&self, region: Region) -> Option<String> {
438 &ty::ReEarlyBound(r) => Some(r.name.to_string()),
443 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
444 // and region constraints of the form ReVar: 'a
446 // This is essentially a simplified version of lexical_region_resolve. However,
447 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
448 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
449 // with determining if a given set up constraints/predicates *are* met, given some
450 // starting conditions (e.g. user-provided code). For this reason, it's easier
451 // to perform the calculations we need on our own, rather than trying to make
452 // existing inference/solver code do what we want.
453 fn handle_lifetimes<'cx>(
455 regions: &RegionConstraintData<'cx>,
456 names_map: &FxHashMap<String, Lifetime>,
457 ) -> Vec<WherePredicate> {
458 // Our goal is to 'flatten' the list of constraints by eliminating
459 // all intermediate RegionVids. At the end, all constraints should
460 // be between Regions (aka region variables). This gives us the information
461 // we need to create the Generics.
462 let mut finished = FxHashMap();
464 let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = FxHashMap();
466 // Flattening is done in two parts. First, we insert all of the constraints
467 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
468 // to its smaller and larger regions. Note that 'larger' regions correspond
469 // to sub-regions in Rust code (e.g. in 'a: 'b, 'a is the larger region).
470 for constraint in regions.constraints.keys() {
472 &Constraint::VarSubVar(r1, r2) => {
475 .entry(RegionTarget::RegionVid(r1))
476 .or_insert_with(|| Default::default());
477 deps1.larger.insert(RegionTarget::RegionVid(r2));
481 .entry(RegionTarget::RegionVid(r2))
482 .or_insert_with(|| Default::default());
483 deps2.smaller.insert(RegionTarget::RegionVid(r1));
485 &Constraint::RegSubVar(region, vid) => {
487 .entry(RegionTarget::RegionVid(vid))
488 .or_insert_with(|| Default::default());
489 deps.smaller.insert(RegionTarget::Region(region));
491 &Constraint::VarSubReg(vid, region) => {
493 .entry(RegionTarget::RegionVid(vid))
494 .or_insert_with(|| Default::default());
495 deps.larger.insert(RegionTarget::Region(region));
497 &Constraint::RegSubReg(r1, r2) => {
498 // The constraint is already in the form that we want, so we're done with it
499 // Desired order is 'larger, smaller', so flip then
500 if self.region_name(r1) != self.region_name(r2) {
502 .entry(self.region_name(r2).unwrap())
503 .or_insert_with(|| Vec::new())
510 // Here, we 'flatten' the map one element at a time.
511 // All of the element's sub and super regions are connected
512 // to each other. For example, if we have a graph that looks like this:
514 // (A, B) - C - (D, E)
515 // Where (A, B) are subregions, and (D,E) are super-regions
517 // then after deleting 'C', the graph will look like this:
518 // ... - A - (D, E ...)
519 // ... - B - (D, E, ...)
520 // (A, B, ...) - D - ...
521 // (A, B, ...) - E - ...
523 // where '...' signifies the existing sub and super regions of an entry
524 // When two adjacent ty::Regions are encountered, we've computed a final
525 // constraint, and add it to our list. Since we make sure to never re-add
526 // deleted items, this process will always finish.
527 while !vid_map.is_empty() {
528 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
529 let deps = vid_map.remove(&target).expect("Entry somehow missing");
531 for smaller in deps.smaller.iter() {
532 for larger in deps.larger.iter() {
533 match (smaller, larger) {
534 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
535 if self.region_name(r1) != self.region_name(r2) {
537 .entry(self.region_name(r2).unwrap())
538 .or_insert_with(|| Vec::new())
539 .push(r1) // Larger, smaller
542 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
543 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
544 let smaller_deps = v.into_mut();
545 smaller_deps.larger.insert(*larger);
546 smaller_deps.larger.remove(&target);
549 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
550 if let Entry::Occupied(v) = vid_map.entry(*larger) {
551 let deps = v.into_mut();
552 deps.smaller.insert(*smaller);
553 deps.smaller.remove(&target);
556 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
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);
574 let lifetime_predicates = names_map
576 .flat_map(|(name, lifetime)| {
577 let empty = Vec::new();
578 let bounds: FxHashSet<GenericBound> = finished.get(name).unwrap_or(&empty).iter()
579 .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
582 if bounds.is_empty() {
585 Some(WherePredicate::RegionPredicate {
586 lifetime: lifetime.clone(),
587 bounds: bounds.into_iter().collect(),
595 fn extract_for_generics<'b, 'c, 'd>(
597 tcx: TyCtxt<'b, 'c, 'd>,
598 pred: ty::Predicate<'d>,
599 ) -> FxHashSet<GenericParamDef> {
602 let mut regions = FxHashSet();
603 tcx.collect_regions(&t, &mut regions);
605 regions.into_iter().flat_map(|r| {
607 // We only care about late bound regions, as we need to add them
608 // to the 'for<>' section
609 &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
610 Some(GenericParamDef {
611 name: name.to_string(),
612 kind: GenericParamDefKind::Lifetime,
615 &ty::ReVar(_) | &ty::ReEarlyBound(_) => None,
616 _ => panic!("Unexpected region type {:?}", r),
623 fn make_final_bounds<'b, 'c, 'cx>(
625 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
626 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
627 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
628 ) -> Vec<WherePredicate> {
631 .flat_map(|(ty, mut bounds)| {
632 if let Some(data) = ty_to_fn.get(&ty) {
633 let (poly_trait, output) =
634 (data.0.as_ref().unwrap().clone(), data.1.as_ref().cloned());
635 let new_ty = match &poly_trait.trait_ {
636 &Type::ResolvedPath {
642 let mut new_path = path.clone();
643 let last_segment = new_path.segments.pop().unwrap();
645 let (old_input, old_output) = match last_segment.args {
646 GenericArgs::AngleBracketed { types, .. } => (types, None),
647 GenericArgs::Parenthesized { inputs, output, .. } => {
652 if old_output.is_some() && old_output != output {
654 "Output mismatch for {:?} {:?} {:?}",
655 ty, old_output, data.1
659 let new_params = GenericArgs::Parenthesized {
664 new_path.segments.push(PathSegment {
665 name: last_segment.name,
671 typarams: typarams.clone(),
673 is_generic: *is_generic,
676 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
678 bounds.insert(GenericBound::TraitBound(
681 generic_params: poly_trait.generic_params,
683 hir::TraitBoundModifier::None,
686 if bounds.is_empty() {
690 let mut bounds_vec = bounds.into_iter().collect();
691 self.sort_where_bounds(&mut bounds_vec);
693 Some(WherePredicate::BoundPredicate {
701 .filter(|&(_, ref bounds)| !bounds.is_empty())
702 .map(|(lifetime, bounds)| {
703 let mut bounds_vec = bounds.into_iter().collect();
704 self.sort_where_bounds(&mut bounds_vec);
705 WherePredicate::RegionPredicate {
714 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
715 // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
716 // so we fix them up:
718 // * Multiple bounds for the same type are coalesced into one: e.g. 'T: Copy', 'T: Debug'
719 // becomes 'T: Copy + Debug'
720 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
721 // K', we use the dedicated syntax 'T: Fn() -> K'
722 // * We explcitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
723 fn param_env_to_generics<'b, 'c, 'cx>(
725 tcx: TyCtxt<'b, 'c, 'cx>,
727 param_env: ty::ParamEnv<'cx>,
728 type_generics: ty::Generics,
729 mut existing_predicates: Vec<WherePredicate>,
730 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
733 "param_env_to_generics(did={:?}, param_env={:?}, type_generics={:?}, \
734 existing_predicates={:?})",
735 did, param_env, type_generics, existing_predicates
738 // The `Sized` trait must be handled specially, since we only only display it when
739 // it is *not* required (i.e. '?Sized')
740 let sized_trait = self.cx
742 .require_lang_item(lang_items::SizedTraitLangItem);
744 let mut replacer = RegionReplacer {
745 vid_to_region: &vid_to_region,
749 let orig_bounds: FxHashSet<_> = self.cx.tcx.param_env(did).caller_bounds.iter().collect();
750 let clean_where_predicates = param_env
754 !orig_bounds.contains(p) || match p {
755 &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
760 let replaced = p.fold_with(&mut replacer);
761 (replaced.clone(), replaced.clean(self.cx))
764 let full_generics = (&type_generics, &tcx.predicates_of(did));
766 params: mut generic_params,
768 } = full_generics.clean(self.cx);
770 let mut has_sized = FxHashSet();
771 let mut ty_to_bounds = FxHashMap();
772 let mut lifetime_to_bounds = FxHashMap();
773 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = FxHashMap();
775 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = FxHashMap();
777 for (orig_p, p) in clean_where_predicates {
779 WherePredicate::BoundPredicate { ty, mut bounds } => {
780 // Writing a projection trait bound of the form
781 // <T as Trait>::Name : ?Sized
782 // is illegal, because ?Sized bounds can only
783 // be written in the (here, nonexistant) definition
785 // Therefore, we make sure that we never add a ?Sized
786 // bound for projections
788 &Type::QPath { .. } => {
789 has_sized.insert(ty.clone());
794 if bounds.is_empty() {
798 let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
800 assert!(bounds.len() == 1);
801 let mut b = bounds.pop().unwrap();
803 if b.is_sized_bound(self.cx) {
804 has_sized.insert(ty.clone());
805 } else if !b.get_trait_type()
809 .map(|bounds| bounds.contains(&strip_type(t.clone())))
813 // If we've already added a projection bound for the same type, don't add
814 // this, as it would be a duplicate
816 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
817 // as we want to combine them with any 'Output' qpaths
820 let is_fn = match &mut b {
821 &mut GenericBound::TraitBound(ref mut p, _) => {
822 // Insert regions into the for_generics hash map first, to ensure
823 // that we don't end up with duplicate bounds (e.g. for<'b, 'b>)
824 for_generics.extend(p.generic_params.clone());
825 p.generic_params = for_generics.into_iter().collect();
826 self.is_fn_ty(&tcx, &p.trait_)
831 let poly_trait = b.get_poly_trait().unwrap();
836 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
837 .or_insert(((Some(poly_trait.clone())), None));
841 .or_insert_with(|| FxHashSet());
845 .or_insert_with(|| FxHashSet())
850 WherePredicate::RegionPredicate { lifetime, bounds } => {
853 .or_insert_with(|| FxHashSet())
856 WherePredicate::EqPredicate { lhs, rhs } => {
863 let ty = &*self_type;
866 path: ref trait_path,
871 let mut new_trait_path = trait_path.clone();
873 if self.is_fn_ty(&tcx, trait_) && left_name == FN_OUTPUT_NAME {
876 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
877 .or_insert((None, Some(rhs)));
881 // FIXME: Remove this scope when NLL lands
884 &mut new_trait_path.segments.last_mut().unwrap().args;
887 // Convert somethiung like '<T as Iterator::Item> = u8'
888 // to 'T: Iterator<Item=u8>'
889 &mut GenericArgs::AngleBracketed {
893 bindings.push(TypeBinding {
894 name: left_name.clone(),
898 &mut GenericArgs::Parenthesized { .. } => {
899 existing_predicates.push(
900 WherePredicate::EqPredicate {
905 continue; // If something other than a Fn ends up
906 // with parenthesis, leave it alone
911 let bounds = ty_to_bounds
913 .or_insert_with(|| FxHashSet());
915 bounds.insert(GenericBound::TraitBound(
917 trait_: Type::ResolvedPath {
918 path: new_trait_path,
919 typarams: typarams.clone(),
921 is_generic: *is_generic,
923 generic_params: Vec::new(),
925 hir::TraitBoundModifier::None,
928 // Remove any existing 'plain' bound (e.g. 'T: Iterator`) so
929 // that we don't see a
930 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
932 bounds.remove(&GenericBound::TraitBound(
934 trait_: *trait_.clone(),
935 generic_params: Vec::new(),
937 hir::TraitBoundModifier::None,
939 // Avoid creating any new duplicate bounds later in the outer
943 .or_insert_with(|| FxHashSet())
944 .insert(*trait_.clone());
946 _ => panic!("Unexpected trait {:?} for {:?}", trait_, did),
949 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, did),
955 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
957 existing_predicates.extend(final_bounds);
959 for param in generic_params.iter_mut() {
961 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
962 // We never want something like `impl<T=Foo>`.
964 let generic_ty = Type::Generic(param.name.clone());
965 if !has_sized.contains(&generic_ty) {
966 bounds.insert(0, GenericBound::maybe_sized(self.cx));
969 GenericParamDefKind::Lifetime => {}
973 self.sort_where_predicates(&mut existing_predicates);
976 params: generic_params,
977 where_predicates: existing_predicates,
981 // Ensure that the predicates are in a consistent order. The precise
982 // ordering doesn't actually matter, but it's important that
983 // a given set of predicates always appears in the same order -
984 // both for visual consistency between 'rustdoc' runs, and to
985 // make writing tests much easier
987 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
988 // We should never have identical bounds - and if we do,
989 // they're visually identical as well. Therefore, using
990 // an unstable sort is fine.
991 self.unstable_debug_sort(&mut predicates);
994 // Ensure that the bounds are in a consistent order. The precise
995 // ordering doesn't actually matter, but it's important that
996 // a given set of bounds always appears in the same order -
997 // both for visual consistency between 'rustdoc' runs, and to
998 // make writing tests much easier
1000 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
1001 // We should never have identical bounds - and if we do,
1002 // they're visually identical as well. Therefore, using
1003 // an unstable sort is fine.
1004 self.unstable_debug_sort(&mut bounds);
1007 // This might look horrendously hacky, but it's actually not that bad.
1009 // For performance reasons, we use several different FxHashMaps
1010 // in the process of computing the final set of where predicates.
1011 // However, the iteration order of a HashMap is completely unspecified.
1012 // In fact, the iteration of an FxHashMap can even vary between platforms,
1013 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
1015 // Obviously, it's extremely undesireable for documentation rendering
1016 // to be depndent on the platform it's run on. Apart from being confusing
1017 // to end users, it makes writing tests much more difficult, as predicates
1018 // can appear in any order in the final result.
1020 // To solve this problem, we sort WherePredicates and GenericBounds
1021 // by their Debug string. The thing to keep in mind is that we don't really
1022 // care what the final order is - we're synthesizing an impl or bound
1023 // ourselves, so any order can be considered equally valid. By sorting the
1024 // predicates and bounds, however, we ensure that for a given codebase, all
1025 // auto-trait impls always render in exactly the same way.
1027 // Using the Debug impementation for sorting prevents us from needing to
1028 // write quite a bit of almost entirely useless code (e.g. how should two
1029 // Types be sorted relative to each other). It also allows us to solve the
1030 // problem for both WherePredicates and GenericBounds at the same time. This
1031 // approach is probably somewhat slower, but the small number of items
1032 // involved (impls rarely have more than a few bounds) means that it
1033 // shouldn't matter in practice.
1034 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
1035 vec.sort_by_cached_key(|x| format!("{:?}", x))
1038 fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {
1040 &&Type::ResolvedPath { ref did, .. } => {
1041 *did == tcx.require_lang_item(lang_items::FnTraitLangItem)
1042 || *did == tcx.require_lang_item(lang_items::FnMutTraitLangItem)
1043 || *did == tcx.require_lang_item(lang_items::FnOnceTraitLangItem)
1049 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
1050 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
1051 // registered after the AST is constructed would require storing the defid mapping in a
1052 // RefCell, decreasing the performance for normal compilation for very little gain.
1054 // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
1055 // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
1056 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
1057 fn next_def_id(&self, crate_num: CrateNum) -> DefId {
1058 let start_def_id = {
1059 let next_id = if crate_num == LOCAL_CRATE {
1065 .next_id(DefIndexAddressSpace::Low)
1069 .def_path_table(crate_num)
1070 .next_id(DefIndexAddressSpace::Low)
1079 let mut fake_ids = self.cx.fake_def_ids.borrow_mut();
1081 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
1086 index: DefIndex::from_array_index(
1087 def_id.index.as_array_index() + 1,
1088 def_id.index.address_space(),
1093 MAX_DEF_ID.with(|m| {
1095 .entry(def_id.krate.clone())
1096 .or_insert(start_def_id);
1099 self.cx.all_fake_def_ids.borrow_mut().insert(def_id);
1105 // Replaces all ReVars in a type with ty::Region's, using the provided map
1106 struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
1107 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
1108 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1111 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
1112 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
1116 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1118 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
1120 }).unwrap_or_else(|| r.super_fold_with(self))