1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Support for inlining external documentation into the current AST.
13 use std::collections::HashSet;
19 use rustc::middle::cstore;
20 use rustc::hir::def::Def;
21 use rustc::hir::def_id::DefId;
22 use rustc::hir::print as pprust;
23 use rustc::ty::{self, TyCtxt};
26 use rustc_const_eval::lookup_const_by_id;
28 use core::{DocContext, DocAccessLevels};
30 use clean::{self, GetDefId};
34 /// Attempt to inline the definition of a local node id into this AST.
36 /// This function will fetch the definition of the id specified, and if it is
37 /// from another crate it will attempt to inline the documentation from the
38 /// other crate into this crate.
40 /// This is primarily used for `pub use` statements which are, in general,
41 /// implementation details. Inlining the documentation should help provide a
42 /// better experience when reading the documentation in this use case.
44 /// The returned value is `None` if the `id` could not be inlined, and `Some`
45 /// of a vector of items if it was successfully expanded.
46 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
47 -> Option<Vec<clean::Item>> {
48 let tcx = match cx.tcx_opt() {
52 let def = match tcx.def_map.borrow().get(&id) {
53 Some(d) => d.full_def(),
56 let did = def.def_id();
57 if did.is_local() { return None }
58 try_inline_def(cx, tcx, def).map(|vec| {
59 vec.into_iter().map(|mut item| {
61 Some(into) if item.name.is_some() => {
62 item.name = Some(into.clean(cx));
71 fn try_inline_def<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
72 def: Def) -> Option<Vec<clean::Item>> {
73 let mut ret = Vec::new();
74 let did = def.def_id();
75 let inner = match def {
77 record_extern_fqn(cx, did, clean::TypeTrait);
78 ret.extend(build_impls(cx, tcx, did));
79 clean::TraitItem(build_external_trait(cx, tcx, did))
82 record_extern_fqn(cx, did, clean::TypeFunction);
83 clean::FunctionItem(build_external_function(cx, tcx, did))
86 // If this is a struct constructor, we skip it
87 if tcx.sess.cstore.tuple_struct_definition_if_ctor(did).is_none() => {
88 record_extern_fqn(cx, did, clean::TypeStruct);
89 ret.extend(build_impls(cx, tcx, did));
90 clean::StructItem(build_struct(cx, tcx, did))
92 Def::TyAlias(did) => {
93 record_extern_fqn(cx, did, clean::TypeTypedef);
94 ret.extend(build_impls(cx, tcx, did));
95 build_type(cx, tcx, did)
98 record_extern_fqn(cx, did, clean::TypeEnum);
99 ret.extend(build_impls(cx, tcx, did));
100 build_type(cx, tcx, did)
102 // Assume that the enum type is reexported next to the variant, and
103 // variants don't show up in documentation specially.
104 Def::Variant(..) => return Some(Vec::new()),
106 record_extern_fqn(cx, did, clean::TypeModule);
107 clean::ModuleItem(build_module(cx, tcx, did))
109 Def::Static(did, mtbl) => {
110 record_extern_fqn(cx, did, clean::TypeStatic);
111 clean::StaticItem(build_static(cx, tcx, did, mtbl))
113 Def::Const(did) | Def::AssociatedConst(did) => {
114 record_extern_fqn(cx, did, clean::TypeConst);
115 clean::ConstantItem(build_const(cx, tcx, did))
119 cx.renderinfo.borrow_mut().inlined.insert(did);
120 ret.push(clean::Item {
121 source: clean::Span::empty(),
122 name: Some(tcx.item_name(did).to_string()),
123 attrs: load_attrs(cx, tcx, did),
125 visibility: Some(clean::Public),
126 stability: tcx.lookup_stability(did).clean(cx),
127 deprecation: tcx.lookup_deprecation(did).clean(cx),
133 pub fn load_attrs<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
134 did: DefId) -> Vec<clean::Attribute> {
135 tcx.get_attrs(did).iter().map(|a| a.clean(cx)).collect()
138 /// Record an external fully qualified name in the external_paths cache.
140 /// These names are used later on by HTML rendering to generate things like
141 /// source links back to the original item.
142 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
143 if let Some(tcx) = cx.tcx_opt() {
144 let crate_name = tcx.sess.cstore.crate_name(did.krate).to_string();
145 let relative = tcx.def_path(did).data.into_iter().map(|elem| {
146 elem.data.to_string()
148 let fqn = once(crate_name).chain(relative).collect();
149 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
153 pub fn build_external_trait<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
154 did: DefId) -> clean::Trait {
155 let def = tcx.lookup_trait_def(did);
156 let trait_items = tcx.trait_items(did).clean(cx);
157 let predicates = tcx.lookup_predicates(did);
158 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
159 let generics = filter_non_trait_generics(did, generics);
160 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
162 unsafety: def.unsafety,
165 bounds: supertrait_bounds,
169 fn build_external_function<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
170 did: DefId) -> clean::Function {
171 let t = tcx.lookup_item_type(did);
172 let (decl, style, abi) = match t.ty.sty {
173 ty::TyFnDef(_, _, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
174 _ => panic!("bad function"),
177 let constness = if tcx.sess.cstore.is_const_fn(did) {
178 hir::Constness::Const
180 hir::Constness::NotConst
183 let predicates = tcx.lookup_predicates(did);
186 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
188 constness: constness,
193 fn build_struct<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
194 did: DefId) -> clean::Struct {
195 let t = tcx.lookup_item_type(did);
196 let predicates = tcx.lookup_predicates(did);
197 let variant = tcx.lookup_adt_def(did).struct_variant();
200 struct_type: match &*variant.fields {
202 [_] if variant.kind == ty::VariantKind::Tuple => doctree::Newtype,
203 [..] if variant.kind == ty::VariantKind::Tuple => doctree::Tuple,
206 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
207 fields: variant.fields.clean(cx),
208 fields_stripped: false,
212 fn build_type<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
213 did: DefId) -> clean::ItemEnum {
214 let t = tcx.lookup_item_type(did);
215 let predicates = tcx.lookup_predicates(did);
217 ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
218 return clean::EnumItem(clean::Enum {
219 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
220 variants_stripped: false,
221 variants: edef.variants.clean(cx),
227 clean::TypedefItem(clean::Typedef {
228 type_: t.ty.clean(cx),
229 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
233 pub fn build_impls<'a, 'tcx>(cx: &DocContext,
234 tcx: TyCtxt<'a, 'tcx, 'tcx>,
235 did: DefId) -> Vec<clean::Item> {
236 tcx.populate_inherent_implementations_for_type_if_necessary(did);
237 let mut impls = Vec::new();
239 if let Some(i) = tcx.inherent_impls.borrow().get(&did) {
240 for &did in i.iter() {
241 build_impl(cx, tcx, did, &mut impls);
245 // If this is the first time we've inlined something from this crate, then
246 // we inline *all* impls from the crate into this crate. Note that there's
247 // currently no way for us to filter this based on type, and we likely need
248 // many impls for a variety of reasons.
250 // Primarily, the impls will be used to populate the documentation for this
251 // type being inlined, but impls can also be used when generating
252 // documentation for primitives (no way to find those specifically).
253 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
254 for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
255 populate_impls(cx, tcx, item.def, &mut impls);
258 fn populate_impls<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
259 def: cstore::DefLike,
260 impls: &mut Vec<clean::Item>) {
262 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
263 cstore::DlDef(Def::Mod(did)) => {
264 for item in tcx.sess.cstore.item_children(did) {
265 populate_impls(cx, tcx, item.def, impls)
276 pub fn build_impl<'a, 'tcx>(cx: &DocContext,
277 tcx: TyCtxt<'a, 'tcx, 'tcx>,
279 ret: &mut Vec<clean::Item>) {
280 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
284 let attrs = load_attrs(cx, tcx, did);
285 let associated_trait = tcx.impl_trait_ref(did);
287 // Only inline impl if the implemented trait is
288 // reachable in rustdoc generated documentation
289 if let Some(traitref) = associated_trait {
290 if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
295 // If this is a defaulted impl, then bail out early here
296 if tcx.sess.cstore.is_default_impl(did) {
297 return ret.push(clean::Item {
298 inner: clean::DefaultImplItem(clean::DefaultImpl {
299 // FIXME: this should be decoded
300 unsafety: hir::Unsafety::Normal,
301 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
302 clean::TraitBound(polyt, _) => polyt.trait_,
303 clean::RegionBound(..) => unreachable!(),
306 source: clean::Span::empty(),
309 visibility: Some(clean::Inherited),
310 stability: tcx.lookup_stability(did).clean(cx),
311 deprecation: tcx.lookup_deprecation(did).clean(cx),
316 let ty = tcx.lookup_item_type(did);
317 let for_ = ty.ty.clean(cx);
319 // Only inline impl if the implementing type is
320 // reachable in rustdoc generated documentation
321 if let Some(did) = for_.def_id() {
322 if !cx.access_levels.borrow().is_doc_reachable(did) {
327 let predicates = tcx.lookup_predicates(did);
328 let trait_items = tcx.sess.cstore.impl_items(did)
331 let did = did.def_id();
332 let impl_item = tcx.impl_or_trait_item(did);
334 ty::ConstTraitItem(ref assoc_const) => {
335 let did = assoc_const.def_id;
336 let type_scheme = tcx.lookup_item_type(did);
337 let default = if assoc_const.has_value {
338 Some(pprust::expr_to_string(
339 lookup_const_by_id(tcx, did, None).unwrap().0))
344 name: Some(assoc_const.name.clean(cx)),
345 inner: clean::AssociatedConstItem(
346 type_scheme.ty.clean(cx),
349 source: clean::Span::empty(),
352 stability: tcx.lookup_stability(did).clean(cx),
353 deprecation: tcx.lookup_deprecation(did).clean(cx),
357 ty::MethodTraitItem(method) => {
358 if method.vis != ty::Visibility::Public && associated_trait.is_none() {
361 let mut item = method.clean(cx);
362 item.inner = match item.inner.clone() {
363 clean::TyMethodItem(clean::TyMethod {
364 unsafety, decl, generics, abi
366 let constness = if tcx.sess.cstore.is_const_fn(did) {
367 hir::Constness::Const
369 hir::Constness::NotConst
372 clean::MethodItem(clean::Method {
374 constness: constness,
380 _ => panic!("not a tymethod"),
384 ty::TypeTraitItem(ref assoc_ty) => {
385 let did = assoc_ty.def_id;
386 let type_scheme = ty::TypeScheme {
387 ty: assoc_ty.ty.unwrap(),
388 generics: ty::Generics::empty()
390 // Not sure the choice of ParamSpace actually matters here,
391 // because an associated type won't have generics on the LHS
392 let typedef = (type_scheme, ty::GenericPredicates::empty(),
393 subst::ParamSpace::TypeSpace).clean(cx);
395 name: Some(assoc_ty.name.clean(cx)),
396 inner: clean::TypedefItem(typedef, true),
397 source: clean::Span::empty(),
400 stability: tcx.lookup_stability(did).clean(cx),
401 deprecation: tcx.lookup_deprecation(did).clean(cx),
406 }).collect::<Vec<_>>();
407 let polarity = tcx.trait_impl_polarity(did);
408 let trait_ = associated_trait.clean(cx).map(|bound| {
410 clean::TraitBound(polyt, _) => polyt.trait_,
411 clean::RegionBound(..) => unreachable!(),
414 if trait_.def_id() == cx.deref_trait_did.get() {
415 super::build_deref_target_impls(cx, &trait_items, ret);
418 let provided = trait_.def_id().map(|did| {
419 cx.tcx().provided_trait_methods(did)
421 .map(|meth| meth.name.to_string())
423 }).unwrap_or(HashSet::new());
425 ret.push(clean::Item {
426 inner: clean::ImplItem(clean::Impl {
427 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
428 derived: clean::detect_derived(&attrs),
429 provided_trait_methods: provided,
432 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
434 polarity: polarity.map(|p| { p.clean(cx) }),
436 source: clean::Span::empty(),
439 visibility: Some(clean::Inherited),
440 stability: tcx.lookup_stability(did).clean(cx),
441 deprecation: tcx.lookup_deprecation(did).clean(cx),
446 fn build_module<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
447 did: DefId) -> clean::Module {
448 let mut items = Vec::new();
449 fill_in(cx, tcx, did, &mut items);
450 return clean::Module {
455 fn fill_in<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
456 did: DefId, items: &mut Vec<clean::Item>) {
457 // If we're reexporting a reexport it may actually reexport something in
458 // two namespaces, so the target may be listed twice. Make sure we only
459 // visit each node at most once.
460 let mut visited = HashSet::new();
461 for item in tcx.sess.cstore.item_children(did) {
463 cstore::DlDef(Def::ForeignMod(did)) => {
464 fill_in(cx, tcx, did, items);
466 cstore::DlDef(def) if item.vis == ty::Visibility::Public => {
467 if !visited.insert(def) { continue }
468 if let Some(i) = try_inline_def(cx, tcx, def) {
472 cstore::DlDef(..) => {}
473 // All impls were inlined above
474 cstore::DlImpl(..) => {}
475 cstore::DlField => panic!("unimplemented field"),
481 fn build_const<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
482 did: DefId) -> clean::Constant {
483 let (expr, ty) = lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
484 panic!("expected lookup_const_by_id to succeed for {:?}", did);
486 debug!("converting constant expr {:?} to snippet", expr);
487 let sn = pprust::expr_to_string(expr);
488 debug!("got snippet {}", sn);
491 type_: ty.map(|t| t.clean(cx)).unwrap_or_else(|| tcx.lookup_item_type(did).ty.clean(cx)),
496 fn build_static<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
498 mutable: bool) -> clean::Static {
500 type_: tcx.lookup_item_type(did).ty.clean(cx),
501 mutability: if mutable {clean::Mutable} else {clean::Immutable},
502 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
506 /// A trait's generics clause actually contains all of the predicates for all of
507 /// its associated types as well. We specifically move these clauses to the
508 /// associated types instead when displaying, so when we're genering the
509 /// generics for the trait itself we need to be sure to remove them.
511 /// The inverse of this filtering logic can be found in the `Clean`
512 /// implementation for `AssociatedType`
513 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
515 g.where_predicates.retain(|pred| {
517 clean::WherePredicate::BoundPredicate {
519 self_type: box clean::Generic(ref s),
520 trait_: box clean::ResolvedPath { did, .. },
523 } => *s != "Self" || did != trait_did,
530 /// Supertrait bounds for a trait are also listed in the generics coming from
531 /// the metadata for a crate, so we want to separate those out and create a new
532 /// list of explicit supertrait bounds to render nicely.
533 fn separate_supertrait_bounds(mut g: clean::Generics)
534 -> (clean::Generics, Vec<clean::TyParamBound>) {
535 let mut ty_bounds = Vec::new();
536 g.where_predicates.retain(|pred| {
538 clean::WherePredicate::BoundPredicate {
539 ty: clean::Generic(ref s),
541 } if *s == "Self" => {
542 ty_bounds.extend(bounds.iter().cloned());