Skip to content

Commit

Permalink
Clean generic impls code
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Aug 4, 2018
1 parent 579adf8 commit 4aba7de
Show file tree
Hide file tree
Showing 8 changed files with 508 additions and 435 deletions.
163 changes: 41 additions & 122 deletions src/Cargo.lock

Large diffs are not rendered by default.

314 changes: 24 additions & 290 deletions src/librustdoc/clean/auto_trait.rs

Large diffs are not rendered by default.

170 changes: 170 additions & 0 deletions src/librustdoc/clean/blanket_impl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Copyright 2018 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.

use rustc::hir;
use rustc::traits;
use rustc::ty::ToPredicate;
use rustc::ty::subst::Subst;
use rustc::infer::InferOk;
use syntax_pos::DUMMY_SP;

use core::DocAccessLevels;

use super::*;

use self::def_ctor::{get_def_ctor_from_def_id, get_def_ctor_from_node_id};
use self::finder_trait::Finder;

pub struct BlanketImplFinder<'a, 'tcx: 'a, 'rcx: 'a> {
pub cx: &'a core::DocContext<'a, 'tcx, 'rcx>,
}

impl<'a, 'tcx, 'rcx> BlanketImplFinder <'a, 'tcx, 'rcx> {
pub fn new(cx: &'a core::DocContext<'a, 'tcx, 'rcx>) -> Self {
BlanketImplFinder { cx }
}

pub fn get_with_def_id(&self, def_id: DefId) -> Vec<Item> {
get_def_ctor_from_def_id(&self.cx, def_id, &|def_ctor| {
self.get_blanket_impls(def_id, &def_ctor, None)
})
}

pub fn get_with_node_id(&self, id: ast::NodeId, name: String) -> Vec<Item> {
get_def_ctor_from_node_id(&self.cx, id, name, &|def_ctor, name| {
let did = self.cx.tcx.hir.local_def_id(id);
self.get_blanket_impls(did, &def_ctor, Some(name))
})
}

pub fn get_blanket_impls<F>(
&self,
def_id: DefId,
def_ctor: &F,
name: Option<String>,
) -> Vec<Item>
where F: Fn(DefId) -> Def {
let mut impls = Vec::new();
if self.cx
.tcx
.get_attrs(def_id)
.lists("doc")
.has_word("hidden")
{
debug!(
"get_blanket_impls(def_id={:?}, def_ctor=...): item has doc('hidden'), \
aborting",
def_id
);
return impls;
}
if self.cx.access_levels.borrow().is_doc_reachable(def_id) {
let generics = self.cx.tcx.generics_of(def_id);
let ty = self.cx.tcx.type_of(def_id);
let real_name = name.clone().map(|name| Ident::from_str(&name));
let param_env = self.cx.tcx.param_env(def_id);
for &trait_def_id in self.cx.all_traits.iter() {
if !self.cx.access_levels.borrow().is_doc_reachable(trait_def_id) ||
self.cx.generated_synthetics
.borrow_mut()
.get(&(def_id, trait_def_id))
.is_some() {
continue
}
self.cx.tcx.for_each_relevant_impl(trait_def_id, ty, |impl_def_id| {
self.cx.tcx.infer_ctxt().enter(|infcx| {
let t_generics = infcx.tcx.generics_of(impl_def_id);
let trait_ref = infcx.tcx.impl_trait_ref(impl_def_id)
.expect("Cannot get impl trait");

match infcx.tcx.type_of(impl_def_id).sty {
::rustc::ty::TypeVariants::TyParam(_) => {},
_ => return,
}

let substs = infcx.fresh_substs_for_item(DUMMY_SP, def_id);
let ty = ty.subst(infcx.tcx, substs);
let param_env = param_env.subst(infcx.tcx, substs);

let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
let trait_ref = trait_ref.subst(infcx.tcx, impl_substs);

// Require the type the impl is implemented on to match
// our type, and ignore the impl if there was a mismatch.
let cause = traits::ObligationCause::dummy();
let eq_result = infcx.at(&cause, param_env)
.eq(trait_ref.self_ty(), ty);
if let Ok(InferOk { value: (), obligations }) = eq_result {
// FIXME(eddyb) ignoring `obligations` might cause false positives.
drop(obligations);

let may_apply = infcx.predicate_may_hold(&traits::Obligation::new(
cause.clone(),
param_env,
trait_ref.to_predicate(),
));
if !may_apply {
return
}
self.cx.generated_synthetics.borrow_mut()
.insert((def_id, trait_def_id));
let trait_ = hir::TraitRef {
path: get_path_for_type(infcx.tcx,
trait_def_id,
hir::def::Def::Trait),
ref_id: ast::DUMMY_NODE_ID,
};
let provided_trait_methods =
infcx.tcx.provided_trait_methods(trait_def_id)
.into_iter()
.map(|meth| meth.ident.to_string())
.collect();

let ty = self.get_real_ty(def_id, def_ctor, &real_name, generics);
let predicates = infcx.tcx.predicates_of(impl_def_id);

impls.push(Item {
source: infcx.tcx.def_span(impl_def_id).clean(self.cx),
name: None,
attrs: Default::default(),
visibility: None,
def_id: self.next_def_id(impl_def_id.krate),
stability: None,
deprecation: None,
inner: ImplItem(Impl {
unsafety: hir::Unsafety::Normal,
generics: (t_generics, &predicates).clean(self.cx),
provided_trait_methods,
trait_: Some(trait_.clean(self.cx)),
for_: ty.clean(self.cx),
items: infcx.tcx.associated_items(impl_def_id)
.collect::<Vec<_>>()
.clean(self.cx),
polarity: None,
synthetic: false,
blanket_impl: Some(infcx.tcx.type_of(impl_def_id)
.clean(self.cx)),
}),
});
debug!("{:?} => {}", trait_ref, may_apply);
}
});
});
}
}
impls
}
}

