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),
127 const_stability: None,
129 kind: ImplItem(Impl {
130 unsafety: hir::Unsafety::Normal,
131 generics: new_generics,
132 provided_trait_methods: Default::default(),
133 trait_: Some(trait_ref.clean(self.cx).get_trait_type().unwrap()),
134 for_: ty.clean(self.cx),
148 names_map: &FxHashMap<Symbol, Lifetime>,
150 self.region_name(region)
152 names_map.get(&name).unwrap_or_else(|| {
153 panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region)
156 .unwrap_or(&Lifetime::statik())
160 fn region_name(&self, region: Region<'_>) -> Option<Symbol> {
162 &ty::ReEarlyBound(r) => Some(r.name),
167 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
168 // and region constraints of the form ReVar: 'a
170 // This is essentially a simplified version of lexical_region_resolve. However,
171 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
172 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
173 // with determining if a given set up constraints/predicates *are* met, given some
174 // starting conditions (e.g., user-provided code). For this reason, it's easier
175 // to perform the calculations we need on our own, rather than trying to make
176 // existing inference/solver code do what we want.
177 fn handle_lifetimes<'cx>(
179 regions: &RegionConstraintData<'cx>,
180 names_map: &FxHashMap<Symbol, Lifetime>,
181 ) -> Vec<WherePredicate> {
182 // Our goal is to 'flatten' the list of constraints by eliminating
183 // all intermediate RegionVids. At the end, all constraints should
184 // be between Regions (aka region variables). This gives us the information
185 // we need to create the Generics.
186 let mut finished: FxHashMap<_, Vec<_>> = Default::default();
188 let mut vid_map: FxHashMap<RegionTarget<'_>, RegionDeps<'_>> = Default::default();
190 // Flattening is done in two parts. First, we insert all of the constraints
191 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
192 // to its smaller and larger regions. Note that 'larger' regions correspond
193 // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
194 for constraint in regions.constraints.keys() {
196 &Constraint::VarSubVar(r1, r2) => {
198 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
199 deps1.larger.insert(RegionTarget::RegionVid(r2));
202 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
203 deps2.smaller.insert(RegionTarget::RegionVid(r1));
205 &Constraint::RegSubVar(region, vid) => {
206 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
207 deps.smaller.insert(RegionTarget::Region(region));
209 &Constraint::VarSubReg(vid, region) => {
210 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
211 deps.larger.insert(RegionTarget::Region(region));
213 &Constraint::RegSubReg(r1, r2) => {
214 // The constraint is already in the form that we want, so we're done with it
215 // Desired order is 'larger, smaller', so flip then
216 if self.region_name(r1) != self.region_name(r2) {
218 .entry(self.region_name(r2).expect("no region_name found"))
226 // Here, we 'flatten' the map one element at a time.
227 // All of the element's sub and super regions are connected
228 // to each other. For example, if we have a graph that looks like this:
230 // (A, B) - C - (D, E)
231 // Where (A, B) are subregions, and (D,E) are super-regions
233 // then after deleting 'C', the graph will look like this:
234 // ... - A - (D, E ...)
235 // ... - B - (D, E, ...)
236 // (A, B, ...) - D - ...
237 // (A, B, ...) - E - ...
239 // where '...' signifies the existing sub and super regions of an entry
240 // When two adjacent ty::Regions are encountered, we've computed a final
241 // constraint, and add it to our list. Since we make sure to never re-add
242 // deleted items, this process will always finish.
243 while !vid_map.is_empty() {
244 let target = *vid_map.keys().next().expect("Keys somehow empty");
245 let deps = vid_map.remove(&target).expect("Entry somehow missing");
247 for smaller in deps.smaller.iter() {
248 for larger in deps.larger.iter() {
249 match (smaller, larger) {
250 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
251 if self.region_name(r1) != self.region_name(r2) {
253 .entry(self.region_name(r2).expect("no region name found"))
255 .push(r1) // Larger, smaller
258 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
259 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
260 let smaller_deps = v.into_mut();
261 smaller_deps.larger.insert(*larger);
262 smaller_deps.larger.remove(&target);
265 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
266 if let Entry::Occupied(v) = vid_map.entry(*larger) {
267 let deps = v.into_mut();
268 deps.smaller.insert(*smaller);
269 deps.smaller.remove(&target);
272 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
273 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
274 let smaller_deps = v.into_mut();
275 smaller_deps.larger.insert(*larger);
276 smaller_deps.larger.remove(&target);
279 if let Entry::Occupied(v) = vid_map.entry(*larger) {
280 let larger_deps = v.into_mut();
281 larger_deps.smaller.insert(*smaller);
282 larger_deps.smaller.remove(&target);
290 let lifetime_predicates = names_map
292 .flat_map(|(name, lifetime)| {
293 let empty = Vec::new();
294 let bounds: FxHashSet<GenericBound> = finished
298 .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
301 if bounds.is_empty() {
304 Some(WherePredicate::RegionPredicate {
305 lifetime: lifetime.clone(),
306 bounds: bounds.into_iter().collect(),
314 fn extract_for_generics(
317 pred: ty::Predicate<'tcx>,
318 ) -> FxHashSet<GenericParamDef> {
319 let bound_predicate = pred.bound_atom();
320 let regions = match bound_predicate.skip_binder() {
321 ty::PredicateAtom::Trait(poly_trait_pred, _) => {
322 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_trait_pred))
324 ty::PredicateAtom::Projection(poly_proj_pred) => {
325 tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_proj_pred))
327 _ => return FxHashSet::default(),
334 // We only care about named late bound regions, as we need to add them
335 // to the 'for<>' section
336 ty::BrNamed(_, name) => {
337 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
345 fn make_final_bounds(
347 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
348 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
349 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
350 ) -> Vec<WherePredicate> {
353 .flat_map(|(ty, mut bounds)| {
354 if let Some(data) = ty_to_fn.get(&ty) {
355 let (poly_trait, output) =
356 (data.0.as_ref().expect("as_ref failed").clone(), data.1.as_ref().cloned());
357 let new_ty = match &poly_trait.trait_ {
358 &Type::ResolvedPath {
364 let mut new_path = path.clone();
366 new_path.segments.pop().expect("segments were empty");
368 let (old_input, old_output) = match last_segment.args {
369 GenericArgs::AngleBracketed { args, .. } => {
372 .filter_map(|arg| match arg {
373 GenericArg::Type(ty) => Some(ty.clone()),
379 GenericArgs::Parenthesized { inputs, output, .. } => {
384 if old_output.is_some() && old_output != output {
386 "Output mismatch for {:?} {:?} {:?}",
387 ty, old_output, data.1
392 GenericArgs::Parenthesized { inputs: old_input, output };
396 .push(PathSegment { name: last_segment.name, args: new_params });
400 param_names: param_names.clone(),
402 is_generic: *is_generic,
405 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
407 bounds.insert(GenericBound::TraitBound(
408 PolyTrait { trait_: new_ty, generic_params: poly_trait.generic_params },
409 hir::TraitBoundModifier::None,
412 if bounds.is_empty() {
416 let mut bounds_vec = bounds.into_iter().collect();
417 self.sort_where_bounds(&mut bounds_vec);
419 Some(WherePredicate::BoundPredicate { ty, bounds: bounds_vec })
422 lifetime_to_bounds.into_iter().filter(|&(_, ref bounds)| !bounds.is_empty()).map(
423 |(lifetime, bounds)| {
424 let mut bounds_vec = bounds.into_iter().collect();
425 self.sort_where_bounds(&mut bounds_vec);
426 WherePredicate::RegionPredicate { lifetime, bounds: bounds_vec }
433 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
434 // display on the docs page. Cleaning the Predicates produces sub-optimal `WherePredicate`s,
435 // so we fix them up:
437 // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug'
438 // becomes 'T: Copy + Debug'
439 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
440 // K', we use the dedicated syntax 'T: Fn() -> K'
441 // * We explicitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
442 fn param_env_to_generics(
445 param_env_def_id: DefId,
446 param_env: ty::ParamEnv<'tcx>,
447 mut existing_predicates: Vec<WherePredicate>,
448 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
451 "param_env_to_generics(param_env_def_id={:?}, param_env={:?}, \
452 existing_predicates={:?})",
453 param_env_def_id, param_env, existing_predicates
456 // The `Sized` trait must be handled specially, since we only display it when
457 // it is *not* required (i.e., '?Sized')
458 let sized_trait = self.cx.tcx.require_lang_item(LangItem::Sized, None);
460 let mut replacer = RegionReplacer { vid_to_region: &vid_to_region, tcx };
462 let orig_bounds: FxHashSet<_> =
463 self.cx.tcx.param_env(param_env_def_id).caller_bounds().iter().collect();
464 let clean_where_predicates = param_env
468 !orig_bounds.contains(p)
469 || match p.skip_binders() {
470 ty::PredicateAtom::Trait(pred, _) => pred.def_id() == sized_trait,
475 let replaced = p.fold_with(&mut replacer);
476 (replaced, replaced.clean(self.cx))
479 let mut generic_params =
480 (tcx.generics_of(param_env_def_id), tcx.explicit_predicates_of(param_env_def_id))
485 "param_env_to_generics({:?}): generic_params={:?}",
486 param_env_def_id, generic_params
489 let mut has_sized = FxHashSet::default();
490 let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
491 let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
492 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = Default::default();
494 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = Default::default();
496 for (orig_p, p) in clean_where_predicates {
502 WherePredicate::BoundPredicate { ty, mut bounds } => {
503 // Writing a projection trait bound of the form
504 // <T as Trait>::Name : ?Sized
505 // is illegal, because ?Sized bounds can only
506 // be written in the (here, nonexistent) definition
508 // Therefore, we make sure that we never add a ?Sized
509 // bound for projections
510 if let Type::QPath { .. } = ty {
511 has_sized.insert(ty.clone());
514 if bounds.is_empty() {
518 let mut for_generics = self.extract_for_generics(tcx, orig_p);
520 assert!(bounds.len() == 1);
521 let mut b = bounds.pop().expect("bounds were empty");
523 if b.is_sized_bound(self.cx) {
524 has_sized.insert(ty.clone());
530 .map(|bounds| bounds.contains(&strip_type(t.clone())))
534 // If we've already added a projection bound for the same type, don't add
535 // this, as it would be a duplicate
537 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
538 // as we want to combine them with any 'Output' qpaths
541 let is_fn = match &mut b {
542 &mut GenericBound::TraitBound(ref mut p, _) => {
543 // Insert regions into the for_generics hash map first, to ensure
544 // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
545 for_generics.extend(p.generic_params.clone());
546 p.generic_params = for_generics.into_iter().collect();
547 self.is_fn_ty(tcx, &p.trait_)
552 let poly_trait = b.get_poly_trait().expect("Cannot get poly trait");
557 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
558 .or_insert(((Some(poly_trait.clone())), None));
560 ty_to_bounds.entry(ty.clone()).or_default();
562 ty_to_bounds.entry(ty.clone()).or_default().insert(b.clone());
566 WherePredicate::RegionPredicate { lifetime, bounds } => {
567 lifetime_to_bounds.entry(lifetime).or_default().extend(bounds);
569 WherePredicate::EqPredicate { lhs, rhs } => {
571 Type::QPath { name: left_name, ref self_type, ref trait_ } => {
572 let ty = &*self_type;
575 path: ref trait_path,
580 let mut new_trait_path = trait_path.clone();
582 if self.is_fn_ty(tcx, trait_) && left_name == sym::Output {
585 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
586 .or_insert((None, Some(rhs)));
590 let args = &mut new_trait_path
593 .expect("segments were empty")
597 // Convert something like '<T as Iterator::Item> = u8'
598 // to 'T: Iterator<Item=u8>'
599 GenericArgs::AngleBracketed {
602 bindings.push(TypeBinding {
603 name: left_name.clone(),
604 kind: TypeBindingKind::Equality { ty: rhs },
607 GenericArgs::Parenthesized { .. } => {
608 existing_predicates.push(WherePredicate::EqPredicate {
612 continue; // If something other than a Fn ends up
613 // with parenthesis, leave it alone
617 let bounds = ty_to_bounds.entry(*ty.clone()).or_default();
619 bounds.insert(GenericBound::TraitBound(
621 trait_: Type::ResolvedPath {
622 path: new_trait_path,
623 param_names: param_names.clone(),
625 is_generic: *is_generic,
627 generic_params: Vec::new(),
629 hir::TraitBoundModifier::None,
632 // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
633 // that we don't see a
634 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
636 bounds.remove(&GenericBound::TraitBound(
638 trait_: *trait_.clone(),
639 generic_params: Vec::new(),
641 hir::TraitBoundModifier::None,
643 // Avoid creating any new duplicate bounds later in the outer
648 .insert(*trait_.clone());
651 "Unexpected trait {:?} for {:?}",
652 trait_, param_env_def_id,
656 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, param_env_def_id),
662 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
664 existing_predicates.extend(final_bounds);
666 for param in generic_params.iter_mut() {
668 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
669 // We never want something like `impl<T=Foo>`.
671 let generic_ty = Type::Generic(param.name.clone());
672 if !has_sized.contains(&generic_ty) {
673 bounds.insert(0, GenericBound::maybe_sized(self.cx));
676 GenericParamDefKind::Lifetime => {}
677 GenericParamDefKind::Const { .. } => {}
681 self.sort_where_predicates(&mut existing_predicates);
683 Generics { params: generic_params, where_predicates: existing_predicates }
686 // Ensure that the predicates are in a consistent order. The precise
687 // ordering doesn't actually matter, but it's important that
688 // a given set of predicates always appears in the same order -
689 // both for visual consistency between 'rustdoc' runs, and to
690 // make writing tests much easier
692 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
693 // We should never have identical bounds - and if we do,
694 // they're visually identical as well. Therefore, using
695 // an unstable sort is fine.
696 self.unstable_debug_sort(&mut predicates);
699 // Ensure that the bounds are in a consistent order. The precise
700 // ordering doesn't actually matter, but it's important that
701 // a given set of bounds always appears in the same order -
702 // both for visual consistency between 'rustdoc' runs, and to
703 // make writing tests much easier
705 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
706 // We should never have identical bounds - and if we do,
707 // they're visually identical as well. Therefore, using
708 // an unstable sort is fine.
709 self.unstable_debug_sort(&mut bounds);
712 // This might look horrendously hacky, but it's actually not that bad.
714 // For performance reasons, we use several different FxHashMaps
715 // in the process of computing the final set of where predicates.
716 // However, the iteration order of a HashMap is completely unspecified.
717 // In fact, the iteration of an FxHashMap can even vary between platforms,
718 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
720 // Obviously, it's extremely undesirable for documentation rendering
721 // to be dependent on the platform it's run on. Apart from being confusing
722 // to end users, it makes writing tests much more difficult, as predicates
723 // can appear in any order in the final result.
725 // To solve this problem, we sort WherePredicates and GenericBounds
726 // by their Debug string. The thing to keep in mind is that we don't really
727 // care what the final order is - we're synthesizing an impl or bound
728 // ourselves, so any order can be considered equally valid. By sorting the
729 // predicates and bounds, however, we ensure that for a given codebase, all
730 // auto-trait impls always render in exactly the same way.
732 // Using the Debug implementation for sorting prevents us from needing to
733 // write quite a bit of almost entirely useless code (e.g., how should two
734 // Types be sorted relative to each other). It also allows us to solve the
735 // problem for both WherePredicates and GenericBounds at the same time. This
736 // approach is probably somewhat slower, but the small number of items
737 // involved (impls rarely have more than a few bounds) means that it
738 // shouldn't matter in practice.
739 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
740 vec.sort_by_cached_key(|x| format!("{:?}", x))
743 fn is_fn_ty(&self, tcx: TyCtxt<'_>, ty: &Type) -> bool {
745 &&Type::ResolvedPath { ref did, .. } => {
746 *did == tcx.require_lang_item(LangItem::Fn, None)
747 || *did == tcx.require_lang_item(LangItem::FnMut, None)
748 || *did == tcx.require_lang_item(LangItem::FnOnce, None)
755 // Replaces all ReVars in a type with ty::Region's, using the provided map
756 struct RegionReplacer<'a, 'tcx> {
757 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
761 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
762 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
766 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
768 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
771 .unwrap_or_else(|| r.super_fold_with(self))