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