]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/auto_trait.rs
Continue String to Symbol conversion in rustdoc
[rust.git] / src / librustdoc / clean / auto_trait.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_hir as hir;
3 use rustc_hir::lang_items::LangItem;
4 use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable};
5 use rustc_trait_selection::traits::auto_trait::{self, AutoTraitResult};
6
7 use std::fmt::Debug;
8
9 use super::*;
10
11 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
12 enum RegionTarget<'tcx> {
13     Region(Region<'tcx>),
14     RegionVid(RegionVid),
15 }
16
17 #[derive(Default, Debug, Clone)]
18 struct RegionDeps<'tcx> {
19     larger: FxHashSet<RegionTarget<'tcx>>,
20     smaller: FxHashSet<RegionTarget<'tcx>>,
21 }
22
23 crate struct AutoTraitFinder<'a, 'tcx> {
24     crate cx: &'a core::DocContext<'tcx>,
25     crate f: auto_trait::AutoTraitFinder<'tcx>,
26 }
27
28 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
29     crate fn new(cx: &'a core::DocContext<'tcx>) -> Self {
30         let f = auto_trait::AutoTraitFinder::new(cx.tcx);
31
32         AutoTraitFinder { cx, f }
33     }
34
35     // FIXME(eddyb) figure out a better way to pass information about
36     // parametrization of `ty` than `param_env_def_id`.
37     crate fn get_auto_trait_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> {
38         let param_env = self.cx.tcx.param_env(param_env_def_id);
39
40         debug!("get_auto_trait_impls({:?})", ty);
41         let auto_traits = self.cx.auto_traits.iter().cloned();
42         auto_traits
43             .filter_map(|trait_def_id| {
44                 let trait_ref = ty::TraitRef {
45                     def_id: trait_def_id,
46                     substs: self.cx.tcx.mk_substs_trait(ty, &[]),
47                 };
48                 if !self.cx.generated_synthetics.borrow_mut().insert((ty, trait_def_id)) {
49                     debug!("get_auto_trait_impl_for({:?}): already generated, aborting", trait_ref);
50                     return None;
51                 }
52
53                 let result =
54                     self.f.find_auto_trait_generics(ty, param_env, trait_def_id, |infcx, info| {
55                         let region_data = info.region_data;
56
57                         let names_map = self
58                             .cx
59                             .tcx
60                             .generics_of(param_env_def_id)
61                             .params
62                             .iter()
63                             .filter_map(|param| match param.kind {
64                                 ty::GenericParamDefKind::Lifetime => Some(param.name),
65                                 _ => None,
66                             })
67                             .map(|name| (name, Lifetime(name)))
68                             .collect();
69                         let lifetime_predicates = self.handle_lifetimes(&region_data, &names_map);
70                         let new_generics = self.param_env_to_generics(
71                             infcx.tcx,
72                             param_env_def_id,
73                             info.full_user_env,
74                             lifetime_predicates,
75                             info.vid_to_region,
76                         );
77
78                         debug!(
79                             "find_auto_trait_generics(param_env_def_id={:?}, trait_def_id={:?}): \
80                             finished with {:?}",
81                             param_env_def_id, trait_def_id, new_generics
82                         );
83
84                         new_generics
85                     });
86
87                 let polarity;
88                 let new_generics = match result {
89                     AutoTraitResult::PositiveImpl(new_generics) => {
90                         polarity = None;
91                         new_generics
92                     }
93                     AutoTraitResult::NegativeImpl => {
94                         polarity = Some(ImplPolarity::Negative);
95
96                         // For negative impls, we use the generic params, but *not* the predicates,
97                         // from the original type. Otherwise, the displayed impl appears to be a
98                         // conditional negative impl, when it's really unconditional.
99                         //
100                         // For example, consider the struct Foo<T: Copy>(*mut T). Using
101                         // the original predicates in our impl would cause us to generate
102                         // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
103                         // implements Send where T is not copy.
104                         //
105                         // Instead, we generate `impl !Send for Foo<T>`, which better
106                         // expresses the fact that `Foo<T>` never implements `Send`,
107                         // regardless of the choice of `T`.
108                         let params = (
109                             self.cx.tcx.generics_of(param_env_def_id),
110                             ty::GenericPredicates::default(),
111                         )
112                             .clean(self.cx)
113                             .params;
114
115                         Generics { params, where_predicates: Vec::new() }
116                     }
117                     AutoTraitResult::ExplicitImpl => return None,
118                 };
119
120                 Some(Item {
121                     source: Span::dummy(),
122                     name: None,
123                     attrs: Default::default(),
124                     visibility: Inherited,
125                     def_id: self.cx.next_def_id(param_env_def_id.krate),
126                     stability: None,
127                     const_stability: None,
128                     deprecation: None,
129                     kind: ImplItem(Impl {
130                         unsafety: hir::Unsafety::Normal,
131                         generics: new_generics,
132                         provided_trait_methods: Default::default(),
133                         trait_: Some(trait_ref.clean(self.cx).get_trait_type().unwrap()),
134                         for_: ty.clean(self.cx),
135                         items: Vec::new(),
136                         polarity,
137                         synthetic: true,
138                         blanket_impl: None,
139                     }),
140                 })
141             })
142             .collect()
143     }
144
145     fn get_lifetime(
146         &self,
147         region: Region<'_>,
148         names_map: &FxHashMap<Symbol, Lifetime>,
149     ) -> Lifetime {
150         self.region_name(region)
151             .map(|name| {
152                 names_map.get(&name).unwrap_or_else(|| {
153                     panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region)
154                 })
155             })
156             .unwrap_or(&Lifetime::statik())
157             .clone()
158     }
159
160     fn region_name(&self, region: Region<'_>) -> Option<Symbol> {
161         match region {
162             &ty::ReEarlyBound(r) => Some(r.name),
163             _ => None,
164         }
165     }
166
167     // This method calculates two things: Lifetime constraints of the form 'a: 'b,
168     // and region constraints of the form ReVar: 'a
169     //
170     // This is essentially a simplified version of lexical_region_resolve. However,
171     // handle_lifetimes determines what *needs be* true in order for an impl to hold.
172     // lexical_region_resolve, along with much of the rest of the compiler, is concerned
173     // with determining if a given set up constraints/predicates *are* met, given some
174     // starting conditions (e.g., user-provided code). For this reason, it's easier
175     // to perform the calculations we need on our own, rather than trying to make
176     // existing inference/solver code do what we want.
177     fn handle_lifetimes<'cx>(
178         &self,
179         regions: &RegionConstraintData<'cx>,
180         names_map: &FxHashMap<Symbol, Lifetime>,
181     ) -> Vec<WherePredicate> {
182         // Our goal is to 'flatten' the list of constraints by eliminating
183         // all intermediate RegionVids. At the end, all constraints should
184         // be between Regions (aka region variables). This gives us the information
185         // we need to create the Generics.
186         let mut finished: FxHashMap<_, Vec<_>> = Default::default();
187
188         let mut vid_map: FxHashMap<RegionTarget<'_>, RegionDeps<'_>> = Default::default();
189
190         // Flattening is done in two parts. First, we insert all of the constraints
191         // into a map. Each RegionTarget (either a RegionVid or a Region) maps
192         // to its smaller and larger regions. Note that 'larger' regions correspond
193         // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
194         for constraint in regions.constraints.keys() {
195             match constraint {
196                 &Constraint::VarSubVar(r1, r2) => {
197                     {
198                         let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
199                         deps1.larger.insert(RegionTarget::RegionVid(r2));
200                     }
201
202                     let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
203                     deps2.smaller.insert(RegionTarget::RegionVid(r1));
204                 }
205                 &Constraint::RegSubVar(region, vid) => {
206                     let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
207                     deps.smaller.insert(RegionTarget::Region(region));
208                 }
209                 &Constraint::VarSubReg(vid, region) => {
210                     let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
211                     deps.larger.insert(RegionTarget::Region(region));
212                 }
213                 &Constraint::RegSubReg(r1, r2) => {
214                     // The constraint is already in the form that we want, so we're done with it
215                     // Desired order is 'larger, smaller', so flip then
216                     if self.region_name(r1) != self.region_name(r2) {
217                         finished
218                             .entry(self.region_name(r2).expect("no region_name found"))
219                             .or_default()
220                             .push(r1);
221                     }
222                 }
223             }
224         }
225
226         // Here, we 'flatten' the map one element at a time.
227         // All of the element's sub and super regions are connected
228         // to each other. For example, if we have a graph that looks like this:
229         //
230         // (A, B) - C - (D, E)
231         // Where (A, B) are subregions, and (D,E) are super-regions
232         //
233         // then after deleting 'C', the graph will look like this:
234         //  ... - A - (D, E ...)
235         //  ... - B - (D, E, ...)
236         //  (A, B, ...) - D - ...
237         //  (A, B, ...) - E - ...
238         //
239         //  where '...' signifies the existing sub and super regions of an entry
240         //  When two adjacent ty::Regions are encountered, we've computed a final
241         //  constraint, and add it to our list. Since we make sure to never re-add
242         //  deleted items, this process will always finish.
243         while !vid_map.is_empty() {
244             let target = *vid_map.keys().next().expect("Keys somehow empty");
245             let deps = vid_map.remove(&target).expect("Entry somehow missing");
246
247             for smaller in deps.smaller.iter() {
248                 for larger in deps.larger.iter() {
249                     match (smaller, larger) {
250                         (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
251                             if self.region_name(r1) != self.region_name(r2) {
252                                 finished
253                                     .entry(self.region_name(r2).expect("no region name found"))
254                                     .or_default()
255                                     .push(r1) // Larger, smaller
256                             }
257                         }
258                         (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
259                             if let Entry::Occupied(v) = vid_map.entry(*smaller) {
260                                 let smaller_deps = v.into_mut();
261                                 smaller_deps.larger.insert(*larger);
262                                 smaller_deps.larger.remove(&target);
263                             }
264                         }
265                         (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
266                             if let Entry::Occupied(v) = vid_map.entry(*larger) {
267                                 let deps = v.into_mut();
268                                 deps.smaller.insert(*smaller);
269                                 deps.smaller.remove(&target);
270                             }
271                         }
272                         (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
273                             if let Entry::Occupied(v) = vid_map.entry(*smaller) {
274                                 let smaller_deps = v.into_mut();
275                                 smaller_deps.larger.insert(*larger);
276                                 smaller_deps.larger.remove(&target);
277                             }
278
279                             if let Entry::Occupied(v) = vid_map.entry(*larger) {
280                                 let larger_deps = v.into_mut();
281                                 larger_deps.smaller.insert(*smaller);
282                                 larger_deps.smaller.remove(&target);
283                             }
284                         }
285                     }
286                 }
287             }
288         }
289
290         let lifetime_predicates = names_map
291             .iter()
292             .flat_map(|(name, lifetime)| {
293                 let empty = Vec::new();
294                 let bounds: FxHashSet<GenericBound> = finished
295                     .get(name)
296                     .unwrap_or(&empty)
297                     .iter()
298                     .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
299                     .collect();
300
301                 if bounds.is_empty() {
302                     return None;
303                 }
304                 Some(WherePredicate::RegionPredicate {
305                     lifetime: lifetime.clone(),
306                     bounds: bounds.into_iter().collect(),
307                 })
308             })
309             .collect();
310
311         lifetime_predicates
312     }
313
314     fn extract_for_generics(
315         &self,
316         tcx: TyCtxt<'tcx>,
317         pred: ty::Predicate<'tcx>,
318     ) -> FxHashSet<GenericParamDef> {
319         let bound_predicate = pred.bound_atom();
320         let regions = match bound_predicate.skip_binder() {
321             ty::PredicateAtom::Trait(poly_trait_pred, _) => {
322                 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_trait_pred))
323             }
324             ty::PredicateAtom::Projection(poly_proj_pred) => {
325                 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_proj_pred))
326             }
327             _ => return FxHashSet::default(),
328         };
329
330         regions
331             .into_iter()
332             .filter_map(|br| {
333                 match br {
334                     // We only care about named late bound regions, as we need to add them
335                     // to the 'for<>' section
336                     ty::BrNamed(_, name) => {
337                         Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
338                     }
339                     _ => None,
340                 }
341             })
342             .collect()
343     }
344
345     fn make_final_bounds(
346         &self,
347         ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
348         ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
349         lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
350     ) -> Vec<WherePredicate> {
351         ty_to_bounds
352             .into_iter()
353             .flat_map(|(ty, mut bounds)| {
354                 if let Some(data) = ty_to_fn.get(&ty) {
355                     let (poly_trait, output) =
356                         (data.0.as_ref().expect("as_ref failed").clone(), data.1.as_ref().cloned());
357                     let new_ty = match &poly_trait.trait_ {
358                         &Type::ResolvedPath {
359                             ref path,
360                             ref param_names,
361                             ref did,
362                             ref is_generic,
363                         } => {
364                             let mut new_path = path.clone();
365                             let last_segment =
366                                 new_path.segments.pop().expect("segments were empty");
367
368                             let (old_input, old_output) = match last_segment.args {
369                                 GenericArgs::AngleBracketed { args, .. } => {
370                                     let types = args
371                                         .iter()
372                                         .filter_map(|arg| match arg {
373                                             GenericArg::Type(ty) => Some(ty.clone()),
374                                             _ => None,
375                                         })
376                                         .collect();
377                                     (types, None)
378                                 }
379                                 GenericArgs::Parenthesized { inputs, output, .. } => {
380                                     (inputs, output)
381                                 }
382                             };
383
384                             if old_output.is_some() && old_output != output {
385                                 panic!(
386                                     "Output mismatch for {:?} {:?} {:?}",
387                                     ty, old_output, data.1
388                                 );
389                             }
390
391                             let new_params =
392                                 GenericArgs::Parenthesized { inputs: old_input, output };
393
394                             new_path
395                                 .segments
396                                 .push(PathSegment { name: last_segment.name, args: new_params });
397
398                             Type::ResolvedPath {
399                                 path: new_path,
400                                 param_names: param_names.clone(),
401                                 did: *did,
402                                 is_generic: *is_generic,
403                             }
404                         }
405                         _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
406                     };
407                     bounds.insert(GenericBound::TraitBound(
408                         PolyTrait { trait_: new_ty, generic_params: poly_trait.generic_params },
409                         hir::TraitBoundModifier::None,
410                     ));
411                 }
412                 if bounds.is_empty() {
413                     return None;
414                 }
415
416                 let mut bounds_vec = bounds.into_iter().collect();
417                 self.sort_where_bounds(&mut bounds_vec);
418
419                 Some(WherePredicate::BoundPredicate { ty, bounds: bounds_vec })
420             })
421             .chain(
422                 lifetime_to_bounds.into_iter().filter(|&(_, ref bounds)| !bounds.is_empty()).map(
423                     |(lifetime, bounds)| {
424                         let mut bounds_vec = bounds.into_iter().collect();
425                         self.sort_where_bounds(&mut bounds_vec);
426                         WherePredicate::RegionPredicate { lifetime, bounds: bounds_vec }
427                     },
428                 ),
429             )
430             .collect()
431     }
432
433     // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
434     // display on the docs page. Cleaning the Predicates produces sub-optimal `WherePredicate`s,
435     // so we fix them up:
436     //
437     // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug'
438     // becomes 'T: Copy + Debug'
439     // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
440     // K', we use the dedicated syntax 'T: Fn() -> K'
441     // * We explicitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
442     fn param_env_to_generics(
443         &self,
444         tcx: TyCtxt<'tcx>,
445         param_env_def_id: DefId,
446         param_env: ty::ParamEnv<'tcx>,
447         mut existing_predicates: Vec<WherePredicate>,
448         vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
449     ) -> Generics {
450         debug!(
451             "param_env_to_generics(param_env_def_id={:?}, param_env={:?}, \
452              existing_predicates={:?})",
453             param_env_def_id, param_env, existing_predicates
454         );
455
456         // The `Sized` trait must be handled specially, since we only display it when
457         // it is *not* required (i.e., '?Sized')
458         let sized_trait = self.cx.tcx.require_lang_item(LangItem::Sized, None);
459
460         let mut replacer = RegionReplacer { vid_to_region: &vid_to_region, tcx };
461
462         let orig_bounds: FxHashSet<_> =
463             self.cx.tcx.param_env(param_env_def_id).caller_bounds().iter().collect();
464         let clean_where_predicates = param_env
465             .caller_bounds()
466             .iter()
467             .filter(|p| {
468                 !orig_bounds.contains(p)
469                     || match p.skip_binders() {
470                         ty::PredicateAtom::Trait(pred, _) => pred.def_id() == sized_trait,
471                         _ => false,
472                     }
473             })
474             .map(|p| {
475                 let replaced = p.fold_with(&mut replacer);
476                 (replaced, replaced.clean(self.cx))
477             });
478
479         let mut generic_params =
480             (tcx.generics_of(param_env_def_id), tcx.explicit_predicates_of(param_env_def_id))
481                 .clean(self.cx)
482                 .params;
483
484         debug!(
485             "param_env_to_generics({:?}): generic_params={:?}",
486             param_env_def_id, generic_params
487         );
488
489         let mut has_sized = FxHashSet::default();
490         let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
491         let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
492         let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = Default::default();
493
494         let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = Default::default();
495
496         for (orig_p, p) in clean_where_predicates {
497             if p.is_none() {
498                 continue;
499             }
500             let p = p.unwrap();
501             match p {
502                 WherePredicate::BoundPredicate { ty, mut bounds } => {
503                     // Writing a projection trait bound of the form
504                     // <T as Trait>::Name : ?Sized
505                     // is illegal, because ?Sized bounds can only
506                     // be written in the (here, nonexistent) definition
507                     // of the type.
508                     // Therefore, we make sure that we never add a ?Sized
509                     // bound for projections
510                     if let Type::QPath { .. } = ty {
511                         has_sized.insert(ty.clone());
512                     }
513
514                     if bounds.is_empty() {
515                         continue;
516                     }
517
518                     let mut for_generics = self.extract_for_generics(tcx, orig_p);
519
520                     assert!(bounds.len() == 1);
521                     let mut b = bounds.pop().expect("bounds were empty");
522
523                     if b.is_sized_bound(self.cx) {
524                         has_sized.insert(ty.clone());
525                     } else if !b
526                         .get_trait_type()
527                         .and_then(|t| {
528                             ty_to_traits
529                                 .get(&ty)
530                                 .map(|bounds| bounds.contains(&strip_type(t.clone())))
531                         })
532                         .unwrap_or(false)
533                     {
534                         // If we've already added a projection bound for the same type, don't add
535                         // this, as it would be a duplicate
536
537                         // Handle any 'Fn/FnOnce/FnMut' bounds specially,
538                         // as we want to combine them with any 'Output' qpaths
539                         // later
540
541                         let is_fn = match &mut b {
542                             &mut GenericBound::TraitBound(ref mut p, _) => {
543                                 // Insert regions into the for_generics hash map first, to ensure
544                                 // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
545                                 for_generics.extend(p.generic_params.clone());
546                                 p.generic_params = for_generics.into_iter().collect();
547                                 self.is_fn_ty(tcx, &p.trait_)
548                             }
549                             _ => false,
550                         };
551
552                         let poly_trait = b.get_poly_trait().expect("Cannot get poly trait");
553
554                         if is_fn {
555                             ty_to_fn
556                                 .entry(ty.clone())
557                                 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
558                                 .or_insert(((Some(poly_trait.clone())), None));
559
560                             ty_to_bounds.entry(ty.clone()).or_default();
561                         } else {
562                             ty_to_bounds.entry(ty.clone()).or_default().insert(b.clone());
563                         }
564                     }
565                 }
566                 WherePredicate::RegionPredicate { lifetime, bounds } => {
567                     lifetime_to_bounds.entry(lifetime).or_default().extend(bounds);
568                 }
569                 WherePredicate::EqPredicate { lhs, rhs } => {
570                     match lhs {
571                         Type::QPath { name: left_name, ref self_type, ref trait_ } => {
572                             let ty = &*self_type;
573                             match **trait_ {
574                                 Type::ResolvedPath {
575                                     path: ref trait_path,
576                                     ref param_names,
577                                     ref did,
578                                     ref is_generic,
579                                 } => {
580                                     let mut new_trait_path = trait_path.clone();
581
582                                     if self.is_fn_ty(tcx, trait_) && left_name == sym::Output {
583                                         ty_to_fn
584                                             .entry(*ty.clone())
585                                             .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
586                                             .or_insert((None, Some(rhs)));
587                                         continue;
588                                     }
589
590                                     let args = &mut new_trait_path
591                                         .segments
592                                         .last_mut()
593                                         .expect("segments were empty")
594                                         .args;
595
596                                     match args {
597                                         // Convert something like '<T as Iterator::Item> = u8'
598                                         // to 'T: Iterator<Item=u8>'
599                                         GenericArgs::AngleBracketed {
600                                             ref mut bindings, ..
601                                         } => {
602                                             bindings.push(TypeBinding {
603                                                 name: left_name.clone(),
604                                                 kind: TypeBindingKind::Equality { ty: rhs },
605                                             });
606                                         }
607                                         GenericArgs::Parenthesized { .. } => {
608                                             existing_predicates.push(WherePredicate::EqPredicate {
609                                                 lhs: lhs.clone(),
610                                                 rhs,
611                                             });
612                                             continue; // If something other than a Fn ends up
613                                             // with parenthesis, leave it alone
614                                         }
615                                     }
616
617                                     let bounds = ty_to_bounds.entry(*ty.clone()).or_default();
618
619                                     bounds.insert(GenericBound::TraitBound(
620                                         PolyTrait {
621                                             trait_: Type::ResolvedPath {
622                                                 path: new_trait_path,
623                                                 param_names: param_names.clone(),
624                                                 did: *did,
625                                                 is_generic: *is_generic,
626                                             },
627                                             generic_params: Vec::new(),
628                                         },
629                                         hir::TraitBoundModifier::None,
630                                     ));
631
632                                     // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
633                                     // that we don't see a
634                                     // duplicate bound like `T: Iterator + Iterator<Item=u8>`
635                                     // on the docs page.
636                                     bounds.remove(&GenericBound::TraitBound(
637                                         PolyTrait {
638                                             trait_: *trait_.clone(),
639                                             generic_params: Vec::new(),
640                                         },
641                                         hir::TraitBoundModifier::None,
642                                     ));
643                                     // Avoid creating any new duplicate bounds later in the outer
644                                     // loop
645                                     ty_to_traits
646                                         .entry(*ty.clone())
647                                         .or_default()
648                                         .insert(*trait_.clone());
649                                 }
650                                 _ => panic!(
651                                     "Unexpected trait {:?} for {:?}",
652                                     trait_, param_env_def_id,
653                                 ),
654                             }
655                         }
656                         _ => panic!("Unexpected LHS {:?} for {:?}", lhs, param_env_def_id),
657                     }
658                 }
659             };
660         }
661
662         let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
663
664         existing_predicates.extend(final_bounds);
665
666         for param in generic_params.iter_mut() {
667             match param.kind {
668                 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
669                     // We never want something like `impl<T=Foo>`.
670                     default.take();
671                     let generic_ty = Type::Generic(param.name.clone());
672                     if !has_sized.contains(&generic_ty) {
673                         bounds.insert(0, GenericBound::maybe_sized(self.cx));
674                     }
675                 }
676                 GenericParamDefKind::Lifetime => {}
677                 GenericParamDefKind::Const { .. } => {}
678             }
679         }
680
681         self.sort_where_predicates(&mut existing_predicates);
682
683         Generics { params: generic_params, where_predicates: existing_predicates }
684     }
685
686     // Ensure that the predicates are in a consistent order. The precise
687     // ordering doesn't actually matter, but it's important that
688     // a given set of predicates always appears in the same order -
689     // both for visual consistency between 'rustdoc' runs, and to
690     // make writing tests much easier
691     #[inline]
692     fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
693         // We should never have identical bounds - and if we do,
694         // they're visually identical as well. Therefore, using
695         // an unstable sort is fine.
696         self.unstable_debug_sort(&mut predicates);
697     }
698
699     // Ensure that the bounds are in a consistent order. The precise
700     // ordering doesn't actually matter, but it's important that
701     // a given set of bounds always appears in the same order -
702     // both for visual consistency between 'rustdoc' runs, and to
703     // make writing tests much easier
704     #[inline]
705     fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
706         // We should never have identical bounds - and if we do,
707         // they're visually identical as well. Therefore, using
708         // an unstable sort is fine.
709         self.unstable_debug_sort(&mut bounds);
710     }
711
712     // This might look horrendously hacky, but it's actually not that bad.
713     //
714     // For performance reasons, we use several different FxHashMaps
715     // in the process of computing the final set of where predicates.
716     // However, the iteration order of a HashMap is completely unspecified.
717     // In fact, the iteration of an FxHashMap can even vary between platforms,
718     // since FxHasher has different behavior for 32-bit and 64-bit platforms.
719     //
720     // Obviously, it's extremely undesirable for documentation rendering
721     // to be dependent on the platform it's run on. Apart from being confusing
722     // to end users, it makes writing tests much more difficult, as predicates
723     // can appear in any order in the final result.
724     //
725     // To solve this problem, we sort WherePredicates and GenericBounds
726     // by their Debug string. The thing to keep in mind is that we don't really
727     // care what the final order is - we're synthesizing an impl or bound
728     // ourselves, so any order can be considered equally valid. By sorting the
729     // predicates and bounds, however, we ensure that for a given codebase, all
730     // auto-trait impls always render in exactly the same way.
731     //
732     // Using the Debug implementation for sorting prevents us from needing to
733     // write quite a bit of almost entirely useless code (e.g., how should two
734     // Types be sorted relative to each other). It also allows us to solve the
735     // problem for both WherePredicates and GenericBounds at the same time. This
736     // approach is probably somewhat slower, but the small number of items
737     // involved (impls rarely have more than a few bounds) means that it
738     // shouldn't matter in practice.
739     fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
740         vec.sort_by_cached_key(|x| format!("{:?}", x))
741     }
742
743     fn is_fn_ty(&self, tcx: TyCtxt<'_>, ty: &Type) -> bool {
744         match &ty {
745             &&Type::ResolvedPath { ref did, .. } => {
746                 *did == tcx.require_lang_item(LangItem::Fn, None)
747                     || *did == tcx.require_lang_item(LangItem::FnMut, None)
748                     || *did == tcx.require_lang_item(LangItem::FnOnce, None)
749             }
750             _ => false,
751         }
752     }
753 }
754
755 // Replaces all ReVars in a type with ty::Region's, using the provided map
756 struct RegionReplacer<'a, 'tcx> {
757     vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
758     tcx: TyCtxt<'tcx>,
759 }
760
761 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
762     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
763         self.tcx
764     }
765
766     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
767         (match r {
768             &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
769             _ => None,
770         })
771         .unwrap_or_else(|| r.super_fold_with(self))
772     }
773 }