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,
86 real_name: &Option<Ident>,
87 generics: &ty::Generics,
89 where F: Fn(DefId) -> Def {
90 let path = get_path_for_type(self.cx.tcx, def_id, def_ctor);
91 let mut segments = path.segments.into_vec();
92 let last = segments.pop().unwrap();
94 segments.push(hir::PathSegment::new(
95 real_name.unwrap_or(last.ident),
96 self.generics_to_path_params(generics.clone()),
100 let new_path = hir::Path {
103 segments: HirVec::from_vec(segments),
107 id: ast::DUMMY_NODE_ID,
108 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
110 hir_id: hir::DUMMY_HIR_ID,
114 pub fn get_blanket_impls<F>(
118 name: Option<String>,
119 generics: &ty::Generics,
121 where F: Fn(DefId) -> Def {
122 let ty = self.cx.tcx.type_of(def_id);
123 let mut traits = Vec::new();
124 if self.cx.access_levels.borrow().is_doc_reachable(def_id) {
125 let real_name = name.clone().map(|name| Ident::from_str(&name));
126 let param_env = self.cx.tcx.param_env(def_id);
127 for &trait_def_id in self.cx.all_traits.iter() {
128 if !self.cx.access_levels.borrow().is_doc_reachable(trait_def_id) ||
129 self.cx.generated_synthetics
131 .get(&(def_id, trait_def_id))
135 self.cx.tcx.for_each_relevant_impl(trait_def_id, ty, |impl_def_id| {
136 self.cx.tcx.infer_ctxt().enter(|infcx| {
137 let t_generics = infcx.tcx.generics_of(impl_def_id);
138 let trait_ref = infcx.tcx.impl_trait_ref(impl_def_id).unwrap();
140 match infcx.tcx.type_of(impl_def_id).sty {
141 ::rustc::ty::TypeVariants::TyParam(_) => {},
145 let substs = infcx.fresh_substs_for_item(DUMMY_SP, def_id);
146 let ty = ty.subst(infcx.tcx, substs);
147 let param_env = param_env.subst(infcx.tcx, substs);
149 let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
150 let trait_ref = trait_ref.subst(infcx.tcx, impl_substs);
152 // Require the type the impl is implemented on to match
153 // our type, and ignore the impl if there was a mismatch.
154 let cause = traits::ObligationCause::dummy();
155 let eq_result = infcx.at(&cause, param_env)
156 .eq(trait_ref.self_ty(), ty);
157 if let Ok(InferOk { value: (), obligations }) = eq_result {
158 // FIXME(eddyb) ignoring `obligations` might cause false positives.
161 let may_apply = infcx.predicate_may_hold(&traits::Obligation::new(
164 trait_ref.to_predicate(),
169 self.cx.generated_synthetics.borrow_mut()
170 .insert((def_id, trait_def_id));
171 let trait_ = hir::TraitRef {
172 path: get_path_for_type(infcx.tcx,
174 hir::def::Def::Trait),
175 ref_id: ast::DUMMY_NODE_ID,
177 let provided_trait_methods =
178 infcx.tcx.provided_trait_methods(trait_def_id)
180 .map(|meth| meth.ident.to_string())
183 let ty = self.get_real_ty(def_id, def_ctor, &real_name, generics);
184 let predicates = infcx.tcx.predicates_of(impl_def_id);
187 source: infcx.tcx.def_span(impl_def_id).clean(self.cx),
189 attrs: Default::default(),
191 def_id: self.next_def_id(impl_def_id.krate),
194 inner: ImplItem(Impl {
195 unsafety: hir::Unsafety::Normal,
196 generics: (t_generics, &predicates).clean(self.cx),
197 provided_trait_methods,
198 trait_: Some(trait_.clean(self.cx)),
199 for_: ty.clean(self.cx),
200 items: infcx.tcx.associated_items(impl_def_id)
205 blanket_impl: Some(infcx.tcx.type_of(impl_def_id)
209 debug!("{:?} => {}", trait_ref, may_apply);
218 pub fn get_auto_trait_impls<F>(
222 name: Option<String>,
224 where F: Fn(DefId) -> Def {
232 "get_auto_trait_impls(def_id={:?}, def_ctor=...): item has doc('hidden'), \
239 let tcx = self.cx.tcx;
240 let generics = self.cx.tcx.generics_of(def_id);
243 "get_auto_trait_impls(def_id={:?}, def_ctor=..., generics={:?}",
246 let auto_traits: Vec<_> = self.cx
248 .and_then(|send_trait| {
249 self.get_auto_trait_impl_for(
258 .chain(self.get_auto_trait_impl_for(
263 tcx.require_lang_item(lang_items::SyncTraitLangItem),
265 .chain(self.get_blanket_impls(def_id, def_ctor, name, &generics).into_iter())
269 "get_auto_traits: type {:?} auto_traits {:?}",
275 fn get_auto_trait_impl_for<F>(
278 name: Option<String>,
279 generics: ty::Generics,
283 where F: Fn(DefId) -> Def {
285 .generated_synthetics
287 .insert((def_id, trait_def_id))
290 "get_auto_trait_impl_for(def_id={:?}, generics={:?}, def_ctor=..., \
291 trait_def_id={:?}): already generated, aborting",
292 def_id, generics, trait_def_id
297 let result = self.find_auto_trait_generics(def_id, trait_def_id, &generics);
299 if result.is_auto() {
300 let trait_ = hir::TraitRef {
301 path: get_path_for_type(self.cx.tcx, trait_def_id, hir::def::Def::Trait),
302 ref_id: ast::DUMMY_NODE_ID,
307 let new_generics = match result {
308 AutoTraitResult::PositiveImpl(new_generics) => {
312 AutoTraitResult::NegativeImpl => {
313 polarity = Some(ImplPolarity::Negative);
315 // For negative impls, we use the generic params, but *not* the predicates,
316 // from the original type. Otherwise, the displayed impl appears to be a
317 // conditional negative impl, when it's really unconditional.
319 // For example, consider the struct Foo<T: Copy>(*mut T). Using
320 // the original predicates in our impl would cause us to generate
321 // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
322 // implements Send where T is not copy.
324 // Instead, we generate `impl !Send for Foo<T>`, which better
325 // expresses the fact that `Foo<T>` never implements `Send`,
326 // regardless of the choice of `T`.
327 let real_generics = (&generics, &Default::default());
329 // Clean the generics, but ignore the '?Sized' bounds generated
330 // by the `Clean` impl
331 let clean_generics = real_generics.clean(self.cx);
334 params: clean_generics.params,
335 where_predicates: Vec::new(),
340 let real_name = name.map(|name| Ident::from_str(&name));
341 let ty = self.get_real_ty(def_id, def_ctor, &real_name, &generics);
344 source: Span::empty(),
346 attrs: Default::default(),
348 def_id: self.next_def_id(def_id.krate),
351 inner: ImplItem(Impl {
352 unsafety: hir::Unsafety::Normal,
353 generics: new_generics,
354 provided_trait_methods: FxHashSet(),
355 trait_: Some(trait_.clean(self.cx)),
356 for_: ty.clean(self.cx),
367 fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
368 let mut args = vec![];
370 for param in generics.params.iter() {
372 ty::GenericParamDefKind::Lifetime => {
373 let name = if param.name == "" {
374 hir::ParamName::Plain(keywords::StaticLifetime.ident())
376 hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
379 args.push(hir::GenericArg::Lifetime(hir::Lifetime {
380 id: ast::DUMMY_NODE_ID,
382 name: hir::LifetimeName::Param(name),
385 ty::GenericParamDefKind::Type {..} => {
386 args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
392 args: HirVec::from_vec(args),
393 bindings: HirVec::new(),
394 parenthesized: false,
398 fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
399 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
401 id: ast::DUMMY_NODE_ID,
402 node: hir::TyKind::Path(hir::QPath::Resolved(
406 def: Def::TyParam(param.def_id),
407 segments: HirVec::from_vec(vec![
408 hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
413 hir_id: hir::DUMMY_HIR_ID,
417 fn find_auto_trait_generics(
421 generics: &ty::Generics,
422 ) -> AutoTraitResult {
423 match self.f.find_auto_trait_generics(did, trait_did, generics,
425 let region_data = info.region_data;
429 .map(|name| (name.clone(), Lifetime(name)))
431 let lifetime_predicates =
432 self.handle_lifetimes(®ion_data, &names_map);
433 let new_generics = self.param_env_to_generics(
443 "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): \
445 did, trait_did, generics, new_generics
450 auto::AutoTraitResult::ExplicitImpl => AutoTraitResult::ExplicitImpl,
451 auto::AutoTraitResult::NegativeImpl => AutoTraitResult::NegativeImpl,
452 auto::AutoTraitResult::PositiveImpl(res) => AutoTraitResult::PositiveImpl(res),
456 fn get_lifetime(&self, region: Region, names_map: &FxHashMap<String, Lifetime>) -> Lifetime {
457 self.region_name(region)
459 names_map.get(&name).unwrap_or_else(|| {
460 panic!("Missing lifetime with name {:?} for {:?}", name, region)
463 .unwrap_or(&Lifetime::statik())
467 fn region_name(&self, region: Region) -> Option<String> {
469 &ty::ReEarlyBound(r) => Some(r.name.to_string()),
474 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
475 // and region constraints of the form ReVar: 'a
477 // This is essentially a simplified version of lexical_region_resolve. However,
478 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
479 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
480 // with determining if a given set up constraints/predicates *are* met, given some
481 // starting conditions (e.g. user-provided code). For this reason, it's easier
482 // to perform the calculations we need on our own, rather than trying to make
483 // existing inference/solver code do what we want.
484 fn handle_lifetimes<'cx>(
486 regions: &RegionConstraintData<'cx>,
487 names_map: &FxHashMap<String, Lifetime>,
488 ) -> Vec<WherePredicate> {
489 // Our goal is to 'flatten' the list of constraints by eliminating
490 // all intermediate RegionVids. At the end, all constraints should
491 // be between Regions (aka region variables). This gives us the information
492 // we need to create the Generics.
493 let mut finished = FxHashMap();
495 let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = FxHashMap();
497 // Flattening is done in two parts. First, we insert all of the constraints
498 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
499 // to its smaller and larger regions. Note that 'larger' regions correspond
500 // to sub-regions in Rust code (e.g. in 'a: 'b, 'a is the larger region).
501 for constraint in regions.constraints.keys() {
503 &Constraint::VarSubVar(r1, r2) => {
506 .entry(RegionTarget::RegionVid(r1))
507 .or_insert_with(|| Default::default());
508 deps1.larger.insert(RegionTarget::RegionVid(r2));
512 .entry(RegionTarget::RegionVid(r2))
513 .or_insert_with(|| Default::default());
514 deps2.smaller.insert(RegionTarget::RegionVid(r1));
516 &Constraint::RegSubVar(region, vid) => {
518 .entry(RegionTarget::RegionVid(vid))
519 .or_insert_with(|| Default::default());
520 deps.smaller.insert(RegionTarget::Region(region));
522 &Constraint::VarSubReg(vid, region) => {
524 .entry(RegionTarget::RegionVid(vid))
525 .or_insert_with(|| Default::default());
526 deps.larger.insert(RegionTarget::Region(region));
528 &Constraint::RegSubReg(r1, r2) => {
529 // The constraint is already in the form that we want, so we're done with it
530 // Desired order is 'larger, smaller', so flip then
531 if self.region_name(r1) != self.region_name(r2) {
533 .entry(self.region_name(r2).unwrap())
534 .or_insert_with(|| Vec::new())
541 // Here, we 'flatten' the map one element at a time.
542 // All of the element's sub and super regions are connected
543 // to each other. For example, if we have a graph that looks like this:
545 // (A, B) - C - (D, E)
546 // Where (A, B) are subregions, and (D,E) are super-regions
548 // then after deleting 'C', the graph will look like this:
549 // ... - A - (D, E ...)
550 // ... - B - (D, E, ...)
551 // (A, B, ...) - D - ...
552 // (A, B, ...) - E - ...
554 // where '...' signifies the existing sub and super regions of an entry
555 // When two adjacent ty::Regions are encountered, we've computed a final
556 // constraint, and add it to our list. Since we make sure to never re-add
557 // deleted items, this process will always finish.
558 while !vid_map.is_empty() {
559 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
560 let deps = vid_map.remove(&target).expect("Entry somehow missing");
562 for smaller in deps.smaller.iter() {
563 for larger in deps.larger.iter() {
564 match (smaller, larger) {
565 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
566 if self.region_name(r1) != self.region_name(r2) {
568 .entry(self.region_name(r2).unwrap())
569 .or_insert_with(|| Vec::new())
570 .push(r1) // Larger, smaller
573 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
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 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
581 if let Entry::Occupied(v) = vid_map.entry(*larger) {
582 let deps = v.into_mut();
583 deps.smaller.insert(*smaller);
584 deps.smaller.remove(&target);
587 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
588 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
589 let smaller_deps = v.into_mut();
590 smaller_deps.larger.insert(*larger);
591 smaller_deps.larger.remove(&target);
594 if let Entry::Occupied(v) = vid_map.entry(*larger) {
595 let larger_deps = v.into_mut();
596 larger_deps.smaller.insert(*smaller);
597 larger_deps.smaller.remove(&target);
605 let lifetime_predicates = names_map
607 .flat_map(|(name, lifetime)| {
608 let empty = Vec::new();
609 let bounds: FxHashSet<GenericBound> = finished.get(name).unwrap_or(&empty).iter()
610 .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
613 if bounds.is_empty() {
616 Some(WherePredicate::RegionPredicate {
617 lifetime: lifetime.clone(),
618 bounds: bounds.into_iter().collect(),
626 fn extract_for_generics<'b, 'c, 'd>(
628 tcx: TyCtxt<'b, 'c, 'd>,
629 pred: ty::Predicate<'d>,
630 ) -> FxHashSet<GenericParamDef> {
633 let mut regions = FxHashSet();
634 tcx.collect_regions(&t, &mut regions);
636 regions.into_iter().flat_map(|r| {
638 // We only care about late bound regions, as we need to add them
639 // to the 'for<>' section
640 &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
641 Some(GenericParamDef {
642 name: name.to_string(),
643 kind: GenericParamDefKind::Lifetime,
646 &ty::ReVar(_) | &ty::ReEarlyBound(_) | &ty::ReStatic => None,
647 _ => panic!("Unexpected region type {:?}", r),
654 fn make_final_bounds<'b, 'c, 'cx>(
656 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
657 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
658 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
659 ) -> Vec<WherePredicate> {
662 .flat_map(|(ty, mut bounds)| {
663 if let Some(data) = ty_to_fn.get(&ty) {
664 let (poly_trait, output) =
665 (data.0.as_ref().unwrap().clone(), data.1.as_ref().cloned());
666 let new_ty = match &poly_trait.trait_ {
667 &Type::ResolvedPath {
673 let mut new_path = path.clone();
674 let last_segment = new_path.segments.pop().unwrap();
676 let (old_input, old_output) = match last_segment.args {
677 GenericArgs::AngleBracketed { types, .. } => (types, None),
678 GenericArgs::Parenthesized { inputs, output, .. } => {
683 if old_output.is_some() && old_output != output {
685 "Output mismatch for {:?} {:?} {:?}",
686 ty, old_output, data.1
690 let new_params = GenericArgs::Parenthesized {
695 new_path.segments.push(PathSegment {
696 name: last_segment.name,
702 typarams: typarams.clone(),
704 is_generic: *is_generic,
707 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
709 bounds.insert(GenericBound::TraitBound(
712 generic_params: poly_trait.generic_params,
714 hir::TraitBoundModifier::None,
717 if bounds.is_empty() {
721 let mut bounds_vec = bounds.into_iter().collect();
722 self.sort_where_bounds(&mut bounds_vec);
724 Some(WherePredicate::BoundPredicate {
732 .filter(|&(_, ref bounds)| !bounds.is_empty())
733 .map(|(lifetime, bounds)| {
734 let mut bounds_vec = bounds.into_iter().collect();
735 self.sort_where_bounds(&mut bounds_vec);
736 WherePredicate::RegionPredicate {
745 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
746 // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
747 // so we fix them up:
749 // * Multiple bounds for the same type are coalesced into one: e.g. 'T: Copy', 'T: Debug'
750 // becomes 'T: Copy + Debug'
751 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
752 // K', we use the dedicated syntax 'T: Fn() -> K'
753 // * We explcitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
754 fn param_env_to_generics<'b, 'c, 'cx>(
756 tcx: TyCtxt<'b, 'c, 'cx>,
758 param_env: ty::ParamEnv<'cx>,
759 type_generics: ty::Generics,
760 mut existing_predicates: Vec<WherePredicate>,
761 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
764 "param_env_to_generics(did={:?}, param_env={:?}, type_generics={:?}, \
765 existing_predicates={:?})",
766 did, param_env, type_generics, existing_predicates
769 // The `Sized` trait must be handled specially, since we only only display it when
770 // it is *not* required (i.e. '?Sized')
771 let sized_trait = self.cx
773 .require_lang_item(lang_items::SizedTraitLangItem);
775 let mut replacer = RegionReplacer {
776 vid_to_region: &vid_to_region,
780 let orig_bounds: FxHashSet<_> = self.cx.tcx.param_env(did).caller_bounds.iter().collect();
781 let clean_where_predicates = param_env
785 !orig_bounds.contains(p) || match p {
786 &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
791 let replaced = p.fold_with(&mut replacer);
792 (replaced.clone(), replaced.clean(self.cx))
795 let full_generics = (&type_generics, &tcx.predicates_of(did));
797 params: mut generic_params,
799 } = full_generics.clean(self.cx);
801 let mut has_sized = FxHashSet();
802 let mut ty_to_bounds = FxHashMap();
803 let mut lifetime_to_bounds = FxHashMap();
804 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = FxHashMap();
806 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = FxHashMap();
808 for (orig_p, p) in clean_where_predicates {
810 WherePredicate::BoundPredicate { ty, mut bounds } => {
811 // Writing a projection trait bound of the form
812 // <T as Trait>::Name : ?Sized
813 // is illegal, because ?Sized bounds can only
814 // be written in the (here, nonexistant) definition
816 // Therefore, we make sure that we never add a ?Sized
817 // bound for projections
819 &Type::QPath { .. } => {
820 has_sized.insert(ty.clone());
825 if bounds.is_empty() {
829 let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
831 assert!(bounds.len() == 1);
832 let mut b = bounds.pop().unwrap();
834 if b.is_sized_bound(self.cx) {
835 has_sized.insert(ty.clone());
836 } else if !b.get_trait_type()
840 .map(|bounds| bounds.contains(&strip_type(t.clone())))
844 // If we've already added a projection bound for the same type, don't add
845 // this, as it would be a duplicate
847 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
848 // as we want to combine them with any 'Output' qpaths
851 let is_fn = match &mut b {
852 &mut GenericBound::TraitBound(ref mut p, _) => {
853 // Insert regions into the for_generics hash map first, to ensure
854 // that we don't end up with duplicate bounds (e.g. for<'b, 'b>)
855 for_generics.extend(p.generic_params.clone());
856 p.generic_params = for_generics.into_iter().collect();
857 self.is_fn_ty(&tcx, &p.trait_)
862 let poly_trait = b.get_poly_trait().unwrap();
867 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
868 .or_insert(((Some(poly_trait.clone())), None));
872 .or_insert_with(|| FxHashSet());
876 .or_insert_with(|| FxHashSet())
881 WherePredicate::RegionPredicate { lifetime, bounds } => {
884 .or_insert_with(|| FxHashSet())
887 WherePredicate::EqPredicate { lhs, rhs } => {
894 let ty = &*self_type;
897 path: ref trait_path,
902 let mut new_trait_path = trait_path.clone();
904 if self.is_fn_ty(&tcx, trait_) && left_name == FN_OUTPUT_NAME {
907 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
908 .or_insert((None, Some(rhs)));
912 // FIXME: Remove this scope when NLL lands
915 &mut new_trait_path.segments.last_mut().unwrap().args;
918 // Convert somethiung like '<T as Iterator::Item> = u8'
919 // to 'T: Iterator<Item=u8>'
920 &mut GenericArgs::AngleBracketed {
924 bindings.push(TypeBinding {
925 name: left_name.clone(),
929 &mut GenericArgs::Parenthesized { .. } => {
930 existing_predicates.push(
931 WherePredicate::EqPredicate {
936 continue; // If something other than a Fn ends up
937 // with parenthesis, leave it alone
942 let bounds = ty_to_bounds
944 .or_insert_with(|| FxHashSet());
946 bounds.insert(GenericBound::TraitBound(
948 trait_: Type::ResolvedPath {
949 path: new_trait_path,
950 typarams: typarams.clone(),
952 is_generic: *is_generic,
954 generic_params: Vec::new(),
956 hir::TraitBoundModifier::None,
959 // Remove any existing 'plain' bound (e.g. 'T: Iterator`) so
960 // that we don't see a
961 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
963 bounds.remove(&GenericBound::TraitBound(
965 trait_: *trait_.clone(),
966 generic_params: Vec::new(),
968 hir::TraitBoundModifier::None,
970 // Avoid creating any new duplicate bounds later in the outer
974 .or_insert_with(|| FxHashSet())
975 .insert(*trait_.clone());
977 _ => panic!("Unexpected trait {:?} for {:?}", trait_, did),
980 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, did),
986 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
988 existing_predicates.extend(final_bounds);
990 for param in generic_params.iter_mut() {
992 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
993 // We never want something like `impl<T=Foo>`.
995 let generic_ty = Type::Generic(param.name.clone());
996 if !has_sized.contains(&generic_ty) {
997 bounds.insert(0, GenericBound::maybe_sized(self.cx));
1000 GenericParamDefKind::Lifetime => {}
1004 self.sort_where_predicates(&mut existing_predicates);
1007 params: generic_params,
1008 where_predicates: existing_predicates,
1012 // Ensure that the predicates are in a consistent order. The precise
1013 // ordering doesn't actually matter, but it's important that
1014 // a given set of predicates always appears in the same order -
1015 // both for visual consistency between 'rustdoc' runs, and to
1016 // make writing tests much easier
1018 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
1019 // We should never have identical bounds - and if we do,
1020 // they're visually identical as well. Therefore, using
1021 // an unstable sort is fine.
1022 self.unstable_debug_sort(&mut predicates);
1025 // Ensure that the bounds are in a consistent order. The precise
1026 // ordering doesn't actually matter, but it's important that
1027 // a given set of bounds always appears in the same order -
1028 // both for visual consistency between 'rustdoc' runs, and to
1029 // make writing tests much easier
1031 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
1032 // We should never have identical bounds - and if we do,
1033 // they're visually identical as well. Therefore, using
1034 // an unstable sort is fine.
1035 self.unstable_debug_sort(&mut bounds);
1038 // This might look horrendously hacky, but it's actually not that bad.
1040 // For performance reasons, we use several different FxHashMaps
1041 // in the process of computing the final set of where predicates.
1042 // However, the iteration order of a HashMap is completely unspecified.
1043 // In fact, the iteration of an FxHashMap can even vary between platforms,
1044 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
1046 // Obviously, it's extremely undesireable for documentation rendering
1047 // to be depndent on the platform it's run on. Apart from being confusing
1048 // to end users, it makes writing tests much more difficult, as predicates
1049 // can appear in any order in the final result.
1051 // To solve this problem, we sort WherePredicates and GenericBounds
1052 // by their Debug string. The thing to keep in mind is that we don't really
1053 // care what the final order is - we're synthesizing an impl or bound
1054 // ourselves, so any order can be considered equally valid. By sorting the
1055 // predicates and bounds, however, we ensure that for a given codebase, all
1056 // auto-trait impls always render in exactly the same way.
1058 // Using the Debug impementation for sorting prevents us from needing to
1059 // write quite a bit of almost entirely useless code (e.g. how should two
1060 // Types be sorted relative to each other). It also allows us to solve the
1061 // problem for both WherePredicates and GenericBounds at the same time. This
1062 // approach is probably somewhat slower, but the small number of items
1063 // involved (impls rarely have more than a few bounds) means that it
1064 // shouldn't matter in practice.
1065 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
1066 vec.sort_by_cached_key(|x| format!("{:?}", x))
1069 fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {
1071 &&Type::ResolvedPath { ref did, .. } => {
1072 *did == tcx.require_lang_item(lang_items::FnTraitLangItem)
1073 || *did == tcx.require_lang_item(lang_items::FnMutTraitLangItem)
1074 || *did == tcx.require_lang_item(lang_items::FnOnceTraitLangItem)
1080 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
1081 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
1082 // registered after the AST is constructed would require storing the defid mapping in a
1083 // RefCell, decreasing the performance for normal compilation for very little gain.
1085 // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
1086 // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
1087 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
1088 fn next_def_id(&self, crate_num: CrateNum) -> DefId {
1089 let start_def_id = {
1090 let next_id = if crate_num == LOCAL_CRATE {
1096 .next_id(DefIndexAddressSpace::Low)
1100 .def_path_table(crate_num)
1101 .next_id(DefIndexAddressSpace::Low)
1110 let mut fake_ids = self.cx.fake_def_ids.borrow_mut();
1112 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
1117 index: DefIndex::from_array_index(
1118 def_id.index.as_array_index() + 1,
1119 def_id.index.address_space(),
1124 MAX_DEF_ID.with(|m| {
1126 .entry(def_id.krate.clone())
1127 .or_insert(start_def_id);
1130 self.cx.all_fake_def_ids.borrow_mut().insert(def_id);
1136 // Replaces all ReVars in a type with ty::Region's, using the provided map
1137 struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
1138 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
1139 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1142 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
1143 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
1147 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1149 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
1151 }).unwrap_or_else(|| r.super_fold_with(self))