simplify.rs 6.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Simplification of where clauses and parameter bounds into a prettier and
//! more canonical form.
//!
14
//! Currently all cross-crate-inlined function use `rustc::ty` to reconstruct
15 16 17
//! the AST (e.g. see all of `clean::inline`), but this is not always a
//! non-lossy transformation. The current format of storage for where clauses
//! for functions and such is simply a list of predicates. One example of this
M
Mark Simulacrum 已提交
18 19
//! is that the AST predicate of: `where T: Trait<Foo=Bar>` is encoded as:
//! `where T: Trait, <T as Trait>::Foo = Bar`.
20 21 22 23 24
//!
//! This module attempts to reconstruct the original where and/or parameter
//! bounds by special casing scenarios such as these. Fun!

use std::mem;
25
use std::collections::BTreeMap;
26

27
use rustc::hir::def_id::DefId;
28
use rustc::ty;
29

30
use clean::GenericArgs as PP;
31
use clean::WherePredicate as WP;
32
use clean;
33
use core::DocContext;
34

35
pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> {
36
    // First, partition the where clause into its separate components
37
    let mut params: BTreeMap<_, Vec<_>> = BTreeMap::new();
38 39 40
    let mut lifetimes = Vec::new();
    let mut equalities = Vec::new();
    let mut tybounds = Vec::new();
41

42 43 44 45
    for clause in clauses {
        match clause {
            WP::BoundPredicate { ty, bounds } => {
                match ty {
46
                    clean::Generic(s) => params.entry(s).or_default()
47 48 49 50 51 52 53 54 55 56 57 58 59 60
                                               .extend(bounds),
                    t => tybounds.push((t, ty_bounds(bounds))),
                }
            }
            WP::RegionPredicate { lifetime, bounds } => {
                lifetimes.push((lifetime, bounds));
            }
            WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
        }
    }

    // Simplify the type parameter bounds on all the generics
    let mut params = params.into_iter().map(|(k, v)| {
        (k, ty_bounds(v))
61
    }).collect::<BTreeMap<_, _>>();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

    // Look for equality predicates on associated types that can be merged into
    // general bound predicates
    equalities.retain(|&(ref lhs, ref rhs)| {
        let (self_, trait_, name) = match *lhs {
            clean::QPath { ref self_type, ref trait_, ref name } => {
                (self_type, trait_, name)
            }
            _ => return true,
        };
        let generic = match **self_ {
            clean::Generic(ref s) => s,
            _ => return true,
        };
        let trait_did = match **trait_ {
            clean::ResolvedPath { did, .. } => did,
            _ => return true,
        };
        let bounds = match params.get_mut(generic) {
            Some(bound) => bound,
            None => return true,
        };
        !bounds.iter_mut().any(|b| {
            let trait_ref = match *b {
V
varkor 已提交
86 87
                clean::GenericBound::TraitBound(ref mut tr, _) => tr,
                clean::GenericBound::Outlives(..) => return false,
88 89 90 91 92
            };
            let (did, path) = match trait_ref.trait_ {
                clean::ResolvedPath { did, ref mut path, ..} => (did, path),
                _ => return false,
            };
93 94 95 96 97 98
            // 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) {
                return false
            }
G
Guillaume Gomez 已提交
99
            let last = path.segments.last_mut().expect("segments were empty");
V
varkor 已提交
100
            match last.args {
101 102 103 104 105 106 107 108
                PP::AngleBracketed { ref mut bindings, .. } => {
                    bindings.push(clean::TypeBinding {
                        name: name.clone(),
                        ty: rhs.clone(),
                    });
                }
                PP::Parenthesized { ref mut output, .. } => {
                    assert!(output.is_none());
109 110 111
                    if *rhs != clean::Type::Tuple(Vec::new()) {
                        *output = Some(rhs.clone());
                    }
112
                }
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
            };
            true
        })
    });

    // And finally, let's reassemble everything
    let mut clauses = Vec::new();
    clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| {
        WP::RegionPredicate { lifetime: lt, bounds: 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: ty, bounds: bounds }
    }));
    clauses.extend(equalities.into_iter().map(|(lhs, rhs)| {
        WP::EqPredicate { lhs: lhs, rhs: rhs }
    }));
    clauses
}

138
pub fn ty_params(mut params: Vec<clean::GenericParamDef>) -> Vec<clean::GenericParamDef> {
139
    for param in &mut params {
140 141 142 143 144 145
        match param.kind {
            clean::GenericParamDefKind::Type { ref mut bounds, .. } => {
                *bounds = ty_bounds(mem::replace(bounds, Vec::new()));
            }
            _ => panic!("expected only type parameters"),
        }
146
    }
C
Corey Farwell 已提交
147
    params
148 149
}

V
varkor 已提交
150
fn ty_bounds(bounds: Vec<clean::GenericBound>) -> Vec<clean::GenericBound> {
151 152
    bounds
}
153

N
Niko Matsakis 已提交
154 155
fn trait_is_same_or_supertrait(cx: &DocContext, child: DefId,
                               trait_: DefId) -> bool {
156 157 158
    if child == trait_ {
        return true
    }
159
    let predicates = cx.tcx.super_predicates_of(child).predicates;
160
    predicates.iter().filter_map(|(pred, _)| {
161
        if let ty::Predicate::Trait(ref pred) = *pred {
162
            if pred.skip_binder().trait_ref.self_ty().is_self() {
163 164 165
                Some(pred.def_id())
            } else {
                None
166
            }
167 168
        } else {
            None
169
        }
170
    }).any(|did| trait_is_same_or_supertrait(cx, did, trait_))
171
}