]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/simplify.rs
Auto merge of #102627 - matthiaskrgr:rollup-2xtrqkw, r=matthiaskrgr
[rust.git] / src / librustdoc / clean / simplify.rs
1 //! Simplification of where-clauses and parameter bounds into a prettier and
2 //! more canonical form.
3 //!
4 //! Currently all cross-crate-inlined function use `rustc_middle::ty` to reconstruct
5 //! the AST (e.g., see all of `clean::inline`), but this is not always a
6 //! non-lossy transformation. The current format of storage for where-clauses
7 //! for functions and such is simply a list of predicates. One example of this
8 //! is that the AST predicate of: `where T: Trait<Foo = Bar>` is encoded as:
9 //! `where T: Trait, <T as Trait>::Foo = Bar`.
10 //!
11 //! This module attempts to reconstruct the original where and/or parameter
12 //! bounds by special casing scenarios such as these. Fun!
13
14 use rustc_data_structures::fx::FxIndexMap;
15 use rustc_hir::def_id::DefId;
16 use rustc_middle::ty;
17
18 use crate::clean;
19 use crate::clean::GenericArgs as PP;
20 use crate::clean::WherePredicate as WP;
21 use crate::core::DocContext;
22
23 pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
24     // First, partition the where clause into its separate components.
25     //
26     // We use `FxIndexMap` so that the insertion order is preserved to prevent messing up to
27     // the order of the generated bounds.
28     let mut tybounds = FxIndexMap::default();
29     let mut lifetimes = Vec::new();
30     let mut equalities = Vec::new();
31
32     for clause in clauses {
33         match clause {
34             WP::BoundPredicate { ty, bounds, bound_params } => {
35                 let (b, p): &mut (Vec<_>, Vec<_>) = tybounds.entry(ty).or_default();
36                 b.extend(bounds);
37                 p.extend(bound_params);
38             }
39             WP::RegionPredicate { lifetime, bounds } => {
40                 lifetimes.push((lifetime, bounds));
41             }
42             WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
43         }
44     }
45
46     // Look for equality predicates on associated types that can be merged into
47     // general bound predicates.
48     equalities.retain(|&(ref lhs, ref rhs)| {
49         let Some((ty, trait_did, name)) = lhs.projection() else { return true; };
50         // FIXME(fmease): We don't handle HRTBs correctly here.
51         //                Pass `_bound_params` (higher-rank lifetimes) to a modified version of
52         //                `merge_bounds`. That vector is currently always empty though since we
53         //                don't keep track of late-bound lifetimes when cleaning projection
54         //                predicates to cleaned equality predicates while we should first query
55         //                them with `collect_referenced_late_bound_regions` and then store them
56         //                (or something similar). For prior art, see `clean::auto_trait`.
57         let Some((bounds, _bound_params)) = tybounds.get_mut(ty) else { return true };
58         merge_bounds(cx, bounds, trait_did, name, rhs)
59     });
60
61     // And finally, let's reassemble everything
62     let mut clauses = Vec::new();
63     clauses.extend(
64         lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
65     );
66     clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
67         ty,
68         bounds,
69         bound_params,
70     }));
71     clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs }));
72     clauses
73 }
74
75 pub(crate) fn merge_bounds(
76     cx: &clean::DocContext<'_>,
77     bounds: &mut Vec<clean::GenericBound>,
78     trait_did: DefId,
79     assoc: clean::PathSegment,
80     rhs: &clean::Term,
81 ) -> bool {
82     !bounds.iter_mut().any(|b| {
83         let trait_ref = match *b {
84             clean::GenericBound::TraitBound(ref mut tr, _) => tr,
85             clean::GenericBound::Outlives(..) => return false,
86         };
87         // If this QPath's trait `trait_did` is the same as, or a supertrait
88         // of, the bound's trait `did` then we can keep going, otherwise
89         // this is just a plain old equality bound.
90         if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
91             return false;
92         }
93         let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
94         match last.args {
95             PP::AngleBracketed { ref mut bindings, .. } => {
96                 bindings.push(clean::TypeBinding {
97                     assoc: assoc.clone(),
98                     kind: clean::TypeBindingKind::Equality { term: rhs.clone() },
99                 });
100             }
101             PP::Parenthesized { ref mut output, .. } => match output {
102                 Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
103                 None => {
104                     if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
105                         *output = Some(Box::new(rhs.ty().unwrap().clone()));
106                     }
107                 }
108             },
109         };
110         true
111     })
112 }
113
114 fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
115     if child == trait_ {
116         return true;
117     }
118     let predicates = cx.tcx.super_predicates_of(child);
119     debug_assert!(cx.tcx.generics_of(child).has_self);
120     let self_ty = cx.tcx.types.self_param;
121     predicates
122         .predicates
123         .iter()
124         .filter_map(|(pred, _)| {
125             if let ty::PredicateKind::Trait(pred) = pred.kind().skip_binder() {
126                 if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None }
127             } else {
128                 None
129             }
130         })
131         .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
132 }