]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/auto_trait.rs
ea25ac5c6826314174337677061a9e44f4fa6d81
[rust.git] / src / librustdoc / clean / auto_trait.rs
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.
4 //
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.
10
11 use rustc::hir;
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;
16 use std::fmt::Debug;
17 use syntax_pos::DUMMY_SP;
18
19 use core::DocAccessLevels;
20
21 use super::*;
22
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>,
26 }
27
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);
31
32         AutoTraitFinder { cx, f }
33     }
34
35     pub fn get_with_def_id(&self, def_id: DefId) -> Vec<Item> {
36         let ty = self.cx.tcx.type_of(def_id);
37
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,
43             }
44             ty::TyInt(_) |
45             ty::TyUint(_) |
46             ty::TyFloat(_) |
47             ty::TyStr |
48             ty::TyBool |
49             ty::TyChar => return self.get_auto_trait_impls(def_id, &move |_: DefId| {
50                 match ty.sty {
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),
57                     _ => unreachable!(),
58                 }
59             }, None),
60             _ => {
61                 debug!("Unexpected type {:?}", def_id);
62                 return Vec::new()
63             }
64         };
65
66         self.get_auto_trait_impls(def_id, &def_ctor, None)
67     }
68
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);
72
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),
78         };
79
80         self.get_auto_trait_impls(did, &def_ctor, Some(name))
81     }
82
83     pub fn get_auto_trait_impls<F>(
84         &self,
85         def_id: DefId,
86         def_ctor: &F,
87         name: Option<String>,
88     ) -> Vec<Item>
89     where F: Fn(DefId) -> Def {
90         if self.cx
91             .tcx
92             .get_attrs(def_id)
93             .lists("doc")
94             .has_word("hidden")
95         {
96             debug!(
97                 "get_auto_trait_impls(def_id={:?}, def_ctor=...): item has doc('hidden'), \
98                  aborting",
99                 def_id
100             );
101             return Vec::new();
102         }
103
104         let tcx = self.cx.tcx;
105         let generics = self.cx.tcx.generics_of(def_id);
106
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) {
115                         continue
116                     }
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();
122
123                             if !match infcx.tcx.type_of(impl_def_id).sty {
124                                 ::rustc::ty::TypeVariants::TyParam(_) => true,
125                                 _ => false,
126                             } {
127                                 return;
128                             }
129
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);
133
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);
136
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.
143                                 drop(obligations);
144
145                                 let may_apply = infcx.predicate_may_hold(&traits::Obligation::new(
146                                     cause.clone(),
147                                     param_env,
148                                     trait_ref.to_predicate(),
149                                 ));
150                                 if may_apply {
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,
155                                         };
156                                         let provided_trait_methods = infcx.tcx.provided_trait_methods(impl_def_id)
157                                                                               .into_iter()
158                                                                               .map(|meth| meth.ident.to_string())
159                                                                               .collect();
160                                         traits.insert(trait_def_id, Item {
161                                             source: Span::empty(),
162                                             name: None,
163                                             attrs: Default::default(),
164                                             visibility: None,
165                                             def_id: self.next_def_id(impl_def_id.krate),
166                                             stability: None,
167                                             deprecation: None,
168                                             inner: ImplItem(Impl {
169                                                 unsafety: hir::Unsafety::Normal,
170                                                 generics: (generics,
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),
176                                                 polarity: None,
177                                                 synthetic: true,
178                                             }),
179                                         });
180                                     }
181                                 }
182                                 debug!("{:?} => {}", trait_ref, may_apply);
183                             }
184                         });
185                     });
186                 }
187             }
188         }
189
190         debug!(
191             "get_auto_trait_impls(def_id={:?}, def_ctor=..., generics={:?}",
192             def_id, generics
193         );
194         let auto_traits: Vec<_> =
195             self.cx.send_trait
196                           .and_then(|send_trait| {
197                     self.get_auto_trait_impl_for(
198                         def_id,
199                         name.clone(),
200                         generics.clone(),
201                         def_ctor,
202                         send_trait,
203                     )
204                 }).into_iter()
205             .chain(self.get_auto_trait_impl_for(
206                 def_id,
207                 name.clone(),
208                 generics.clone(),
209                 def_ctor,
210                 tcx.require_lang_item(lang_items::SyncTraitLangItem),
211             ).into_iter())
212             .chain(traits.into_iter().map(|(_, v)| v))
213             .collect();
214
215         debug!(
216             "get_auto_traits: type {:?} auto_traits {:?}",
217             def_id, auto_traits
218         );
219         auto_traits
220     }
221
222     fn get_auto_trait_impl_for<F>(
223         &self,
224         def_id: DefId,
225         name: Option<String>,
226         generics: ty::Generics,
227         def_ctor: &F,
228         trait_def_id: DefId,
229     ) -> Option<Item>
230     where F: Fn(DefId) -> Def {
231         if !self.cx
232             .generated_synthetics
233             .borrow_mut()
234             .insert((def_id, trait_def_id))
235         {
236             debug!(
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
240             );
241             return None;
242         }
243
244         let result = self.find_auto_trait_generics(def_id, trait_def_id, &generics);
245
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,
250             };
251
252             let polarity;
253
254             let new_generics = match result {
255                 AutoTraitResult::PositiveImpl(new_generics) => {
256                     polarity = None;
257                     new_generics
258                 }
259                 AutoTraitResult::NegativeImpl => {
260                     polarity = Some(ImplPolarity::Negative);
261
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.
265                     //
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.
270                     //
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());
275
276                     // Clean the generics, but ignore the '?Sized' bounds generated
277                     // by the `Clean` impl
278                     let clean_generics = real_generics.clean(self.cx);
279
280                     Generics {
281                         params: clean_generics.params,
282                         where_predicates: Vec::new(),
283                     }
284                 }
285                 _ => unreachable!(),
286             };
287
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();
291
292             let real_name = name.map(|name| Ident::from_str(&name));
293
294             segments.push(hir::PathSegment::new(
295                 real_name.unwrap_or(last.ident),
296                 self.generics_to_path_params(generics.clone()),
297                 false,
298             ));
299
300             let new_path = hir::Path {
301                 span: path.span,
302                 def: path.def,
303                 segments: HirVec::from_vec(segments),
304             };
305
306             let ty = hir::Ty {
307                 id: ast::DUMMY_NODE_ID,
308                 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
309                 span: DUMMY_SP,
310                 hir_id: hir::DUMMY_HIR_ID,
311             };
312
313             return Some(Item {
314                 source: Span::empty(),
315                 name: None,
316                 attrs: Default::default(),
317                 visibility: None,
318                 def_id: self.next_def_id(def_id.krate),
319                 stability: None,
320                 deprecation: None,
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),
327                     items: Vec::new(),
328                     polarity,
329                     synthetic: true,
330                 }),
331             });
332         }
333         None
334     }
335
336     fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
337         let mut args = vec![];
338
339         for param in generics.params.iter() {
340             match param.kind {
341                 ty::GenericParamDefKind::Lifetime => {
342                     let name = if param.name == "" {
343                         hir::ParamName::Plain(keywords::StaticLifetime.ident())
344                     } else {
345                         hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
346                     };
347
348                     args.push(hir::GenericArg::Lifetime(hir::Lifetime {
349                         id: ast::DUMMY_NODE_ID,
350                         span: DUMMY_SP,
351                         name: hir::LifetimeName::Param(name),
352                     }));
353                 }
354                 ty::GenericParamDefKind::Type {..} => {
355                     args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
356                 }
357             }
358         }
359
360         hir::GenericArgs {
361             args: HirVec::from_vec(args),
362             bindings: HirVec::new(),
363             parenthesized: false,
364         }
365     }
366
367     fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
368         debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
369         hir::Ty {
370             id: ast::DUMMY_NODE_ID,
371             node: hir::TyKind::Path(hir::QPath::Resolved(
372                 None,
373                 P(hir::Path {
374                     span: DUMMY_SP,
375                     def: Def::TyParam(param.def_id),
376                     segments: HirVec::from_vec(vec![
377                         hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
378                     ]),
379                 }),
380             )),
381             span: DUMMY_SP,
382             hir_id: hir::DUMMY_HIR_ID,
383         }
384     }
385
386     fn find_auto_trait_generics(
387         &self,
388         did: DefId,
389         trait_did: DefId,
390         generics: &ty::Generics,
391     ) -> AutoTraitResult {
392         match self.f.find_auto_trait_generics(did, trait_did, generics,
393                 |infcx, mut info| {
394                     let region_data = info.region_data;
395                     let names_map =
396                         info.names_map
397                             .drain()
398                             .map(|name| (name.clone(), Lifetime(name)))
399                             .collect();
400                     let lifetime_predicates =
401                         self.handle_lifetimes(&region_data, &names_map);
402                     let new_generics = self.param_env_to_generics(
403                         infcx.tcx,
404                         did,
405                         info.full_user_env,
406                         generics.clone(),
407                         lifetime_predicates,
408                         info.vid_to_region,
409                     );
410
411                     debug!(
412                         "find_auto_trait_generics(did={:?}, trait_did={:?}, generics={:?}): \
413                          finished with {:?}",
414                         did, trait_did, generics, new_generics
415                     );
416
417                     new_generics
418                 }) {
419             auto::AutoTraitResult::ExplicitImpl => AutoTraitResult::ExplicitImpl,
420             auto::AutoTraitResult::NegativeImpl => AutoTraitResult::NegativeImpl,
421             auto::AutoTraitResult::PositiveImpl(res) => AutoTraitResult::PositiveImpl(res),
422         }
423     }
424
425     fn get_lifetime(&self, region: Region, names_map: &FxHashMap<String, Lifetime>) -> Lifetime {
426         self.region_name(region)
427             .map(|name| {
428                 names_map.get(&name).unwrap_or_else(|| {
429                     panic!("Missing lifetime with name {:?} for {:?}", name, region)
430                 })
431             })
432             .unwrap_or(&Lifetime::statik())
433             .clone()
434     }
435
436     fn region_name(&self, region: Region) -> Option<String> {
437         match region {
438             &ty::ReEarlyBound(r) => Some(r.name.to_string()),
439             _ => None,
440         }
441     }
442
443     // This method calculates two things: Lifetime constraints of the form 'a: 'b,
444     // and region constraints of the form ReVar: 'a
445     //
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>(
454         &self,
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();
463
464         let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = FxHashMap();
465
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() {
471             match constraint {
472                 &Constraint::VarSubVar(r1, r2) => {
473                     {
474                         let deps1 = vid_map
475                             .entry(RegionTarget::RegionVid(r1))
476                             .or_insert_with(|| Default::default());
477                         deps1.larger.insert(RegionTarget::RegionVid(r2));
478                     }
479
480                     let deps2 = vid_map
481                         .entry(RegionTarget::RegionVid(r2))
482                         .or_insert_with(|| Default::default());
483                     deps2.smaller.insert(RegionTarget::RegionVid(r1));
484                 }
485                 &Constraint::RegSubVar(region, vid) => {
486                     let deps = vid_map
487                         .entry(RegionTarget::RegionVid(vid))
488                         .or_insert_with(|| Default::default());
489                     deps.smaller.insert(RegionTarget::Region(region));
490                 }
491                 &Constraint::VarSubReg(vid, region) => {
492                     let deps = vid_map
493                         .entry(RegionTarget::RegionVid(vid))
494                         .or_insert_with(|| Default::default());
495                     deps.larger.insert(RegionTarget::Region(region));
496                 }
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) {
501                         finished
502                             .entry(self.region_name(r2).unwrap())
503                             .or_insert_with(|| Vec::new())
504                             .push(r1);
505                     }
506                 }
507             }
508         }
509
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:
513         //
514         // (A, B) - C - (D, E)
515         // Where (A, B) are subregions, and (D,E) are super-regions
516         //
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 - ...
522         //
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");
530
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) {
536                                 finished
537                                     .entry(self.region_name(r2).unwrap())
538                                     .or_insert_with(|| Vec::new())
539                                     .push(r1) // Larger, smaller
540                             }
541                         }
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);
547                             }
548                         }
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);
554                             }
555                         }
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);
561                             }
562
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);
567                             }
568                         }
569                     }
570                 }
571             }
572         }
573
574         let lifetime_predicates = names_map
575             .iter()
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)))
580                     .collect();
581
582                 if bounds.is_empty() {
583                     return None;
584                 }
585                 Some(WherePredicate::RegionPredicate {
586                     lifetime: lifetime.clone(),
587                     bounds: bounds.into_iter().collect(),
588                 })
589             })
590             .collect();
591
592         lifetime_predicates
593     }
594
595     fn extract_for_generics<'b, 'c, 'd>(
596         &self,
597         tcx: TyCtxt<'b, 'c, 'd>,
598         pred: ty::Predicate<'d>,
599     ) -> FxHashSet<GenericParamDef> {
600         pred.walk_tys()
601             .flat_map(|t| {
602                 let mut regions = FxHashSet();
603                 tcx.collect_regions(&t, &mut regions);
604
605                 regions.into_iter().flat_map(|r| {
606                     match 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,
613                             })
614                         }
615                         &ty::ReVar(_) | &ty::ReEarlyBound(_) => None,
616                         _ => panic!("Unexpected region type {:?}", r),
617                     }
618                 })
619             })
620             .collect()
621     }
622
623     fn make_final_bounds<'b, 'c, 'cx>(
624         &self,
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> {
629         ty_to_bounds
630             .into_iter()
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 {
637                             ref path,
638                             ref typarams,
639                             ref did,
640                             ref is_generic,
641                         } => {
642                             let mut new_path = path.clone();
643                             let last_segment = new_path.segments.pop().unwrap();
644
645                             let (old_input, old_output) = match last_segment.args {
646                                 GenericArgs::AngleBracketed { types, .. } => (types, None),
647                                 GenericArgs::Parenthesized { inputs, output, .. } => {
648                                     (inputs, output)
649                                 }
650                             };
651
652                             if old_output.is_some() && old_output != output {
653                                 panic!(
654                                     "Output mismatch for {:?} {:?} {:?}",
655                                     ty, old_output, data.1
656                                 );
657                             }
658
659                             let new_params = GenericArgs::Parenthesized {
660                                 inputs: old_input,
661                                 output,
662                             };
663
664                             new_path.segments.push(PathSegment {
665                                 name: last_segment.name,
666                                 args: new_params,
667                             });
668
669                             Type::ResolvedPath {
670                                 path: new_path,
671                                 typarams: typarams.clone(),
672                                 did: did.clone(),
673                                 is_generic: *is_generic,
674                             }
675                         }
676                         _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
677                     };
678                     bounds.insert(GenericBound::TraitBound(
679                         PolyTrait {
680                             trait_: new_ty,
681                             generic_params: poly_trait.generic_params,
682                         },
683                         hir::TraitBoundModifier::None,
684                     ));
685                 }
686                 if bounds.is_empty() {
687                     return None;
688                 }
689
690                 let mut bounds_vec = bounds.into_iter().collect();
691                 self.sort_where_bounds(&mut bounds_vec);
692
693                 Some(WherePredicate::BoundPredicate {
694                     ty,
695                     bounds: bounds_vec,
696                 })
697             })
698             .chain(
699                 lifetime_to_bounds
700                     .into_iter()
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 {
706                             lifetime,
707                             bounds: bounds_vec,
708                         }
709                     }),
710             )
711             .collect()
712     }
713
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:
717     //
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>(
724         &self,
725         tcx: TyCtxt<'b, 'c, 'cx>,
726         did: DefId,
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>>,
731     ) -> Generics {
732         debug!(
733             "param_env_to_generics(did={:?}, param_env={:?}, type_generics={:?}, \
734              existing_predicates={:?})",
735             did, param_env, type_generics, existing_predicates
736         );
737
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
741             .tcx
742             .require_lang_item(lang_items::SizedTraitLangItem);
743
744         let mut replacer = RegionReplacer {
745             vid_to_region: &vid_to_region,
746             tcx,
747         };
748
749         let orig_bounds: FxHashSet<_> = self.cx.tcx.param_env(did).caller_bounds.iter().collect();
750         let clean_where_predicates = param_env
751             .caller_bounds
752             .iter()
753             .filter(|p| {
754                 !orig_bounds.contains(p) || match p {
755                     &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
756                     _ => false,
757                 }
758             })
759             .map(|p| {
760                 let replaced = p.fold_with(&mut replacer);
761                 (replaced.clone(), replaced.clean(self.cx))
762             });
763
764         let full_generics = (&type_generics, &tcx.predicates_of(did));
765         let Generics {
766             params: mut generic_params,
767             ..
768         } = full_generics.clean(self.cx);
769
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();
774
775         let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = FxHashMap();
776
777         for (orig_p, p) in clean_where_predicates {
778             match p {
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
784                     // of the type.
785                     // Therefore, we make sure that we never add a ?Sized
786                     // bound for projections
787                     match &ty {
788                         &Type::QPath { .. } => {
789                             has_sized.insert(ty.clone());
790                         }
791                         _ => {}
792                     }
793
794                     if bounds.is_empty() {
795                         continue;
796                     }
797
798                     let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
799
800                     assert!(bounds.len() == 1);
801                     let mut b = bounds.pop().unwrap();
802
803                     if b.is_sized_bound(self.cx) {
804                         has_sized.insert(ty.clone());
805                     } else if !b.get_trait_type()
806                         .and_then(|t| {
807                             ty_to_traits
808                                 .get(&ty)
809                                 .map(|bounds| bounds.contains(&strip_type(t.clone())))
810                         })
811                         .unwrap_or(false)
812                     {
813                         // If we've already added a projection bound for the same type, don't add
814                         // this, as it would be a duplicate
815
816                         // Handle any 'Fn/FnOnce/FnMut' bounds specially,
817                         // as we want to combine them with any 'Output' qpaths
818                         // later
819
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_)
827                             }
828                             _ => false,
829                         };
830
831                         let poly_trait = b.get_poly_trait().unwrap();
832
833                         if is_fn {
834                             ty_to_fn
835                                 .entry(ty.clone())
836                                 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
837                                 .or_insert(((Some(poly_trait.clone())), None));
838
839                             ty_to_bounds
840                                 .entry(ty.clone())
841                                 .or_insert_with(|| FxHashSet());
842                         } else {
843                             ty_to_bounds
844                                 .entry(ty.clone())
845                                 .or_insert_with(|| FxHashSet())
846                                 .insert(b.clone());
847                         }
848                     }
849                 }
850                 WherePredicate::RegionPredicate { lifetime, bounds } => {
851                     lifetime_to_bounds
852                         .entry(lifetime)
853                         .or_insert_with(|| FxHashSet())
854                         .extend(bounds);
855                 }
856                 WherePredicate::EqPredicate { lhs, rhs } => {
857                     match &lhs {
858                         &Type::QPath {
859                             name: ref left_name,
860                             ref self_type,
861                             ref trait_,
862                         } => {
863                             let ty = &*self_type;
864                             match **trait_ {
865                                 Type::ResolvedPath {
866                                     path: ref trait_path,
867                                     ref typarams,
868                                     ref did,
869                                     ref is_generic,
870                                 } => {
871                                     let mut new_trait_path = trait_path.clone();
872
873                                     if self.is_fn_ty(&tcx, trait_) && left_name == FN_OUTPUT_NAME {
874                                         ty_to_fn
875                                             .entry(*ty.clone())
876                                             .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
877                                             .or_insert((None, Some(rhs)));
878                                         continue;
879                                     }
880
881                                     // FIXME: Remove this scope when NLL lands
882                                     {
883                                         let args =
884                                             &mut new_trait_path.segments.last_mut().unwrap().args;
885
886                                         match args {
887                                             // Convert somethiung like '<T as Iterator::Item> = u8'
888                                             // to 'T: Iterator<Item=u8>'
889                                             &mut GenericArgs::AngleBracketed {
890                                                 ref mut bindings,
891                                                 ..
892                                             } => {
893                                                 bindings.push(TypeBinding {
894                                                     name: left_name.clone(),
895                                                     ty: rhs,
896                                                 });
897                                             }
898                                             &mut GenericArgs::Parenthesized { .. } => {
899                                                 existing_predicates.push(
900                                                     WherePredicate::EqPredicate {
901                                                         lhs: lhs.clone(),
902                                                         rhs,
903                                                     },
904                                                 );
905                                                 continue; // If something other than a Fn ends up
906                                                           // with parenthesis, leave it alone
907                                             }
908                                         }
909                                     }
910
911                                     let bounds = ty_to_bounds
912                                         .entry(*ty.clone())
913                                         .or_insert_with(|| FxHashSet());
914
915                                     bounds.insert(GenericBound::TraitBound(
916                                         PolyTrait {
917                                             trait_: Type::ResolvedPath {
918                                                 path: new_trait_path,
919                                                 typarams: typarams.clone(),
920                                                 did: did.clone(),
921                                                 is_generic: *is_generic,
922                                             },
923                                             generic_params: Vec::new(),
924                                         },
925                                         hir::TraitBoundModifier::None,
926                                     ));
927
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>`
931                                     // on the docs page.
932                                     bounds.remove(&GenericBound::TraitBound(
933                                         PolyTrait {
934                                             trait_: *trait_.clone(),
935                                             generic_params: Vec::new(),
936                                         },
937                                         hir::TraitBoundModifier::None,
938                                     ));
939                                     // Avoid creating any new duplicate bounds later in the outer
940                                     // loop
941                                     ty_to_traits
942                                         .entry(*ty.clone())
943                                         .or_insert_with(|| FxHashSet())
944                                         .insert(*trait_.clone());
945                                 }
946                                 _ => panic!("Unexpected trait {:?} for {:?}", trait_, did),
947                             }
948                         }
949                         _ => panic!("Unexpected LHS {:?} for {:?}", lhs, did),
950                     }
951                 }
952             };
953         }
954
955         let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
956
957         existing_predicates.extend(final_bounds);
958
959         for param in generic_params.iter_mut() {
960             match param.kind {
961                 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
962                     // We never want something like `impl<T=Foo>`.
963                     default.take();
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));
967                     }
968                 }
969                 GenericParamDefKind::Lifetime => {}
970             }
971         }
972
973         self.sort_where_predicates(&mut existing_predicates);
974
975         Generics {
976             params: generic_params,
977             where_predicates: existing_predicates,
978         }
979     }
980
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
986     #[inline]
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);
992     }
993
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
999     #[inline]
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);
1005     }
1006
1007     // This might look horrendously hacky, but it's actually not that bad.
1008     //
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.
1014     //
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.
1019     //
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.
1026     //
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))
1036     }
1037
1038     fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {
1039         match &ty {
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)
1044             }
1045             _ => false,
1046         }
1047     }
1048
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.
1053     //
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 {
1060                 self.cx
1061                     .tcx
1062                     .hir
1063                     .definitions()
1064                     .def_path_table()
1065                     .next_id(DefIndexAddressSpace::Low)
1066             } else {
1067                 self.cx
1068                     .cstore
1069                     .def_path_table(crate_num)
1070                     .next_id(DefIndexAddressSpace::Low)
1071             };
1072
1073             DefId {
1074                 krate: crate_num,
1075                 index: next_id,
1076             }
1077         };
1078
1079         let mut fake_ids = self.cx.fake_def_ids.borrow_mut();
1080
1081         let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
1082         fake_ids.insert(
1083             crate_num,
1084             DefId {
1085                 krate: crate_num,
1086                 index: DefIndex::from_array_index(
1087                     def_id.index.as_array_index() + 1,
1088                     def_id.index.address_space(),
1089                 ),
1090             },
1091         );
1092
1093         MAX_DEF_ID.with(|m| {
1094             m.borrow_mut()
1095                 .entry(def_id.krate.clone())
1096                 .or_insert(start_def_id);
1097         });
1098
1099         self.cx.all_fake_def_ids.borrow_mut().insert(def_id);
1100
1101         def_id.clone()
1102     }
1103 }
1104
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>,
1109 }
1110
1111 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
1112     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
1113         self.tcx
1114     }
1115
1116     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1117         (match r {
1118             &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
1119             _ => None,
1120         }).unwrap_or_else(|| r.super_fold_with(self))
1121     }
1122 }