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