simplify.rs 5.0 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 std::collections::BTreeMap;
15

16
use rustc_hir::def_id::DefId;
M
Mazdak Farrokhzad 已提交
17
use rustc_middle::ty;
18
use rustc_span::Symbol;
19

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

25
crate fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
26
    // First, partition the where clause into its separate components
27
    let mut params: BTreeMap<_, Vec<_>> = BTreeMap::new();
28 29 30
    let mut lifetimes = Vec::new();
    let mut equalities = Vec::new();
    let mut tybounds = Vec::new();
31

32 33
    for clause in clauses {
        match clause {
M
Mark Rousskov 已提交
34 35 36 37
            WP::BoundPredicate { ty, bounds } => match ty {
                clean::Generic(s) => params.entry(s).or_default().extend(bounds),
                t => tybounds.push((t, bounds)),
            },
38 39 40 41 42 43 44 45 46 47
            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)| {
48 49 50 51
        let (self_, trait_did, name) = if let Some(p) = lhs.projection() {
            p
        } else {
            return true;
52
        };
53 54
        let generic = match self_ {
            clean::Generic(s) => s,
55 56 57 58 59 60
            _ => return true,
        };
        let bounds = match params.get_mut(generic) {
            Some(bound) => bound,
            None => return true,
        };
61 62

        merge_bounds(cx, bounds, trait_did, name, rhs)
63 64 65 66
    });

    // And finally, let's reassemble everything
    let mut clauses = Vec::new();
M
Mark Rousskov 已提交
67 68 69 70 71 72 73 74
    clauses.extend(
        lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
    );
    clauses.extend(
        params.into_iter().map(|(k, v)| WP::BoundPredicate { ty: clean::Generic(k), bounds: v }),
    );
    clauses.extend(tybounds.into_iter().map(|(ty, bounds)| WP::BoundPredicate { ty, bounds }));
    clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs }));
75 76 77
    clauses
}

78
crate fn merge_bounds(
79 80 81
    cx: &clean::DocContext<'_>,
    bounds: &mut Vec<clean::GenericBound>,
    trait_did: DefId,
82
    name: Symbol,
83 84 85 86 87 88 89 90
    rhs: &clean::Type,
) -> bool {
    !bounds.iter_mut().any(|b| {
        let trait_ref = match *b {
            clean::GenericBound::TraitBound(ref mut tr, _) => tr,
            clean::GenericBound::Outlives(..) => return false,
        };
        let (did, path) = match trait_ref.trait_ {
M
Mark Rousskov 已提交
91
            clean::ResolvedPath { did, ref mut path, .. } => (did, path),
92 93 94 95 96 97
            _ => 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.
        if !trait_is_same_or_supertrait(cx, did, trait_did) {
M
Mark Rousskov 已提交
98
            return false;
99 100 101 102 103
        }
        let last = path.segments.last_mut().expect("segments were empty");
        match last.args {
            PP::AngleBracketed { ref mut bindings, .. } => {
                bindings.push(clean::TypeBinding {
104
                    name,
M
Mark Rousskov 已提交
105
                    kind: clean::TypeBindingKind::Equality { ty: rhs.clone() },
106 107
                });
            }
108
            PP::Parenthesized { ref mut output, .. } => match output {
109
                Some(o) => assert_eq!(o, rhs),
M
Mark Rousskov 已提交
110 111 112 113
                None => {
                    if *rhs != clean::Type::Tuple(Vec::new()) {
                        *output = Some(rhs.clone());
                    }
114
                }
M
Mark Rousskov 已提交
115
            },
116 117 118 119 120
        };
        true
    })
}

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