impl<'a, 'tcx: 'a, 'rcx: 'a> Finder<'a, 'tcx, 'rcx> for BlanketImplFinder<'a, 'tcx, 'rcx> {
fn get_cx(&self) -> &DocContext<'a, 'tcx, 'rcx> {
&self.cx
}
}
65 changes: 65 additions & 0 deletions src/librustdoc/clean/def_ctor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2018 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.

use core::DocContext;

use super::*;

pub fn get_def_ctor_from_def_id<F>(cx: &DocContext,
def_id: DefId,
callback: &F,
) -> Vec<Item>
where F: Fn(&Fn(DefId) -> Def) -> Vec<Item> {
let ty = cx.tcx.type_of(def_id);

match ty.sty {
ty::TyAdt(adt, _) => callback(&match adt.adt_kind() {
AdtKind::Struct => Def::Struct,
AdtKind::Enum => Def::Enum,
AdtKind::Union => Def::Union,
}),
ty::TyInt(_) |
ty::TyUint(_) |
ty::TyFloat(_) |
ty::TyStr |
ty::TyBool |
ty::TyChar => callback(&move |_: DefId| {
match ty.sty {
ty::TyInt(x) => Def::PrimTy(hir::TyInt(x)),
ty::TyUint(x) => Def::PrimTy(hir::TyUint(x)),
ty::TyFloat(x) => Def::PrimTy(hir::TyFloat(x)),
ty::TyStr => Def::PrimTy(hir::TyStr),
ty::TyBool => Def::PrimTy(hir::TyBool),
ty::TyChar => Def::PrimTy(hir::TyChar),
_ => unreachable!(),
}
}),
_ => {
debug!("Unexpected type {:?}", def_id);
Vec::new()
}
}
}

