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