1 use rustc::traits::auto_trait::{self, AutoTraitResult};
2 use rustc::ty::{self, Region, RegionVid, TypeFoldable};
3 use rustc_data_structures::fx::FxHashSet;
10 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
11 enum RegionTarget<'tcx> {
16 #[derive(Default, Debug, Clone)]
17 struct RegionDeps<'tcx> {
18 larger: FxHashSet<RegionTarget<'tcx>>,
19 smaller: FxHashSet<RegionTarget<'tcx>>,
22 pub struct AutoTraitFinder<'a, 'tcx> {
23 pub cx: &'a core::DocContext<'tcx>,
24 pub f: auto_trait::AutoTraitFinder<'tcx>,
27 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
28 pub fn new(cx: &'a core::DocContext<'tcx>) -> Self {
29 let f = auto_trait::AutoTraitFinder::new(cx.tcx);
31 AutoTraitFinder { cx, f }
34 // FIXME(eddyb) figure out a better way to pass information about
35 // parametrization of `ty` than `param_env_def_id`.
36 pub fn get_auto_trait_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> {
37 let param_env = self.cx.tcx.param_env(param_env_def_id);
39 debug!("get_auto_trait_impls({:?})", ty);
40 let auto_traits = self.cx.auto_traits.iter().cloned();
42 .filter_map(|trait_def_id| {
43 let trait_ref = ty::TraitRef {
45 substs: self.cx.tcx.mk_substs_trait(ty, &[]),
47 if !self.cx.generated_synthetics.borrow_mut().insert((ty, trait_def_id)) {
48 debug!("get_auto_trait_impl_for({:?}): already generated, aborting", trait_ref);
53 self.f.find_auto_trait_generics(ty, param_env, trait_def_id, |infcx, info| {
54 let region_data = info.region_data;
59 .generics_of(param_env_def_id)
62 .filter_map(|param| match param.kind {
63 ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
66 .map(|name| (name.clone(), Lifetime(name)))
68 let lifetime_predicates = self.handle_lifetimes(®ion_data, &names_map);
69 let new_generics = self.param_env_to_generics(
78 "find_auto_trait_generics(param_env_def_id={:?}, trait_def_id={:?}): \
80 param_env_def_id, trait_def_id, new_generics
87 let new_generics = match result {
88 AutoTraitResult::PositiveImpl(new_generics) => {
92 AutoTraitResult::NegativeImpl => {
93 polarity = Some(ImplPolarity::Negative);
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.
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.
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`.
108 self.cx.tcx.generics_of(param_env_def_id),
109 ty::GenericPredicates::default(),
114 Generics { params, where_predicates: Vec::new() }
116 AutoTraitResult::ExplicitImpl => return None,
120 source: Span::empty(),
122 attrs: Default::default(),
123 visibility: Inherited,
124 def_id: self.cx.next_def_id(param_env_def_id.krate),
127 inner: ImplItem(Impl {
128 unsafety: hir::Unsafety::Normal,
129 generics: new_generics,
130 provided_trait_methods: Default::default(),
131 trait_: Some(trait_ref.clean(self.cx).get_trait_type().unwrap()),
132 for_: ty.clean(self.cx),
146 names_map: &FxHashMap<String, Lifetime>,
148 self.region_name(region)
150 names_map.get(&name).unwrap_or_else(|| {
151 panic!("Missing lifetime with name {:?} for {:?}", name, region)
154 .unwrap_or(&Lifetime::statik())
158 fn region_name(&self, region: Region<'_>) -> Option<String> {
160 &ty::ReEarlyBound(r) => Some(r.name.to_string()),
165 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
166 // and region constraints of the form ReVar: 'a
168 // This is essentially a simplified version of lexical_region_resolve. However,
169 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
170 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
171 // with determining if a given set up constraints/predicates *are* met, given some
172 // starting conditions (e.g., user-provided code). For this reason, it's easier
173 // to perform the calculations we need on our own, rather than trying to make
174 // existing inference/solver code do what we want.
175 fn handle_lifetimes<'cx>(
177 regions: &RegionConstraintData<'cx>,
178 names_map: &FxHashMap<String, Lifetime>,
179 ) -> Vec<WherePredicate> {
180 // Our goal is to 'flatten' the list of constraints by eliminating
181 // all intermediate RegionVids. At the end, all constraints should
182 // be between Regions (aka region variables). This gives us the information
183 // we need to create the Generics.
184 let mut finished: FxHashMap<_, Vec<_>> = Default::default();
186 let mut vid_map: FxHashMap<RegionTarget<'_>, RegionDeps<'_>> = Default::default();
188 // Flattening is done in two parts. First, we insert all of the constraints
189 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
190 // to its smaller and larger regions. Note that 'larger' regions correspond
191 // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
192 for constraint in regions.constraints.keys() {
194 &Constraint::VarSubVar(r1, r2) => {
196 let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
197 deps1.larger.insert(RegionTarget::RegionVid(r2));
200 let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
201 deps2.smaller.insert(RegionTarget::RegionVid(r1));
203 &Constraint::RegSubVar(region, vid) => {
204 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
205 deps.smaller.insert(RegionTarget::Region(region));
207 &Constraint::VarSubReg(vid, region) => {
208 let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
209 deps.larger.insert(RegionTarget::Region(region));
211 &Constraint::RegSubReg(r1, r2) => {
212 // The constraint is already in the form that we want, so we're done with it
213 // Desired order is 'larger, smaller', so flip then
214 if self.region_name(r1) != self.region_name(r2) {
216 .entry(self.region_name(r2).expect("no region_name found"))
224 // Here, we 'flatten' the map one element at a time.
225 // All of the element's sub and super regions are connected
226 // to each other. For example, if we have a graph that looks like this:
228 // (A, B) - C - (D, E)
229 // Where (A, B) are subregions, and (D,E) are super-regions
231 // then after deleting 'C', the graph will look like this:
232 // ... - A - (D, E ...)
233 // ... - B - (D, E, ...)
234 // (A, B, ...) - D - ...
235 // (A, B, ...) - E - ...
237 // where '...' signifies the existing sub and super regions of an entry
238 // When two adjacent ty::Regions are encountered, we've computed a final
239 // constraint, and add it to our list. Since we make sure to never re-add
240 // deleted items, this process will always finish.
241 while !vid_map.is_empty() {
242 let target = *vid_map.keys().next().expect("Keys somehow empty");
243 let deps = vid_map.remove(&target).expect("Entry somehow missing");
245 for smaller in deps.smaller.iter() {
246 for larger in deps.larger.iter() {
247 match (smaller, larger) {
248 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
249 if self.region_name(r1) != self.region_name(r2) {
251 .entry(self.region_name(r2).expect("no region name found"))
253 .push(r1) // Larger, smaller
256 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
257 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
258 let smaller_deps = v.into_mut();
259 smaller_deps.larger.insert(*larger);
260 smaller_deps.larger.remove(&target);
263 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
264 if let Entry::Occupied(v) = vid_map.entry(*larger) {
265 let deps = v.into_mut();
266 deps.smaller.insert(*smaller);
267 deps.smaller.remove(&target);
270 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
271 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
272 let smaller_deps = v.into_mut();
273 smaller_deps.larger.insert(*larger);
274 smaller_deps.larger.remove(&target);
277 if let Entry::Occupied(v) = vid_map.entry(*larger) {
278 let larger_deps = v.into_mut();
279 larger_deps.smaller.insert(*smaller);
280 larger_deps.smaller.remove(&target);
288 let lifetime_predicates = names_map
290 .flat_map(|(name, lifetime)| {
291 let empty = Vec::new();
292 let bounds: FxHashSet<GenericBound> = finished
296 .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
299 if bounds.is_empty() {
302 Some(WherePredicate::RegionPredicate {
303 lifetime: lifetime.clone(),
304 bounds: bounds.into_iter().collect(),
312 fn extract_for_generics(
315 pred: ty::Predicate<'tcx>,
316 ) -> FxHashSet<GenericParamDef> {
319 let mut regions = FxHashSet::default();
320 tcx.collect_regions(&t, &mut regions);
322 regions.into_iter().flat_map(|r| {
324 // We only care about late bound regions, as we need to add them
325 // to the 'for<>' section
326 &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
327 Some(GenericParamDef {
328 name: name.to_string(),
329 kind: GenericParamDefKind::Lifetime,
332 &ty::ReVar(_) | &ty::ReEarlyBound(_) | &ty::ReStatic => None,
333 _ => panic!("Unexpected region type {:?}", r),
340 fn make_final_bounds(
342 ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
343 ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
344 lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
345 ) -> Vec<WherePredicate> {
348 .flat_map(|(ty, mut bounds)| {
349 if let Some(data) = ty_to_fn.get(&ty) {
350 let (poly_trait, output) =
351 (data.0.as_ref().expect("as_ref failed").clone(), data.1.as_ref().cloned());
352 let new_ty = match &poly_trait.trait_ {
353 &Type::ResolvedPath {
359 let mut new_path = path.clone();
361 new_path.segments.pop().expect("segments were empty");
363 let (old_input, old_output) = match last_segment.args {
364 GenericArgs::AngleBracketed { args, .. } => {
367 .filter_map(|arg| match arg {
368 GenericArg::Type(ty) => Some(ty.clone()),
374 GenericArgs::Parenthesized { inputs, output, .. } => {
379 if old_output.is_some() && old_output != output {
381 "Output mismatch for {:?} {:?} {:?}",
382 ty, old_output, data.1
387 GenericArgs::Parenthesized { inputs: old_input, output };
391 .push(PathSegment { name: last_segment.name, args: new_params });
395 param_names: param_names.clone(),
397 is_generic: *is_generic,
400 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
402 bounds.insert(GenericBound::TraitBound(
403 PolyTrait { trait_: new_ty, generic_params: poly_trait.generic_params },
404 hir::TraitBoundModifier::None,
407 if bounds.is_empty() {
411 let mut bounds_vec = bounds.into_iter().collect();
412 self.sort_where_bounds(&mut bounds_vec);
414 Some(WherePredicate::BoundPredicate { ty, bounds: bounds_vec })
417 lifetime_to_bounds.into_iter().filter(|&(_, ref bounds)| !bounds.is_empty()).map(
418 |(lifetime, bounds)| {
419 let mut bounds_vec = bounds.into_iter().collect();
420 self.sort_where_bounds(&mut bounds_vec);
421 WherePredicate::RegionPredicate { lifetime, bounds: bounds_vec }
428 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
429 // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
430 // so we fix them up:
432 // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug'
433 // becomes 'T: Copy + Debug'
434 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
435 // K', we use the dedicated syntax 'T: Fn() -> K'
436 // * We explcitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
437 fn param_env_to_generics(
440 param_env_def_id: DefId,
441 param_env: ty::ParamEnv<'tcx>,
442 mut existing_predicates: Vec<WherePredicate>,
443 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
446 "param_env_to_generics(param_env_def_id={:?}, param_env={:?}, \
447 existing_predicates={:?})",
448 param_env_def_id, param_env, existing_predicates
451 // The `Sized` trait must be handled specially, since we only display it when
452 // it is *not* required (i.e., '?Sized')
453 let sized_trait = self.cx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
455 let mut replacer = RegionReplacer { vid_to_region: &vid_to_region, tcx };
457 let orig_bounds: FxHashSet<_> =
458 self.cx.tcx.param_env(param_env_def_id).caller_bounds.iter().collect();
459 let clean_where_predicates = param_env
463 !orig_bounds.contains(p)
465 &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
470 let replaced = p.fold_with(&mut replacer);
471 (replaced.clone(), replaced.clean(self.cx))
474 let mut generic_params =
475 (tcx.generics_of(param_env_def_id), tcx.explicit_predicates_of(param_env_def_id))
479 let mut has_sized = FxHashSet::default();
480 let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
481 let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
482 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = Default::default();
484 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = Default::default();
486 for (orig_p, p) in clean_where_predicates {
492 WherePredicate::BoundPredicate { ty, mut bounds } => {
493 // Writing a projection trait bound of the form
494 // <T as Trait>::Name : ?Sized
495 // is illegal, because ?Sized bounds can only
496 // be written in the (here, nonexistant) definition
498 // Therefore, we make sure that we never add a ?Sized
499 // bound for projections
501 &Type::QPath { .. } => {
502 has_sized.insert(ty.clone());
507 if bounds.is_empty() {
511 let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
513 assert!(bounds.len() == 1);
514 let mut b = bounds.pop().expect("bounds were empty");
516 if b.is_sized_bound(self.cx) {
517 has_sized.insert(ty.clone());
523 .map(|bounds| bounds.contains(&strip_type(t.clone())))
527 // If we've already added a projection bound for the same type, don't add
528 // this, as it would be a duplicate
530 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
531 // as we want to combine them with any 'Output' qpaths
534 let is_fn = match &mut b {
535 &mut GenericBound::TraitBound(ref mut p, _) => {
536 // Insert regions into the for_generics hash map first, to ensure
537 // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
538 for_generics.extend(p.generic_params.clone());
539 p.generic_params = for_generics.into_iter().collect();
540 self.is_fn_ty(tcx, &p.trait_)
545 let poly_trait = b.get_poly_trait().expect("Cannot get poly trait");
550 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
551 .or_insert(((Some(poly_trait.clone())), None));
553 ty_to_bounds.entry(ty.clone()).or_default();
555 ty_to_bounds.entry(ty.clone()).or_default().insert(b.clone());
559 WherePredicate::RegionPredicate { lifetime, bounds } => {
560 lifetime_to_bounds.entry(lifetime).or_default().extend(bounds);
562 WherePredicate::EqPredicate { lhs, rhs } => {
564 Type::QPath { name: ref left_name, ref self_type, ref trait_ } => {
565 let ty = &*self_type;
568 path: ref trait_path,
573 let mut new_trait_path = trait_path.clone();
575 if self.is_fn_ty(tcx, trait_) && left_name == FN_OUTPUT_NAME {
578 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
579 .or_insert((None, Some(rhs)));
583 let args = &mut new_trait_path
586 .expect("segments were empty")
590 // Convert somethiung like '<T as Iterator::Item> = u8'
591 // to 'T: Iterator<Item=u8>'
592 GenericArgs::AngleBracketed {
595 bindings.push(TypeBinding {
596 name: left_name.clone(),
597 kind: TypeBindingKind::Equality { ty: rhs },
600 GenericArgs::Parenthesized { .. } => {
601 existing_predicates.push(WherePredicate::EqPredicate {
605 continue; // If something other than a Fn ends up
606 // with parenthesis, leave it alone
610 let bounds = ty_to_bounds.entry(*ty.clone()).or_default();
612 bounds.insert(GenericBound::TraitBound(
614 trait_: Type::ResolvedPath {
615 path: new_trait_path,
616 param_names: param_names.clone(),
618 is_generic: *is_generic,
620 generic_params: Vec::new(),
622 hir::TraitBoundModifier::None,
625 // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
626 // that we don't see a
627 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
629 bounds.remove(&GenericBound::TraitBound(
631 trait_: *trait_.clone(),
632 generic_params: Vec::new(),
634 hir::TraitBoundModifier::None,
636 // Avoid creating any new duplicate bounds later in the outer
641 .insert(*trait_.clone());
644 "Unexpected trait {:?} for {:?}",
645 trait_, param_env_def_id,
649 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, param_env_def_id),
655 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
657 existing_predicates.extend(final_bounds);
659 for param in generic_params.iter_mut() {
661 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
662 // We never want something like `impl<T=Foo>`.
664 let generic_ty = Type::Generic(param.name.clone());
665 if !has_sized.contains(&generic_ty) {
666 bounds.insert(0, GenericBound::maybe_sized(self.cx));
669 GenericParamDefKind::Lifetime => {}
670 GenericParamDefKind::Const { .. } => {}
674 self.sort_where_predicates(&mut existing_predicates);
676 Generics { params: generic_params, where_predicates: existing_predicates }
679 // Ensure that the predicates are in a consistent order. The precise
680 // ordering doesn't actually matter, but it's important that
681 // a given set of predicates always appears in the same order -
682 // both for visual consistency between 'rustdoc' runs, and to
683 // make writing tests much easier
685 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
686 // We should never have identical bounds - and if we do,
687 // they're visually identical as well. Therefore, using
688 // an unstable sort is fine.
689 self.unstable_debug_sort(&mut predicates);
692 // Ensure that the bounds are in a consistent order. The precise
693 // ordering doesn't actually matter, but it's important that
694 // a given set of bounds always appears in the same order -
695 // both for visual consistency between 'rustdoc' runs, and to
696 // make writing tests much easier
698 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
699 // We should never have identical bounds - and if we do,
700 // they're visually identical as well. Therefore, using
701 // an unstable sort is fine.
702 self.unstable_debug_sort(&mut bounds);
705 // This might look horrendously hacky, but it's actually not that bad.
707 // For performance reasons, we use several different FxHashMaps
708 // in the process of computing the final set of where predicates.
709 // However, the iteration order of a HashMap is completely unspecified.
710 // In fact, the iteration of an FxHashMap can even vary between platforms,
711 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
713 // Obviously, it's extremely undesirable for documentation rendering
714 // to be depndent on the platform it's run on. Apart from being confusing
715 // to end users, it makes writing tests much more difficult, as predicates
716 // can appear in any order in the final result.
718 // To solve this problem, we sort WherePredicates and GenericBounds
719 // by their Debug string. The thing to keep in mind is that we don't really
720 // care what the final order is - we're synthesizing an impl or bound
721 // ourselves, so any order can be considered equally valid. By sorting the
722 // predicates and bounds, however, we ensure that for a given codebase, all
723 // auto-trait impls always render in exactly the same way.
725 // Using the Debug implementation for sorting prevents us from needing to
726 // write quite a bit of almost entirely useless code (e.g., how should two
727 // Types be sorted relative to each other). It also allows us to solve the
728 // problem for both WherePredicates and GenericBounds at the same time. This
729 // approach is probably somewhat slower, but the small number of items
730 // involved (impls rarely have more than a few bounds) means that it
731 // shouldn't matter in practice.
732 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
733 vec.sort_by_cached_key(|x| format!("{:?}", x))
736 fn is_fn_ty(&self, tcx: TyCtxt<'_>, ty: &Type) -> bool {
738 &&Type::ResolvedPath { ref did, .. } => {
739 *did == tcx.require_lang_item(lang_items::FnTraitLangItem, None)
740 || *did == tcx.require_lang_item(lang_items::FnMutTraitLangItem, None)
741 || *did == tcx.require_lang_item(lang_items::FnOnceTraitLangItem, None)
748 // Replaces all ReVars in a type with ty::Region's, using the provided map
749 struct RegionReplacer<'a, 'tcx> {
750 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
754 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
755 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
759 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
761 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
764 .unwrap_or_else(|| r.super_fold_with(self))