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