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