simplify.rs 5.3 KB
Newer Older
A
Alexander Regueiro 已提交
1
//! Simplification of where-clauses and parameter bounds into a prettier and
2 3
//! more canonical form.
//!
M
Mazdak Farrokhzad 已提交
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
A
Alexander Regueiro 已提交
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
A
Alexander Regueiro 已提交
8
//! is that the AST predicate of: `where T: Trait<Foo = Bar>` is encoded as:
M
Mark Simulacrum 已提交
9
//! `where T: Trait, <T as Trait>::Foo = Bar`.
10 11 12 13
//!
//! This module attempts to reconstruct the original where and/or parameter
//! bounds by special casing scenarios such as these. Fun!

14
use rustc_data_structures::fx::FxIndexMap;
15
use rustc_hir::def_id::DefId;
M
Mazdak Farrokhzad 已提交
16
use rustc_middle::ty;
17
use rustc_span::Symbol;
18

M
Mark Rousskov 已提交
19
use crate::clean;
20 21 22
use crate::clean::GenericArgs as PP;
use crate::clean::WherePredicate as WP;
use crate::core::DocContext;
23

24
crate fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
25 26 27 28 29
    // First, partition the where clause into its separate components.
    //
    // We use `FxIndexMap` so that the insertion order is preserved to prevent messing up to
    // the order of the generated bounds.
    let mut params: FxIndexMap<Symbol, (Vec<_>, Vec<_>)> = FxIndexMap::default();
30 31 32
    let mut lifetimes = Vec::new();
    let mut equalities = Vec::new();
    let mut tybounds = Vec::new();
33

34 35
    for clause in clauses {
        match clause {
36 37 38 39 40 41 42
            WP::BoundPredicate { ty, bounds, bound_params } => match ty {
                clean::Generic(s) => {
                    let (b, p) = params.entry(s).or_default();
                    b.extend(bounds);
                    p.extend(bound_params);
                }
                t => tybounds.push((t, (bounds, bound_params))),
M
Mark Rousskov 已提交
43
            },
44 45 46 47 48 49 50 51 52 53
            WP::RegionPredicate { lifetime, bounds } => {
                lifetimes.push((lifetime, bounds));
            }
            WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
        }
    }

    // Look for equality predicates on associated types that can be merged into
    // general bound predicates
    equalities.retain(|&(ref lhs, ref rhs)| {
E
est31 已提交
54
        let Some((self_, trait_did, name)) = lhs.projection() else {
55
            return true;
56
        };
57 58
        let generic = match self_ {
            clean::Generic(s) => s,
59 60
            _ => return true,
        };
61
        let (bounds, _) = match params.get_mut(generic) {
62 63 64
            Some(bound) => bound,
            None => return true,
        };
65 66

        merge_bounds(cx, bounds, trait_did, name, rhs)
67 68 69 70
    });

    // And finally, let's reassemble everything
    let mut clauses = Vec::new();
M
Mark Rousskov 已提交
71 72 73
    clauses.extend(
        lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
    );
74 75 76 77 78 79 80 81 82 83
    clauses.extend(params.into_iter().map(|(k, (bounds, params))| WP::BoundPredicate {
        ty: clean::Generic(k),
        bounds,
        bound_params: params,
    }));
    clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
        ty,
        bounds,
        bound_params,
    }));
M
Mark Rousskov 已提交
84
    clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs }));
85 86 87
    clauses
}

88
crate fn merge_bounds(
89 90 91
    cx: &clean::DocContext<'_>,
    bounds: &mut Vec<clean::GenericBound>,
    trait_did: DefId,
92
    assoc: clean::PathSegment,
K
kadmin 已提交
93
    rhs: &clean::Term,
94 95 96 97 98 99 100 101 102
) -> bool {
    !bounds.iter_mut().any(|b| {
        let trait_ref = match *b {
            clean::GenericBound::TraitBound(ref mut tr, _) => tr,
            clean::GenericBound::Outlives(..) => return false,
        };
        // If this QPath's trait `trait_did` is the same as, or a supertrait
        // of, the bound's trait `did` then we can keep going, otherwise
        // this is just a plain old equality bound.
103
        if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
M
Mark Rousskov 已提交
104
            return false;
105
        }
106
        let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
107 108 109
        match last.args {
            PP::AngleBracketed { ref mut bindings, .. } => {
                bindings.push(clean::TypeBinding {
110
                    assoc: assoc.clone(),
K
kadmin 已提交
111
                    kind: clean::TypeBindingKind::Equality { term: rhs.clone() },
112 113
                });
            }
114
            PP::Parenthesized { ref mut output, .. } => match output {
K
kadmin 已提交
115
                Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
M
Mark Rousskov 已提交
116
                None => {
K
kadmin 已提交
117 118
                    if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
                        *output = Some(Box::new(rhs.ty().unwrap().clone()));
M
Mark Rousskov 已提交
119
                    }
120
                }
M
Mark Rousskov 已提交
121
            },
122 123 124 125 126
        };
        true
    })
}

M
Mark Rousskov 已提交
127
fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
128
    if child == trait_ {
M
Mark Rousskov 已提交
129
        return true;
130
    }
131
    let predicates = cx.tcx.super_predicates_of(child);
132
    debug_assert!(cx.tcx.generics_of(child).has_self);
133
    let self_ty = cx.tcx.types.self_param;
M
Mark Rousskov 已提交
134 135 136 137
    predicates
        .predicates
        .iter()
        .filter_map(|(pred, _)| {
D
Deadbeef 已提交
138
            if let ty::PredicateKind::Trait(pred) = pred.kind().skip_binder() {
B
rustdoc  
Bastian Kauschke 已提交
139
                if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None }
140 141
            } else {
                None
142
            }
M
Mark Rousskov 已提交
143 144
        })
        .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
145
}