1 use rustc_data_structures::fx::FxHashSet;
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};
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 crate struct AutoTraitFinder<'a, 'tcx> {
24 crate cx: &'a core::DocContext<'tcx>,
25 crate f: auto_trait::AutoTraitFinder<'tcx>,
28 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
29 crate fn new(cx: &'a core::DocContext<'tcx>) -> Self {
30 let f = auto_trait::AutoTraitFinder::new(cx.tcx);
32 AutoTraitFinder { cx, f }
35 // FIXME(eddyb) figure out a better way to pass information about
36 // parametrization of `ty` than `param_env_def_id`.
37 crate fn get_auto_trait_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> {
38 let param_env = self.cx.tcx.param_env(param_env_def_id);
40 debug!("get_auto_trait_impls({:?})", ty);
41 let auto_traits = self.cx.auto_traits.iter().cloned();
43 .filter_map(|trait_def_id| {
44 let trait_ref = ty::TraitRef {
46 substs: self.cx.tcx.mk_substs_trait(ty, &[]),
48 if !self.cx.generated_synthetics.borrow_mut().insert((ty, trait_def_id)) {
49 debug!("get_auto_trait_impl_for({:?}): already generated, aborting", trait_ref);
54 self.f.find_auto_trait_generics(ty, param_env, trait_def_id, |infcx, info| {
55 let region_data = info.region_data;
60 .generics_of(param_env_def_id)
63 .filter_map(|param| match param.kind {
64 ty::GenericParamDefKind::Lifetime => Some(param.name),
67 .map(|name| (name, Lifetime(name)))
69 let lifetime_predicates = self.handle_lifetimes(®ion_data, &names_map);
70 let new_generics = self.param_env_to_generics(
79 "find_auto_trait_generics(param_env_def_id={:?}, trait_def_id={:?}): \
81 param_env_def_id, trait_def_id, new_generics
88 let new_generics = match result {
89 AutoTraitResult::PositiveImpl(new_generics) => {
93 AutoTraitResult::NegativeImpl => {
94 polarity = Some(ImplPolarity::Negative);
96 // For negative impls, we use the generic params, but *not* the predicates,
97 // from the original type. Otherwise, the displayed impl appears to be a
98 // conditional negative impl, when it's really unconditional.
100 // For example, consider the struct Foo<T: Copy>(*mut T). Using
101 // the original predicates in our impl would cause us to generate
102 // `impl !Send for Foo<T: Copy>`, which makes it appear that Foo
103 // implements Send where T is not copy.
105 // Instead, we generate `impl !Send for Foo<T>`, which better
106 // expresses the fact that `Foo<T>` never implements `Send`,
107 // regardless of the choice of `T`.
109 self.cx.tcx.generics_of(param_env_def_id),
110 ty::GenericPredicates::default(),
115 Generics { params, where_predicates: Vec::new() }
117 AutoTraitResult::ExplicitImpl => return None,
121 source: Span::dummy(),
123 attrs: Default::default(),
124 visibility: Inherited,
125 def_id: self.cx.next_def_id(param_env_def_id.krate),
126 kind: box ImplItem(Impl {
127 unsafety: hir::Unsafety::Normal,
128 generics: new_generics,
129 provided_trait_methods: Default::default(),
130 trait_: Some(trait_ref.clean(self.cx).get_trait_type().unwrap()),
131 for_: ty.clean(self.cx),
145 names_map: &FxHashMap<Symbol, Lifetime>,
147 self.region_name(region)
149 names_map.get(&name).unwrap_or_else(|| {
150 panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region)
153 .unwrap_or(&Lifetime::statik())
157 fn region_name(&self, region: Region<'_>) -> Option<Symbol> {
159 &ty::ReEarlyBound(r) => Some(r.name),
164 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
165 // and region constraints of the form ReVar: 'a
167 // This is essentially a simplified version of lexical_region_resolve. However,
168 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
169 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
170 // with determining if a given set up constraints/predicates *are* met, given some
171 // starting conditions (e.g., user-provided code). For this reason, it's easier
172 // to perform the calculations we need on our own, rather than trying to make
173 // existing inference/solver code do what we want.
174 fn handle_lifetimes<'cx>(
176 regions: &RegionConstraintData<'cx>,
177 names_map: &FxHashMap<Symbol, Lifetime>,
178 ) -> Vec<WherePredicate> {
179 // Our goal is to 'flatten' the list of constraints by eliminating
180 // all intermediate RegionVids. At the end, all constraints should
181 // be between Regions (aka region variables). This gives us the information
182 // we need to create the Generics.
183 let mut finished: FxHashMap<_, Vec<_>> = Default::default();
185 let mut vid_map: FxHashMap<RegionTarget<'_>, RegionDeps<'_>> = Default::default();
187 // Flattening is done in two parts. First, we insert all of the constraints
188 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
189 // to its smaller and larger regions. Note that 'larger' regions correspond
190 // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
191 for constraint in regions.constraints.keys() {
193 &Constraint::VarSubVar(r1, r2) => {
195 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
196 deps1.larger.insert(RegionTarget::RegionVid(r2));
199 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
200 deps2.smaller.insert(RegionTarget::RegionVid(r1));
202 &Constraint::RegSubVar(region, vid) => {
203 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
204 deps.smaller.insert(RegionTarget::Region(region));
206 &Constraint::VarSubReg(vid, region) => {
207 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
208 deps.larger.insert(RegionTarget::Region(region));
210 &Constraint::RegSubReg(r1, r2) => {
211 // The constraint is already in the form that we want, so we're done with it
212 // Desired order is 'larger, smaller', so flip then
213 if self.region_name(r1) != self.region_name(r2) {
215 .entry(self.region_name(r2).expect("no region_name found"))
223 // Here, we 'flatten' the map one element at a time.
224 // All of the element's sub and super regions are connected
225 // to each other. For example, if we have a graph that looks like this:
227 // (A, B) - C - (D, E)
228 // Where (A, B) are subregions, and (D,E) are super-regions
230 // then after deleting 'C', the graph will look like this:
231 // ... - A - (D, E ...)
232 // ... - B - (D, E, ...)
233 // (A, B, ...) - D - ...
234 // (A, B, ...) - E - ...
236 // where '...' signifies the existing sub and super regions of an entry
237 // When two adjacent ty::Regions are encountered, we've computed a final
238 // constraint, and add it to our list. Since we make sure to never re-add
239 // deleted items, this process will always finish.
240 while !vid_map.is_empty() {
241 let target = *vid_map.keys().next().expect("Keys somehow empty");
242 let deps = vid_map.remove(&target).expect("Entry somehow missing");
244 for smaller in deps.smaller.iter() {
245 for larger in deps.larger.iter() {
246 match (smaller, larger) {
247 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
248 if self.region_name(r1) != self.region_name(r2) {
250 .entry(self.region_name(r2).expect("no region name found"))
252 .push(r1) // Larger, smaller
255 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
256 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
257 let smaller_deps = v.into_mut();
258 smaller_deps.larger.insert(*larger);
259 smaller_deps.larger.remove(&target);
262 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
263 if let Entry::Occupied(v) = vid_map.entry(*larger) {
264 let deps = v.into_mut();
265 deps.smaller.insert(*smaller);
266 deps.smaller.remove(&target);
269 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
270 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
271 let smaller_deps = v.into_mut();
272 smaller_deps.larger.insert(*larger);
273 smaller_deps.larger.remove(&target);
276 if let Entry::Occupied(v) = vid_map.entry(*larger) {
277 let larger_deps = v.into_mut();
278 larger_deps.smaller.insert(*smaller);
279 larger_deps.smaller.remove(&target);
287 let lifetime_predicates = names_map
289 .flat_map(|(name, lifetime)| {
290 let empty = Vec::new();
291 let bounds: FxHashSet<GenericBound> = finished
295 .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
298 if bounds.is_empty() {
301 Some(WherePredicate::RegionPredicate {
302 lifetime: lifetime.clone(),
303 bounds: bounds.into_iter().collect(),
311 fn extract_for_generics(
314 pred: ty::Predicate<'tcx>,
315 ) -> FxHashSet<GenericParamDef> {
316 let bound_predicate = pred.bound_atom();
317 let regions = match bound_predicate.skip_binder() {
318 ty::PredicateAtom::Trait(poly_trait_pred, _) => {
319 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_trait_pred))
321 ty::PredicateAtom::Projection(poly_proj_pred) => {
322 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_proj_pred))
324 _ => return FxHashSet::default(),
331 // We only care about named late bound regions, as we need to add them
332 // to the 'for<>' section
333 ty::BrNamed(_, name) => {
334 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
342 fn make_final_bounds(
344 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
345 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
346 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
347 ) -> Vec<WherePredicate> {
350 .flat_map(|(ty, mut bounds)| {
351 if let Some(data) = ty_to_fn.get(&ty) {
352 let (poly_trait, output) =
353 (data.0.as_ref().expect("as_ref failed").clone(), data.1.as_ref().cloned());
354 let new_ty = match poly_trait.trait_ {
361 let mut new_path = path.clone();
363 new_path.segments.pop().expect("segments were empty");
365 let (old_input, old_output) = match last_segment.args {
366 GenericArgs::AngleBracketed { args, .. } => {
369 .filter_map(|arg| match arg {
370 GenericArg::Type(ty) => Some(ty.clone()),
376 GenericArgs::Parenthesized { inputs, output, .. } => {
381 if old_output.is_some() && old_output != output {
383 "Output mismatch for {:?} {:?} {:?}",
384 ty, old_output, data.1
389 GenericArgs::Parenthesized { inputs: old_input, output };
393 .push(PathSegment { name: last_segment.name, args: new_params });
397 param_names: param_names.clone(),
399 is_generic: *is_generic,
402 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
404 bounds.insert(GenericBound::TraitBound(
405 PolyTrait { trait_: new_ty, generic_params: poly_trait.generic_params },
406 hir::TraitBoundModifier::None,
409 if bounds.is_empty() {
413 let mut bounds_vec = bounds.into_iter().collect();
414 self.sort_where_bounds(&mut bounds_vec);
416 Some(WherePredicate::BoundPredicate { ty, bounds: bounds_vec })
419 lifetime_to_bounds.into_iter().filter(|&(_, ref bounds)| !bounds.is_empty()).map(
420 |(lifetime, bounds)| {
421 let mut bounds_vec = bounds.into_iter().collect();
422 self.sort_where_bounds(&mut bounds_vec);
423 WherePredicate::RegionPredicate { lifetime, bounds: bounds_vec }
430 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
431 // display on the docs page. Cleaning the Predicates produces sub-optimal `WherePredicate`s,
432 // so we fix them up:
434 // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug'
435 // becomes 'T: Copy + Debug'
436 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
437 // K', we use the dedicated syntax 'T: Fn() -> K'
438 // * We explicitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
439 fn param_env_to_generics(
442 param_env_def_id: DefId,
443 param_env: ty::ParamEnv<'tcx>,
444 mut existing_predicates: Vec<WherePredicate>,
445 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
448 "param_env_to_generics(param_env_def_id={:?}, param_env={:?}, \
449 existing_predicates={:?})",
450 param_env_def_id, param_env, existing_predicates
453 // The `Sized` trait must be handled specially, since we only display it when
454 // it is *not* required (i.e., '?Sized')
455 let sized_trait = self.cx.tcx.require_lang_item(LangItem::Sized, None);
457 let mut replacer = RegionReplacer { vid_to_region: &vid_to_region, tcx };
459 let orig_bounds: FxHashSet<_> =
460 self.cx.tcx.param_env(param_env_def_id).caller_bounds().iter().collect();
461 let clean_where_predicates = param_env
465 !orig_bounds.contains(p)
466 || match p.skip_binders() {
467 ty::PredicateAtom::Trait(pred, _) => pred.def_id() == sized_trait,
472 let replaced = p.fold_with(&mut replacer);
473 (replaced, replaced.clean(self.cx))
476 let mut generic_params =
477 (tcx.generics_of(param_env_def_id), tcx.explicit_predicates_of(param_env_def_id))
482 "param_env_to_generics({:?}): generic_params={:?}",
483 param_env_def_id, generic_params
486 let mut has_sized = FxHashSet::default();
487 let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
488 let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
489 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = Default::default();
491 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = Default::default();
493 for (orig_p, p) in clean_where_predicates {
499 WherePredicate::BoundPredicate { ty, mut bounds } => {
500 // Writing a projection trait bound of the form
501 // <T as Trait>::Name : ?Sized
502 // is illegal, because ?Sized bounds can only
503 // be written in the (here, nonexistent) definition
505 // Therefore, we make sure that we never add a ?Sized
506 // bound for projections
507 if let Type::QPath { .. } = ty {
508 has_sized.insert(ty.clone());
511 if bounds.is_empty() {
515 let mut for_generics = self.extract_for_generics(tcx, orig_p);
517 assert!(bounds.len() == 1);
518 let mut b = bounds.pop().expect("bounds were empty");
520 if b.is_sized_bound(self.cx) {
521 has_sized.insert(ty.clone());
527 .map(|bounds| bounds.contains(&strip_type(t.clone())))
531 // If we've already added a projection bound for the same type, don't add
532 // this, as it would be a duplicate
534 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
535 // as we want to combine them with any 'Output' qpaths
538 let is_fn = match &mut b {
539 &mut GenericBound::TraitBound(ref mut p, _) => {
540 // Insert regions into the for_generics hash map first, to ensure
541 // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
542 for_generics.extend(p.generic_params.clone());
543 p.generic_params = for_generics.into_iter().collect();
544 self.is_fn_ty(tcx, &p.trait_)
549 let poly_trait = b.get_poly_trait().expect("Cannot get poly trait");
554 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
555 .or_insert(((Some(poly_trait.clone())), None));
557 ty_to_bounds.entry(ty.clone()).or_default();
559 ty_to_bounds.entry(ty.clone()).or_default().insert(b.clone());
563 WherePredicate::RegionPredicate { lifetime, bounds } => {
564 lifetime_to_bounds.entry(lifetime).or_default().extend(bounds);
566 WherePredicate::EqPredicate { lhs, rhs } => {
568 Type::QPath { name: left_name, ref self_type, ref trait_ } => {
569 let ty = &*self_type;
572 path: ref trait_path,
577 let mut new_trait_path = trait_path.clone();
579 if self.is_fn_ty(tcx, trait_) && left_name == sym::Output {
582 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
583 .or_insert((None, Some(rhs)));
587 let args = &mut new_trait_path
590 .expect("segments were empty")
594 // Convert something like '<T as Iterator::Item> = u8'
595 // to 'T: Iterator<Item=u8>'
596 GenericArgs::AngleBracketed {
599 bindings.push(TypeBinding {
601 kind: TypeBindingKind::Equality { ty: rhs },
604 GenericArgs::Parenthesized { .. } => {
605 existing_predicates.push(WherePredicate::EqPredicate {
609 continue; // If something other than a Fn ends up
610 // with parenthesis, leave it alone
614 let bounds = ty_to_bounds.entry(*ty.clone()).or_default();
616 bounds.insert(GenericBound::TraitBound(
618 trait_: Type::ResolvedPath {
619 path: new_trait_path,
620 param_names: param_names.clone(),
622 is_generic: *is_generic,
624 generic_params: Vec::new(),
626 hir::TraitBoundModifier::None,
629 // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
630 // that we don't see a
631 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
633 bounds.remove(&GenericBound::TraitBound(
635 trait_: *trait_.clone(),
636 generic_params: Vec::new(),
638 hir::TraitBoundModifier::None,
640 // Avoid creating any new duplicate bounds later in the outer
645 .insert(*trait_.clone());
648 "Unexpected trait {:?} for {:?}",
649 trait_, param_env_def_id,
653 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, param_env_def_id),
659 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
661 existing_predicates.extend(final_bounds);
663 for param in generic_params.iter_mut() {
665 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
666 // We never want something like `impl<T=Foo>`.
668 let generic_ty = Type::Generic(param.name);
669 if !has_sized.contains(&generic_ty) {
670 bounds.insert(0, GenericBound::maybe_sized(self.cx));
673 GenericParamDefKind::Lifetime => {}
674 GenericParamDefKind::Const { .. } => {}
678 self.sort_where_predicates(&mut existing_predicates);
680 Generics { params: generic_params, where_predicates: existing_predicates }
683 // Ensure that the predicates are in a consistent order. The precise
684 // ordering doesn't actually matter, but it's important that
685 // a given set of predicates always appears in the same order -
686 // both for visual consistency between 'rustdoc' runs, and to
687 // make writing tests much easier
689 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
690 // We should never have identical bounds - and if we do,
691 // they're visually identical as well. Therefore, using
692 // an unstable sort is fine.
693 self.unstable_debug_sort(&mut predicates);
696 // Ensure that the bounds are in a consistent order. The precise
697 // ordering doesn't actually matter, but it's important that
698 // a given set of bounds always appears in the same order -
699 // both for visual consistency between 'rustdoc' runs, and to
700 // make writing tests much easier
702 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
703 // We should never have identical bounds - and if we do,
704 // they're visually identical as well. Therefore, using
705 // an unstable sort is fine.
706 self.unstable_debug_sort(&mut bounds);
709 // This might look horrendously hacky, but it's actually not that bad.
711 // For performance reasons, we use several different FxHashMaps
712 // in the process of computing the final set of where predicates.
713 // However, the iteration order of a HashMap is completely unspecified.
714 // In fact, the iteration of an FxHashMap can even vary between platforms,
715 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
717 // Obviously, it's extremely undesirable for documentation rendering
718 // to be dependent on the platform it's run on. Apart from being confusing
719 // to end users, it makes writing tests much more difficult, as predicates
720 // can appear in any order in the final result.
722 // To solve this problem, we sort WherePredicates and GenericBounds
723 // by their Debug string. The thing to keep in mind is that we don't really
724 // care what the final order is - we're synthesizing an impl or bound
725 // ourselves, so any order can be considered equally valid. By sorting the
726 // predicates and bounds, however, we ensure that for a given codebase, all
727 // auto-trait impls always render in exactly the same way.
729 // Using the Debug implementation for sorting prevents us from needing to
730 // write quite a bit of almost entirely useless code (e.g., how should two
731 // Types be sorted relative to each other). It also allows us to solve the
732 // problem for both WherePredicates and GenericBounds at the same time. This
733 // approach is probably somewhat slower, but the small number of items
734 // involved (impls rarely have more than a few bounds) means that it
735 // shouldn't matter in practice.
736 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
737 vec.sort_by_cached_key(|x| format!("{:?}", x))
740 fn is_fn_ty(&self, tcx: TyCtxt<'_>, ty: &Type) -> bool {
742 &Type::ResolvedPath { did, .. } => {
743 did == tcx.require_lang_item(LangItem::Fn, None)
744 || did == tcx.require_lang_item(LangItem::FnMut, None)
745 || did == tcx.require_lang_item(LangItem::FnOnce, None)
752 // Replaces all ReVars in a type with ty::Region's, using the provided map
753 struct RegionReplacer<'a, 'tcx> {
754 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
758 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
759 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
763 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
765 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
768 .unwrap_or_else(|| r.super_fold_with(self))