pub fn get_def_ctor_from_node_id<F>(cx: &DocContext,
id: ast::NodeId,
name: String,
callback: &F,
) -> Vec<Item>
where F: Fn(&Fn(DefId) -> Def, String) -> Vec<Item> {
let item = &cx.tcx.hir.expect_item(id).node;

callback(&match *item {
hir::ItemKind::Struct(_, _) => Def::Struct,
hir::ItemKind::Union(_, _) => Def::Union,
hir::ItemKind::Enum(_, _) => Def::Enum,
_ => panic!("Unexpected type {:?} {:?}", item, id),
}, name)
}
154 changes: 154 additions & 0 deletions src/librustdoc/clean/finder_trait.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright 2018 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.

use rustc::hir;
use syntax_pos::DUMMY_SP;

use super::*;

pub trait Finder<'a, 'tcx: 'a, 'rcx: 'a> {
fn get_cx(&self) -> &DocContext<'a, 'tcx, 'rcx>;

// This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
// refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
// registered after the AST is constructed would require storing the defid mapping in a
// RefCell, decreasing the performance for normal compilation for very little gain.
//
// Instead, we construct 'fake' def ids, which start immediately after the last DefId in
// DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
// def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
fn next_def_id(&self, crate_num: CrateNum) -> DefId {
let start_def_id = {
let next_id = if crate_num == LOCAL_CRATE {
self.get_cx()
.tcx
.hir
.definitions()
.def_path_table()
.next_id(DefIndexAddressSpace::Low)
} else {
self.get_cx()
.cstore
.def_path_table(crate_num)
.next_id(DefIndexAddressSpace::Low)
};

DefId {
krate: crate_num,
index: next_id,
}
};

let mut fake_ids = self.get_cx().fake_def_ids.borrow_mut();

let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
fake_ids.insert(
crate_num,
DefId {
krate: crate_num,
index: DefIndex::from_array_index(
def_id.index.as_array_index() + 1,
def_id.index.address_space(),
),
},
);

MAX_DEF_ID.with(|m| {
m.borrow_mut()
.entry(def_id.krate.clone())
.or_insert(start_def_id);
});

self.get_cx().all_fake_def_ids.borrow_mut().insert(def_id);

def_id.clone()
}

fn get_real_ty<F>(&self,
def_id: DefId,
def_ctor: &F,
real_name: &Option<Ident>,
generics: &ty::Generics,
) -> hir::Ty
where F: Fn(DefId) -> Def {
let path = get_path_for_type(self.get_cx().tcx, def_id, def_ctor);
let mut segments = path.segments.into_vec();
let last = segments.pop().expect("segments were empty");

segments.push(hir::PathSegment::new(
real_name.unwrap_or(last.ident),
self.generics_to_path_params(generics.clone()),
false,
));

let new_path = hir::Path {
span: path.span,
def: path.def,
segments: HirVec::from_vec(segments),
};

hir::Ty {
id: ast::DUMMY_NODE_ID,
node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
span: DUMMY_SP,
hir_id: hir::DUMMY_HIR_ID,
}
}

fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
let mut args = vec![];

for param in generics.params.iter() {
match param.kind {
ty::GenericParamDefKind::Lifetime => {
let name = if param.name == "" {
hir::ParamName::Plain(keywords::StaticLifetime.ident())
} else {
hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
};

args.push(hir::GenericArg::Lifetime(hir::Lifetime {
id: ast::DUMMY_NODE_ID,
span: DUMMY_SP,
name: hir::LifetimeName::Param(name),
}));
}
ty::GenericParamDefKind::Type {..} => {
args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
}
}
}

hir::GenericArgs {
args: HirVec::from_vec(args),
bindings: HirVec::new(),
parenthesized: false,
}
}

fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
hir::Ty {
id: ast::DUMMY_NODE_ID,
node: hir::TyKind::Path(hir::QPath::Resolved(
None,
P(hir::Path {
span: DUMMY_SP,
def: Def::TyParam(param.def_id),
segments: HirVec::from_vec(vec![
hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
]),
}),
)),
span: DUMMY_SP,
hir_id: hir::DUMMY_HIR_ID,
}
}
}
Loading

0 comments on commit 4aba7de

Please sign in to comment.