1 use rustc_data_structures::fx::FxHashSet;
3 use rustc_hir::lang_items::LangItem;
4 use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable, TypeSuperFoldable};
5 use rustc_trait_selection::traits::auto_trait::{self, AutoTraitResult};
11 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
12 enum RegionTarget<'tcx> {
17 #[derive(Default, Debug, Clone)]
18 struct RegionDeps<'tcx> {
19 larger: FxHashSet<RegionTarget<'tcx>>,
20 smaller: FxHashSet<RegionTarget<'tcx>>,
23 pub(crate) struct AutoTraitFinder<'a, 'tcx> {
24 pub(crate) cx: &'a mut core::DocContext<'tcx>,
27 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx>
29 'tcx: 'a, // should be an implied bound; rustc bug #98852.
31 pub(crate) fn new(cx: &'a mut core::DocContext<'tcx>) -> Self {
32 AutoTraitFinder { cx }
35 fn generate_for_trait(
39 param_env: ty::ParamEnv<'tcx>,
41 f: &auto_trait::AutoTraitFinder<'tcx>,
42 // If this is set, show only negative trait implementations, not positive ones.
43 discard_positive_impl: bool,
45 let tcx = self.cx.tcx;
46 let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, &[]) };
47 if !self.cx.generated_synthetics.insert((ty, trait_def_id)) {
48 debug!("get_auto_trait_impl_for({:?}): already generated, aborting", trait_ref);
52 let result = f.find_auto_trait_generics(ty, param_env, trait_def_id, |info| {
53 let region_data = info.region_data;
56 .generics_of(item_def_id)
59 .filter_map(|param| match param.kind {
60 ty::GenericParamDefKind::Lifetime => Some(param.name),
63 .map(|name| (name, Lifetime(name)))
65 let lifetime_predicates = Self::handle_lifetimes(®ion_data, &names_map);
66 let new_generics = self.param_env_to_generics(
74 "find_auto_trait_generics(item_def_id={:?}, trait_def_id={:?}): \
76 item_def_id, trait_def_id, new_generics
83 let new_generics = match result {
84 AutoTraitResult::PositiveImpl(new_generics) => {
85 polarity = ty::ImplPolarity::Positive;
86 if discard_positive_impl {
91 AutoTraitResult::NegativeImpl => {
92 polarity = ty::ImplPolarity::Negative;
94 // For negative impls, we use the generic params, but *not* the predicates,
95 // from the original type. Otherwise, the displayed impl appears to be a
96 // conditional negative impl, when it's really unconditional.
98 // For example, consider the struct Foo<T: Copy>(*mut T). Using
99 // the original predicates in our impl would cause us to generate
100 // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
101 // implements Send where T is not copy.
103 // Instead, we generate `impl !Send for Foo<T>`, which better
104 // expresses the fact that `Foo<T>` never implements `Send`,
105 // regardless of the choice of `T`.
106 let raw_generics = clean_ty_generics(
108 tcx.generics_of(item_def_id),
109 ty::GenericPredicates::default(),
111 let params = raw_generics.params;
113 Generics { params, where_predicates: Vec::new() }
115 AutoTraitResult::ExplicitImpl => return None,
120 attrs: Default::default(),
121 visibility: Inherited,
122 item_id: ItemId::Auto { trait_: trait_def_id, for_: item_def_id },
123 kind: Box::new(ImplItem(Box::new(Impl {
124 unsafety: hir::Unsafety::Normal,
125 generics: new_generics,
126 trait_: Some(clean_trait_ref_with_bindings(self.cx, trait_ref, &[])),
127 for_: clean_middle_ty(ty, self.cx, None),
130 kind: ImplKind::Auto,
136 pub(crate) fn get_auto_trait_impls(&mut self, item_def_id: DefId) -> Vec<Item> {
137 let tcx = self.cx.tcx;
138 let param_env = tcx.param_env(item_def_id);
139 let ty = tcx.type_of(item_def_id);
140 let f = auto_trait::AutoTraitFinder::new(tcx);
142 debug!("get_auto_trait_impls({:?})", ty);
143 let auto_traits: Vec<_> = self.cx.auto_traits.iter().copied().collect();
144 let mut auto_traits: Vec<Item> = auto_traits
146 .filter_map(|trait_def_id| {
147 self.generate_for_trait(ty, trait_def_id, param_env, item_def_id, &f, false)
150 // We are only interested in case the type *doesn't* implement the Sized trait.
151 if !ty.is_sized(tcx.at(rustc_span::DUMMY_SP), param_env) {
152 // In case `#![no_core]` is used, `sized_trait` returns nothing.
153 if let Some(item) = tcx.lang_items().sized_trait().and_then(|sized_trait_did| {
154 self.generate_for_trait(ty, sized_trait_did, param_env, item_def_id, &f, true)
156 auto_traits.push(item);
162 fn get_lifetime(region: Region<'_>, names_map: &FxHashMap<Symbol, Lifetime>) -> Lifetime {
165 names_map.get(&name).unwrap_or_else(|| {
166 panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region)
169 .unwrap_or(&Lifetime::statik())
173 /// This method calculates two things: Lifetime constraints of the form `'a: 'b`,
174 /// and region constraints of the form `RegionVid: 'a`
176 /// This is essentially a simplified version of lexical_region_resolve. However,
177 /// handle_lifetimes determines what *needs be* true in order for an impl to hold.
178 /// lexical_region_resolve, along with much of the rest of the compiler, is concerned
179 /// with determining if a given set up constraints/predicates *are* met, given some
180 /// starting conditions (e.g., user-provided code). For this reason, it's easier
181 /// to perform the calculations we need on our own, rather than trying to make
182 /// existing inference/solver code do what we want.
183 fn handle_lifetimes<'cx>(
184 regions: &RegionConstraintData<'cx>,
185 names_map: &FxHashMap<Symbol, Lifetime>,
186 ) -> Vec<WherePredicate> {
187 // Our goal is to 'flatten' the list of constraints by eliminating
188 // all intermediate RegionVids. At the end, all constraints should
189 // be between Regions (aka region variables). This gives us the information
190 // we need to create the Generics.
191 let mut finished: FxHashMap<_, Vec<_>> = Default::default();
193 let mut vid_map: FxHashMap<RegionTarget<'_>, RegionDeps<'_>> = Default::default();
195 // Flattening is done in two parts. First, we insert all of the constraints
196 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
197 // to its smaller and larger regions. Note that 'larger' regions correspond
198 // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
199 for constraint in regions.constraints.keys() {
201 Constraint::VarSubVar(r1, r2) => {
203 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
204 deps1.larger.insert(RegionTarget::RegionVid(r2));
207 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
208 deps2.smaller.insert(RegionTarget::RegionVid(r1));
210 Constraint::RegSubVar(region, vid) => {
211 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
212 deps.smaller.insert(RegionTarget::Region(region));
214 Constraint::VarSubReg(vid, region) => {
215 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
216 deps.larger.insert(RegionTarget::Region(region));
218 Constraint::RegSubReg(r1, r2) => {
219 // The constraint is already in the form that we want, so we're done with it
220 // Desired order is 'larger, smaller', so flip then
221 if region_name(r1) != region_name(r2) {
223 .entry(region_name(r2).expect("no region_name found"))
231 // Here, we 'flatten' the map one element at a time.
232 // All of the element's sub and super regions are connected
233 // to each other. For example, if we have a graph that looks like this:
235 // (A, B) - C - (D, E)
236 // Where (A, B) are subregions, and (D,E) are super-regions
238 // then after deleting 'C', the graph will look like this:
239 // ... - A - (D, E ...)
240 // ... - B - (D, E, ...)
241 // (A, B, ...) - D - ...
242 // (A, B, ...) - E - ...
244 // where '...' signifies the existing sub and super regions of an entry
245 // When two adjacent ty::Regions are encountered, we've computed a final
246 // constraint, and add it to our list. Since we make sure to never re-add
247 // deleted items, this process will always finish.
248 while !vid_map.is_empty() {
249 let target = *vid_map.keys().next().expect("Keys somehow empty");
250 let deps = vid_map.remove(&target).expect("Entry somehow missing");
252 for smaller in deps.smaller.iter() {
253 for larger in deps.larger.iter() {
254 match (smaller, larger) {
255 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
256 if region_name(r1) != region_name(r2) {
258 .entry(region_name(r2).expect("no region name found"))
260 .push(r1) // Larger, smaller
263 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
264 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
265 let smaller_deps = v.into_mut();
266 smaller_deps.larger.insert(*larger);
267 smaller_deps.larger.remove(&target);
270 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
271 if let Entry::Occupied(v) = vid_map.entry(*larger) {
272 let deps = v.into_mut();
273 deps.smaller.insert(*smaller);
274 deps.smaller.remove(&target);
277 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
278 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
279 let smaller_deps = v.into_mut();
280 smaller_deps.larger.insert(*larger);
281 smaller_deps.larger.remove(&target);
284 if let Entry::Occupied(v) = vid_map.entry(*larger) {
285 let larger_deps = v.into_mut();
286 larger_deps.smaller.insert(*smaller);
287 larger_deps.smaller.remove(&target);
295 let lifetime_predicates = names_map
297 .flat_map(|(name, lifetime)| {
298 let empty = Vec::new();
299 let bounds: FxHashSet<GenericBound> = finished
303 .map(|region| GenericBound::Outlives(Self::get_lifetime(*region, names_map)))
306 if bounds.is_empty() {
309 Some(WherePredicate::RegionPredicate {
310 lifetime: lifetime.clone(),
311 bounds: bounds.into_iter().collect(),
319 fn extract_for_generics(&self, pred: ty::Predicate<'tcx>) -> FxHashSet<GenericParamDef> {
320 let bound_predicate = pred.kind();
321 let tcx = self.cx.tcx;
322 let regions = match bound_predicate.skip_binder() {
323 ty::PredicateKind::Trait(poly_trait_pred) => {
324 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_trait_pred))
326 ty::PredicateKind::Projection(poly_proj_pred) => {
327 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_proj_pred))
329 _ => return FxHashSet::default(),
336 // We only care about named late bound regions, as we need to add them
337 // to the 'for<>' section
338 ty::BrNamed(_, name) => Some(GenericParamDef {
340 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
348 fn make_final_bounds(
350 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
351 ty_to_fn: FxHashMap<Type, (PolyTrait, Option<Type>)>,
352 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
353 ) -> Vec<WherePredicate> {
356 .flat_map(|(ty, mut bounds)| {
357 if let Some((ref poly_trait, ref output)) = ty_to_fn.get(&ty) {
358 let mut new_path = poly_trait.trait_.clone();
359 let last_segment = new_path.segments.pop().expect("segments were empty");
361 let (old_input, old_output) = match last_segment.args {
362 GenericArgs::AngleBracketed { args, .. } => {
365 .filter_map(|arg| match arg {
366 GenericArg::Type(ty) => Some(ty.clone()),
372 GenericArgs::Parenthesized { inputs, output } => (inputs, output),
375 let output = output.as_ref().cloned().map(Box::new);
376 if old_output.is_some() && old_output != output {
377 panic!("Output mismatch for {:?} {:?} {:?}", ty, old_output, output);
380 let new_params = GenericArgs::Parenthesized { inputs: old_input, output };
384 .push(PathSegment { name: last_segment.name, args: new_params });
386 bounds.insert(GenericBound::TraitBound(
389 generic_params: poly_trait.generic_params.clone(),
391 hir::TraitBoundModifier::None,
394 if bounds.is_empty() {
398 let mut bounds_vec = bounds.into_iter().collect();
399 self.sort_where_bounds(&mut bounds_vec);
401 Some(WherePredicate::BoundPredicate {
404 bound_params: Vec::new(),
408 lifetime_to_bounds.into_iter().filter(|&(_, ref bounds)| !bounds.is_empty()).map(
409 |(lifetime, bounds)| {
410 let mut bounds_vec = bounds.into_iter().collect();
411 self.sort_where_bounds(&mut bounds_vec);
412 WherePredicate::RegionPredicate { lifetime, bounds: bounds_vec }
419 /// Converts the calculated `ParamEnv` and lifetime information to a [`clean::Generics`](Generics), suitable for
420 /// display on the docs page. Cleaning the `Predicates` produces sub-optimal [`WherePredicate`]s,
421 /// so we fix them up:
423 /// * Multiple bounds for the same type are coalesced into one: e.g., `T: Copy`, `T: Debug`
424 /// becomes `T: Copy + Debug`
425 /// * `Fn` bounds are handled specially - instead of leaving it as `T: Fn(), <T as Fn::Output> =
426 /// K`, we use the dedicated syntax `T: Fn() -> K`
427 /// * We explicitly add a `?Sized` bound if we didn't find any `Sized` predicates for a type
428 fn param_env_to_generics(
431 param_env: ty::ParamEnv<'tcx>,
432 mut existing_predicates: Vec<WherePredicate>,
433 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
436 "param_env_to_generics(item_def_id={:?}, param_env={:?}, \
437 existing_predicates={:?})",
438 item_def_id, param_env, existing_predicates
441 let tcx = self.cx.tcx;
443 // The `Sized` trait must be handled specially, since we only display it when
444 // it is *not* required (i.e., '?Sized')
445 let sized_trait = tcx.require_lang_item(LangItem::Sized, None);
447 let mut replacer = RegionReplacer { vid_to_region: &vid_to_region, tcx };
449 let orig_bounds: FxHashSet<_> = tcx.param_env(item_def_id).caller_bounds().iter().collect();
450 let clean_where_predicates = param_env
454 !orig_bounds.contains(p)
455 || match p.kind().skip_binder() {
456 ty::PredicateKind::Trait(pred) => pred.def_id() == sized_trait,
460 .map(|p| p.fold_with(&mut replacer));
462 let raw_generics = clean_ty_generics(
464 tcx.generics_of(item_def_id),
465 tcx.explicit_predicates_of(item_def_id),
467 let mut generic_params = raw_generics.params;
469 debug!("param_env_to_generics({:?}): generic_params={:?}", item_def_id, generic_params);
471 let mut has_sized = FxHashSet::default();
472 let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
473 let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
474 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Path>> = Default::default();
476 let mut ty_to_fn: FxHashMap<Type, (PolyTrait, Option<Type>)> = Default::default();
478 for p in clean_where_predicates {
479 let (orig_p, p) = (p, clean_predicate(p, self.cx));
485 WherePredicate::BoundPredicate { ty, mut bounds, .. } => {
486 // Writing a projection trait bound of the form
487 // <T as Trait>::Name : ?Sized
488 // is illegal, because ?Sized bounds can only
489 // be written in the (here, nonexistent) definition
491 // Therefore, we make sure that we never add a ?Sized
492 // bound for projections
493 if let Type::QPath { .. } = ty {
494 has_sized.insert(ty.clone());
497 if bounds.is_empty() {
501 let mut for_generics = self.extract_for_generics(orig_p);
503 assert!(bounds.len() == 1);
504 let mut b = bounds.pop().expect("bounds were empty");
506 if b.is_sized_bound(self.cx) {
507 has_sized.insert(ty.clone());
513 .map(|bounds| bounds.contains(&strip_path_generics(trait_)))
517 // If we've already added a projection bound for the same type, don't add
518 // this, as it would be a duplicate
520 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
521 // as we want to combine them with any 'Output' qpaths
524 let is_fn = match b {
525 GenericBound::TraitBound(ref mut p, _) => {
526 // Insert regions into the for_generics hash map first, to ensure
527 // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
528 for_generics.extend(p.generic_params.clone());
529 p.generic_params = for_generics.into_iter().collect();
530 self.is_fn_trait(&p.trait_)
535 let poly_trait = b.get_poly_trait().expect("Cannot get poly trait");
540 .and_modify(|e| *e = (poly_trait.clone(), e.1.clone()))
541 .or_insert(((poly_trait.clone()), None));
543 ty_to_bounds.entry(ty.clone()).or_default();
545 ty_to_bounds.entry(ty.clone()).or_default().insert(b.clone());
549 WherePredicate::RegionPredicate { lifetime, bounds } => {
550 lifetime_to_bounds.entry(lifetime).or_default().extend(bounds);
552 WherePredicate::EqPredicate { lhs, rhs } => {
554 Type::QPath { ref assoc, ref self_type, ref trait_, .. } => {
555 let ty = &*self_type;
556 let mut new_trait = trait_.clone();
558 if self.is_fn_trait(trait_) && assoc.name == sym::Output {
562 *e = (e.0.clone(), Some(rhs.ty().unwrap().clone()))
566 trait_: trait_.clone(),
567 generic_params: Vec::new(),
569 Some(rhs.ty().unwrap().clone()),
574 let args = &mut new_trait
577 .expect("segments were empty")
581 // Convert something like '<T as Iterator::Item> = u8'
582 // to 'T: Iterator<Item=u8>'
583 GenericArgs::AngleBracketed { ref mut bindings, .. } => {
584 bindings.push(TypeBinding {
585 assoc: *assoc.clone(),
586 kind: TypeBindingKind::Equality { term: rhs },
589 GenericArgs::Parenthesized { .. } => {
590 existing_predicates.push(WherePredicate::EqPredicate {
594 continue; // If something other than a Fn ends up
595 // with parentheses, leave it alone
599 let bounds = ty_to_bounds.entry(*ty.clone()).or_default();
601 bounds.insert(GenericBound::TraitBound(
602 PolyTrait { trait_: new_trait, generic_params: Vec::new() },
603 hir::TraitBoundModifier::None,
606 // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
607 // that we don't see a
608 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
610 bounds.remove(&GenericBound::TraitBound(
611 PolyTrait { trait_: trait_.clone(), generic_params: Vec::new() },
612 hir::TraitBoundModifier::None,
614 // Avoid creating any new duplicate bounds later in the outer
616 ty_to_traits.entry(*ty.clone()).or_default().insert(trait_.clone());
618 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, item_def_id),
624 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
626 existing_predicates.extend(final_bounds);
628 for param in generic_params.iter_mut() {
630 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
631 // We never want something like `impl<T=Foo>`.
633 let generic_ty = Type::Generic(param.name);
634 if !has_sized.contains(&generic_ty) {
635 bounds.insert(0, GenericBound::maybe_sized(self.cx));
638 GenericParamDefKind::Lifetime { .. } => {}
639 GenericParamDefKind::Const { ref mut default, .. } => {
640 // We never want something like `impl<const N: usize = 10>`
646 self.sort_where_predicates(&mut existing_predicates);
648 Generics { params: generic_params, where_predicates: existing_predicates }
651 /// Ensure that the predicates are in a consistent order. The precise
652 /// ordering doesn't actually matter, but it's important that
653 /// a given set of predicates always appears in the same order -
654 /// both for visual consistency between 'rustdoc' runs, and to
655 /// make writing tests much easier
657 fn sort_where_predicates(&self, predicates: &mut Vec<WherePredicate>) {
658 // We should never have identical bounds - and if we do,
659 // they're visually identical as well. Therefore, using
660 // an unstable sort is fine.
661 self.unstable_debug_sort(predicates);
664 /// Ensure that the bounds are in a consistent order. The precise
665 /// ordering doesn't actually matter, but it's important that
666 /// a given set of bounds always appears in the same order -
667 /// both for visual consistency between 'rustdoc' runs, and to
668 /// make writing tests much easier
670 fn sort_where_bounds(&self, bounds: &mut Vec<GenericBound>) {
671 // We should never have identical bounds - and if we do,
672 // they're visually identical as well. Therefore, using
673 // an unstable sort is fine.
674 self.unstable_debug_sort(bounds);
677 /// This might look horrendously hacky, but it's actually not that bad.
679 /// For performance reasons, we use several different FxHashMaps
680 /// in the process of computing the final set of where predicates.
681 /// However, the iteration order of a HashMap is completely unspecified.
682 /// In fact, the iteration of an FxHashMap can even vary between platforms,
683 /// since FxHasher has different behavior for 32-bit and 64-bit platforms.
685 /// Obviously, it's extremely undesirable for documentation rendering
686 /// to be dependent on the platform it's run on. Apart from being confusing
687 /// to end users, it makes writing tests much more difficult, as predicates
688 /// can appear in any order in the final result.
690 /// To solve this problem, we sort WherePredicates and GenericBounds
691 /// by their Debug string. The thing to keep in mind is that we don't really
692 /// care what the final order is - we're synthesizing an impl or bound
693 /// ourselves, so any order can be considered equally valid. By sorting the
694 /// predicates and bounds, however, we ensure that for a given codebase, all
695 /// auto-trait impls always render in exactly the same way.
697 /// Using the Debug implementation for sorting prevents us from needing to
698 /// write quite a bit of almost entirely useless code (e.g., how should two
699 /// Types be sorted relative to each other). It also allows us to solve the
700 /// problem for both WherePredicates and GenericBounds at the same time. This
701 /// approach is probably somewhat slower, but the small number of items
702 /// involved (impls rarely have more than a few bounds) means that it
703 /// shouldn't matter in practice.
704 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
705 vec.sort_by_cached_key(|x| format!("{:?}", x))
708 fn is_fn_trait(&self, path: &Path) -> bool {
709 let tcx = self.cx.tcx;
710 let did = path.def_id();
711 did == tcx.require_lang_item(LangItem::Fn, None)
712 || did == tcx.require_lang_item(LangItem::FnMut, None)
713 || did == tcx.require_lang_item(LangItem::FnOnce, None)
717 fn region_name(region: Region<'_>) -> Option<Symbol> {
719 ty::ReEarlyBound(r) => Some(r.name),
724 /// Replaces all [`ty::RegionVid`]s in a type with [`ty::Region`]s, using the provided map.
725 struct RegionReplacer<'a, 'tcx> {
726 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
730 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
731 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
735 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
737 ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
740 .unwrap_or_else(|| r.super_fold_with(self))