2 use rustc::traits::auto_trait::{self, AutoTraitResult};
3 use rustc::ty::{self, TypeFoldable};
8 pub struct AutoTraitFinder<'a, 'tcx> {
9 pub cx: &'a core::DocContext<'tcx>,
10 pub f: auto_trait::AutoTraitFinder<'a, 'tcx>,
13 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
14 pub fn new(cx: &'a core::DocContext<'tcx>) -> Self {
15 let f = auto_trait::AutoTraitFinder::new(cx.tcx);
17 AutoTraitFinder { cx, f }
20 // FIXME(eddyb) figure out a better way to pass information about
21 // parametrization of `ty` than `param_env_def_id`.
22 pub fn get_auto_trait_impls(
25 param_env_def_id: DefId,
27 let param_env = self.cx.tcx.param_env(param_env_def_id);
29 debug!("get_auto_trait_impls({:?})", ty);
30 let auto_traits = self.cx.send_trait.into_iter().chain(
31 Some(self.cx.tcx.require_lang_item(lang_items::SyncTraitLangItem))
33 auto_traits.filter_map(|trait_def_id| {
34 let trait_ref = ty::TraitRef {
36 substs: self.cx.tcx.mk_substs_trait(ty, &[]),
41 .insert((ty, trait_def_id))
44 "get_auto_trait_impl_for({:?}): already generated, aborting",
50 let result = self.f.find_auto_trait_generics(
55 let region_data = info.region_data;
57 let names_map = self.cx.tcx.generics_of(param_env_def_id)
60 .filter_map(|param| match param.kind {
61 ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
64 .map(|name| (name.clone(), Lifetime(name)))
66 let lifetime_predicates =
67 self.handle_lifetimes(®ion_data, &names_map);
68 let new_generics = self.param_env_to_generics(
77 "find_auto_trait_generics(param_env_def_id={:?}, trait_def_id={:?}): \
79 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`.
107 let params = (self.cx.tcx.generics_of(param_env_def_id), &Default::default())
108 .clean(self.cx).params;
112 where_predicates: Vec::new(),
115 AutoTraitResult::ExplicitImpl => return None,
119 source: Span::empty(),
121 attrs: Default::default(),
123 def_id: self.cx.next_def_id(param_env_def_id.krate),
126 inner: 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),
142 &self, region: Region<'_>,
143 names_map: &FxHashMap<String, Lifetime>
145 self.region_name(region)
147 names_map.get(&name).unwrap_or_else(|| {
148 panic!("Missing lifetime with name {:?} for {:?}", name, region)
151 .unwrap_or(&Lifetime::statik())
155 fn region_name(&self, region: Region<'_>) -> Option<String> {
157 &ty::ReEarlyBound(r) => Some(r.name.to_string()),
162 // This method calculates two things: Lifetime constraints of the form 'a: 'b,
163 // and region constraints of the form ReVar: 'a
165 // This is essentially a simplified version of lexical_region_resolve. However,
166 // handle_lifetimes determines what *needs be* true in order for an impl to hold.
167 // lexical_region_resolve, along with much of the rest of the compiler, is concerned
168 // with determining if a given set up constraints/predicates *are* met, given some
169 // starting conditions (e.g., user-provided code). For this reason, it's easier
170 // to perform the calculations we need on our own, rather than trying to make
171 // existing inference/solver code do what we want.
172 fn handle_lifetimes<'cx>(
174 regions: &RegionConstraintData<'cx>,
175 names_map: &FxHashMap<String, Lifetime>,
176 ) -> Vec<WherePredicate> {
177 // Our goal is to 'flatten' the list of constraints by eliminating
178 // all intermediate RegionVids. At the end, all constraints should
179 // be between Regions (aka region variables). This gives us the information
180 // we need to create the Generics.
181 let mut finished: FxHashMap<_, Vec<_>> = Default::default();
183 let mut vid_map: FxHashMap<RegionTarget<'_>, RegionDeps<'_>> = Default::default();
185 // Flattening is done in two parts. First, we insert all of the constraints
186 // into a map. Each RegionTarget (either a RegionVid or a Region) maps
187 // to its smaller and larger regions. Note that 'larger' regions correspond
188 // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
189 for constraint in regions.constraints.keys() {
191 &Constraint::VarSubVar(r1, r2) => {
194 .entry(RegionTarget::RegionVid(r1))
196 deps1.larger.insert(RegionTarget::RegionVid(r2));
200 .entry(RegionTarget::RegionVid(r2))
202 deps2.smaller.insert(RegionTarget::RegionVid(r1));
204 &Constraint::RegSubVar(region, vid) => {
206 .entry(RegionTarget::RegionVid(vid))
208 deps.smaller.insert(RegionTarget::Region(region));
210 &Constraint::VarSubReg(vid, region) => {
212 .entry(RegionTarget::RegionVid(vid))
214 deps.larger.insert(RegionTarget::Region(region));
216 &Constraint::RegSubReg(r1, r2) => {
217 // The constraint is already in the form that we want, so we're done with it
218 // Desired order is 'larger, smaller', so flip then
219 if self.region_name(r1) != self.region_name(r2) {
221 .entry(self.region_name(r2).expect("no region_name found"))
229 // Here, we 'flatten' the map one element at a time.
230 // All of the element's sub and super regions are connected
231 // to each other. For example, if we have a graph that looks like this:
233 // (A, B) - C - (D, E)
234 // Where (A, B) are subregions, and (D,E) are super-regions
236 // then after deleting 'C', the graph will look like this:
237 // ... - A - (D, E ...)
238 // ... - B - (D, E, ...)
239 // (A, B, ...) - D - ...
240 // (A, B, ...) - E - ...
242 // where '...' signifies the existing sub and super regions of an entry
243 // When two adjacent ty::Regions are encountered, we've computed a final
244 // constraint, and add it to our list. Since we make sure to never re-add
245 // deleted items, this process will always finish.
246 while !vid_map.is_empty() {
247 let target = vid_map.keys().next().expect("Keys somehow empty").clone();
248 let deps = vid_map.remove(&target).expect("Entry somehow missing");
250 for smaller in deps.smaller.iter() {
251 for larger in deps.larger.iter() {
252 match (smaller, larger) {
253 (&RegionTarget::Region(r1), &RegionTarget::Region(r2)) => {
254 if self.region_name(r1) != self.region_name(r2) {
256 .entry(self.region_name(r2).expect("no region name found"))
258 .push(r1) // Larger, smaller
261 (&RegionTarget::RegionVid(_), &RegionTarget::Region(_)) => {
262 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
263 let smaller_deps = v.into_mut();
264 smaller_deps.larger.insert(*larger);
265 smaller_deps.larger.remove(&target);
268 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
269 if let Entry::Occupied(v) = vid_map.entry(*larger) {
270 let deps = v.into_mut();
271 deps.smaller.insert(*smaller);
272 deps.smaller.remove(&target);
275 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
276 if let Entry::Occupied(v) = vid_map.entry(*smaller) {
277 let smaller_deps = v.into_mut();
278 smaller_deps.larger.insert(*larger);
279 smaller_deps.larger.remove(&target);
282 if let Entry::Occupied(v) = vid_map.entry(*larger) {
283 let larger_deps = v.into_mut();
284 larger_deps.smaller.insert(*smaller);
285 larger_deps.smaller.remove(&target);
293 let lifetime_predicates = names_map
295 .flat_map(|(name, lifetime)| {
296 let empty = Vec::new();
297 let bounds: FxHashSet<GenericBound> = finished.get(name).unwrap_or(&empty).iter()
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<'b, 'c, 'd>(
316 tcx: TyCtxt<'b, 'c, 'd>,
317 pred: ty::Predicate<'d>,
318 ) -> FxHashSet<GenericParamDef> {
321 let mut regions = FxHashSet::default();
322 tcx.collect_regions(&t, &mut regions);
324 regions.into_iter().flat_map(|r| {
326 // We only care about late bound regions, as we need to add them
327 // to the 'for<>' section
328 &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
329 Some(GenericParamDef {
330 name: name.to_string(),
331 kind: GenericParamDefKind::Lifetime,
334 &ty::ReVar(_) | &ty::ReEarlyBound(_) | &ty::ReStatic => None,
335 _ => panic!("Unexpected region type {:?}", r),
342 fn make_final_bounds<'b, 'c, 'cx>(
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_ {
355 &Type::ResolvedPath {
361 let mut new_path = path.clone();
362 let last_segment = new_path.segments.pop()
363 .expect("segments were empty");
365 let (old_input, old_output) = match last_segment.args {
366 GenericArgs::AngleBracketed { args, .. } => {
367 let types = args.iter().filter_map(|arg| match arg {
368 GenericArg::Type(ty) => Some(ty.clone()),
373 GenericArgs::Parenthesized { inputs, output, .. } => {
378 if old_output.is_some() && old_output != output {
380 "Output mismatch for {:?} {:?} {:?}",
381 ty, old_output, data.1
385 let new_params = GenericArgs::Parenthesized {
390 new_path.segments.push(PathSegment {
391 name: last_segment.name,
397 param_names: param_names.clone(),
399 is_generic: *is_generic,
402 _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
404 bounds.insert(GenericBound::TraitBound(
407 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 {
427 .filter(|&(_, ref bounds)| !bounds.is_empty())
428 .map(|(lifetime, bounds)| {
429 let mut bounds_vec = bounds.into_iter().collect();
430 self.sort_where_bounds(&mut bounds_vec);
431 WherePredicate::RegionPredicate {
440 // Converts the calculated ParamEnv and lifetime information to a clean::Generics, suitable for
441 // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
442 // so we fix them up:
444 // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug'
445 // becomes 'T: Copy + Debug'
446 // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
447 // K', we use the dedicated syntax 'T: Fn() -> K'
448 // * We explcitly add a '?Sized' bound if we didn't find any 'Sized' predicates for a type
449 fn param_env_to_generics<'b, 'c, 'cx>(
451 tcx: TyCtxt<'b, 'c, 'cx>,
452 param_env_def_id: DefId,
453 param_env: ty::ParamEnv<'cx>,
454 mut existing_predicates: Vec<WherePredicate>,
455 vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
458 "param_env_to_generics(param_env_def_id={:?}, param_env={:?}, \
459 existing_predicates={:?})",
460 param_env_def_id, param_env, existing_predicates
463 // The `Sized` trait must be handled specially, since we only display it when
464 // it is *not* required (i.e., '?Sized')
465 let sized_trait = self.cx
467 .require_lang_item(lang_items::SizedTraitLangItem);
469 let mut replacer = RegionReplacer {
470 vid_to_region: &vid_to_region,
474 let orig_bounds: FxHashSet<_> =
475 self.cx.tcx.param_env(param_env_def_id).caller_bounds.iter().collect();
476 let clean_where_predicates = param_env
480 !orig_bounds.contains(p) || match p {
481 &&ty::Predicate::Trait(pred) => pred.def_id() == sized_trait,
486 let replaced = p.fold_with(&mut replacer);
487 (replaced.clone(), replaced.clean(self.cx))
490 let mut generic_params = (
491 tcx.generics_of(param_env_def_id),
492 &tcx.explicit_predicates_of(param_env_def_id),
493 ).clean(self.cx).params;
495 let mut has_sized = FxHashSet::default();
496 let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
497 let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
498 let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = Default::default();
500 let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = Default::default();
502 for (orig_p, p) in clean_where_predicates {
508 WherePredicate::BoundPredicate { ty, mut bounds } => {
509 // Writing a projection trait bound of the form
510 // <T as Trait>::Name : ?Sized
511 // is illegal, because ?Sized bounds can only
512 // be written in the (here, nonexistant) definition
514 // Therefore, we make sure that we never add a ?Sized
515 // bound for projections
517 &Type::QPath { .. } => {
518 has_sized.insert(ty.clone());
523 if bounds.is_empty() {
527 let mut for_generics = self.extract_for_generics(tcx, orig_p.clone());
529 assert!(bounds.len() == 1);
530 let mut b = bounds.pop().expect("bounds were empty");
532 if b.is_sized_bound(self.cx) {
533 has_sized.insert(ty.clone());
534 } else if !b.get_trait_type()
538 .map(|bounds| bounds.contains(&strip_type(t.clone())))
542 // If we've already added a projection bound for the same type, don't add
543 // this, as it would be a duplicate
545 // Handle any 'Fn/FnOnce/FnMut' bounds specially,
546 // as we want to combine them with any 'Output' qpaths
549 let is_fn = match &mut b {
550 &mut GenericBound::TraitBound(ref mut p, _) => {
551 // Insert regions into the for_generics hash map first, to ensure
552 // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
553 for_generics.extend(p.generic_params.clone());
554 p.generic_params = for_generics.into_iter().collect();
555 self.is_fn_ty(tcx, &p.trait_)
560 let poly_trait = b.get_poly_trait().expect("Cannot get poly trait");
565 .and_modify(|e| *e = (Some(poly_trait.clone()), e.1.clone()))
566 .or_insert(((Some(poly_trait.clone())), None));
579 WherePredicate::RegionPredicate { lifetime, bounds } => {
585 WherePredicate::EqPredicate { lhs, rhs } => {
592 let ty = &*self_type;
595 path: ref trait_path,
600 let mut new_trait_path = trait_path.clone();
602 if self.is_fn_ty(tcx, trait_) && left_name == FN_OUTPUT_NAME {
605 .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))
606 .or_insert((None, Some(rhs)));
610 // FIXME: Remove this scope when NLL lands
613 &mut new_trait_path.segments
615 .expect("segments were empty")
619 // Convert somethiung like '<T as Iterator::Item> = u8'
620 // to 'T: Iterator<Item=u8>'
621 &mut GenericArgs::AngleBracketed {
625 bindings.push(TypeBinding {
626 name: left_name.clone(),
630 &mut GenericArgs::Parenthesized { .. } => {
631 existing_predicates.push(
632 WherePredicate::EqPredicate {
637 continue; // If something other than a Fn ends up
638 // with parenthesis, leave it alone
643 let bounds = ty_to_bounds
647 bounds.insert(GenericBound::TraitBound(
649 trait_: Type::ResolvedPath {
650 path: new_trait_path,
651 param_names: param_names.clone(),
653 is_generic: *is_generic,
655 generic_params: Vec::new(),
657 hir::TraitBoundModifier::None,
660 // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
661 // that we don't see a
662 // duplicate bound like `T: Iterator + Iterator<Item=u8>`
664 bounds.remove(&GenericBound::TraitBound(
666 trait_: *trait_.clone(),
667 generic_params: Vec::new(),
669 hir::TraitBoundModifier::None,
671 // Avoid creating any new duplicate bounds later in the outer
676 .insert(*trait_.clone());
679 "Unexpected trait {:?} for {:?}",
685 _ => panic!("Unexpected LHS {:?} for {:?}", lhs, param_env_def_id),
691 let final_bounds = self.make_final_bounds(ty_to_bounds, ty_to_fn, lifetime_to_bounds);
693 existing_predicates.extend(final_bounds);
695 for param in generic_params.iter_mut() {
697 GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
698 // We never want something like `impl<T=Foo>`.
700 let generic_ty = Type::Generic(param.name.clone());
701 if !has_sized.contains(&generic_ty) {
702 bounds.insert(0, GenericBound::maybe_sized(self.cx));
705 GenericParamDefKind::Lifetime => {}
706 GenericParamDefKind::Const { .. } => {}
710 self.sort_where_predicates(&mut existing_predicates);
713 params: generic_params,
714 where_predicates: existing_predicates,
718 // Ensure that the predicates are in a consistent order. The precise
719 // ordering doesn't actually matter, but it's important that
720 // a given set of predicates always appears in the same order -
721 // both for visual consistency between 'rustdoc' runs, and to
722 // make writing tests much easier
724 fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
725 // We should never have identical bounds - and if we do,
726 // they're visually identical as well. Therefore, using
727 // an unstable sort is fine.
728 self.unstable_debug_sort(&mut predicates);
731 // Ensure that the bounds are in a consistent order. The precise
732 // ordering doesn't actually matter, but it's important that
733 // a given set of bounds always appears in the same order -
734 // both for visual consistency between 'rustdoc' runs, and to
735 // make writing tests much easier
737 fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
738 // We should never have identical bounds - and if we do,
739 // they're visually identical as well. Therefore, using
740 // an unstable sort is fine.
741 self.unstable_debug_sort(&mut bounds);
744 // This might look horrendously hacky, but it's actually not that bad.
746 // For performance reasons, we use several different FxHashMaps
747 // in the process of computing the final set of where predicates.
748 // However, the iteration order of a HashMap is completely unspecified.
749 // In fact, the iteration of an FxHashMap can even vary between platforms,
750 // since FxHasher has different behavior for 32-bit and 64-bit platforms.
752 // Obviously, it's extremely undesirable for documentation rendering
753 // to be depndent on the platform it's run on. Apart from being confusing
754 // to end users, it makes writing tests much more difficult, as predicates
755 // can appear in any order in the final result.
757 // To solve this problem, we sort WherePredicates and GenericBounds
758 // by their Debug string. The thing to keep in mind is that we don't really
759 // care what the final order is - we're synthesizing an impl or bound
760 // ourselves, so any order can be considered equally valid. By sorting the
761 // predicates and bounds, however, we ensure that for a given codebase, all
762 // auto-trait impls always render in exactly the same way.
764 // Using the Debug implementation for sorting prevents us from needing to
765 // write quite a bit of almost entirely useless code (e.g., how should two
766 // Types be sorted relative to each other). It also allows us to solve the
767 // problem for both WherePredicates and GenericBounds at the same time. This
768 // approach is probably somewhat slower, but the small number of items
769 // involved (impls rarely have more than a few bounds) means that it
770 // shouldn't matter in practice.
771 fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
772 vec.sort_by_cached_key(|x| format!("{:?}", x))
775 fn is_fn_ty(&self, tcx: TyCtxt<'_, '_, '_>, ty: &Type) -> bool {
777 &&Type::ResolvedPath { ref did, .. } => {
778 *did == tcx.require_lang_item(lang_items::FnTraitLangItem)
779 || *did == tcx.require_lang_item(lang_items::FnMutTraitLangItem)
780 || *did == tcx.require_lang_item(lang_items::FnOnceTraitLangItem)
787 // Replaces all ReVars in a type with ty::Region's, using the provided map
788 struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
789 vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
790 tcx: TyCtxt<'a, 'gcx, 'tcx>,
793 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
794 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
798 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
800 &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
802 }).unwrap_or_else(|| r.super_fold_with(self))