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};
25 use rustc_const_eval::lookup_const_by_id;
27 use core::{DocContext, DocAccessLevels};
29 use clean::{self, GetDefId};
33 /// Attempt to inline the definition of a local node id into this AST.
35 /// This function will fetch the definition of the id specified, and if it is
36 /// from another crate it will attempt to inline the documentation from the
37 /// other crate into this crate.
39 /// This is primarily used for `pub use` statements which are, in general,
40 /// implementation details. Inlining the documentation should help provide a
41 /// better experience when reading the documentation in this use case.
43 /// The returned value is `None` if the `id` could not be inlined, and `Some`
44 /// of a vector of items if it was successfully expanded.
45 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
46 -> Option<Vec<clean::Item>> {
47 let tcx = match cx.tcx_opt() {
51 let def = match tcx.expect_def_or_none(id) {
55 let did = def.def_id();
56 if did.is_local() { return None }
57 try_inline_def(cx, tcx, def).map(|vec| {
58 vec.into_iter().map(|mut item| {
60 Some(into) if item.name.is_some() => {
61 item.name = Some(into.clean(cx));
70 fn try_inline_def<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
71 def: Def) -> Option<Vec<clean::Item>> {
72 let mut ret = Vec::new();
73 let did = def.def_id();
74 let inner = match def {
76 record_extern_fqn(cx, did, clean::TypeTrait);
77 ret.extend(build_impls(cx, tcx, did));
78 clean::TraitItem(build_external_trait(cx, tcx, did))
81 record_extern_fqn(cx, did, clean::TypeFunction);
82 clean::FunctionItem(build_external_function(cx, tcx, did))
85 // If this is a struct constructor, we skip it
86 if tcx.sess.cstore.tuple_struct_definition_if_ctor(did).is_none() => {
87 record_extern_fqn(cx, did, clean::TypeStruct);
88 ret.extend(build_impls(cx, tcx, did));
89 clean::StructItem(build_struct(cx, tcx, did))
91 Def::TyAlias(did) => {
92 record_extern_fqn(cx, did, clean::TypeTypedef);
93 ret.extend(build_impls(cx, tcx, did));
94 build_type(cx, tcx, did)
97 record_extern_fqn(cx, did, clean::TypeEnum);
98 ret.extend(build_impls(cx, tcx, did));
99 build_type(cx, tcx, did)
101 // Assume that the enum type is reexported next to the variant, and
102 // variants don't show up in documentation specially.
103 Def::Variant(..) => return Some(Vec::new()),
105 record_extern_fqn(cx, did, clean::TypeModule);
106 clean::ModuleItem(build_module(cx, tcx, did))
108 Def::Static(did, mtbl) => {
109 record_extern_fqn(cx, did, clean::TypeStatic);
110 clean::StaticItem(build_static(cx, tcx, did, mtbl))
112 Def::Const(did) | Def::AssociatedConst(did) => {
113 record_extern_fqn(cx, did, clean::TypeConst);
114 clean::ConstantItem(build_const(cx, tcx, did))
118 cx.renderinfo.borrow_mut().inlined.insert(did);
119 ret.push(clean::Item {
120 source: clean::Span::empty(),
121 name: Some(tcx.item_name(did).to_string()),
122 attrs: load_attrs(cx, tcx, did),
124 visibility: Some(clean::Public),
125 stability: tcx.lookup_stability(did).clean(cx),
126 deprecation: tcx.lookup_deprecation(did).clean(cx),
132 pub fn load_attrs<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
133 did: DefId) -> Vec<clean::Attribute> {
134 tcx.get_attrs(did).iter().map(|a| a.clean(cx)).collect()
137 /// Record an external fully qualified name in the external_paths cache.
139 /// These names are used later on by HTML rendering to generate things like
140 /// source links back to the original item.
141 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
142 if let Some(tcx) = cx.tcx_opt() {
143 let crate_name = tcx.sess.cstore.crate_name(did.krate).to_string();
144 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
145 // extern blocks have an empty name
146 let s = elem.data.to_string();
153 let fqn = once(crate_name).chain(relative).collect();
154 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
158 pub fn build_external_trait<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
159 did: DefId) -> clean::Trait {
160 let def = tcx.lookup_trait_def(did);
161 let trait_items = tcx.trait_items(did).clean(cx);
162 let predicates = tcx.lookup_predicates(did);
163 let generics = (def.generics, &predicates).clean(cx);
164 let generics = filter_non_trait_generics(did, generics);
165 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
167 unsafety: def.unsafety,
170 bounds: supertrait_bounds,
174 fn build_external_function<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
175 did: DefId) -> clean::Function {
176 let t = tcx.lookup_item_type(did);
177 let (decl, style, abi) = match t.ty.sty {
178 ty::TyFnDef(_, _, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
179 _ => panic!("bad function"),
182 let constness = if tcx.sess.cstore.is_const_fn(did) {
183 hir::Constness::Const
185 hir::Constness::NotConst
188 let predicates = tcx.lookup_predicates(did);
191 generics: (t.generics, &predicates).clean(cx),
193 constness: constness,
198 fn build_struct<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
199 did: DefId) -> clean::Struct {
200 let t = tcx.lookup_item_type(did);
201 let predicates = tcx.lookup_predicates(did);
202 let variant = tcx.lookup_adt_def(did).struct_variant();
205 struct_type: match &variant.fields[..] {
206 &[] => doctree::Unit,
207 &[_] if variant.kind == ty::VariantKind::Tuple => doctree::Newtype,
208 &[..] if variant.kind == ty::VariantKind::Tuple => doctree::Tuple,
211 generics: (t.generics, &predicates).clean(cx),
212 fields: variant.fields.clean(cx),
213 fields_stripped: false,
217 fn build_type<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
218 did: DefId) -> clean::ItemEnum {
219 let t = tcx.lookup_item_type(did);
220 let predicates = tcx.lookup_predicates(did);
222 ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
223 return clean::EnumItem(clean::Enum {
224 generics: (t.generics, &predicates).clean(cx),
225 variants_stripped: false,
226 variants: edef.variants.clean(cx),
232 clean::TypedefItem(clean::Typedef {
233 type_: t.ty.clean(cx),
234 generics: (t.generics, &predicates).clean(cx),
238 pub fn build_impls<'a, 'tcx>(cx: &DocContext,
239 tcx: TyCtxt<'a, 'tcx, 'tcx>,
240 did: DefId) -> Vec<clean::Item> {
241 tcx.populate_inherent_implementations_for_type_if_necessary(did);
242 let mut impls = Vec::new();
244 if let Some(i) = tcx.inherent_impls.borrow().get(&did) {
245 for &did in i.iter() {
246 build_impl(cx, tcx, did, &mut impls);
250 // If this is the first time we've inlined something from this crate, then
251 // we inline *all* impls from the crate into this crate. Note that there's
252 // currently no way for us to filter this based on type, and we likely need
253 // many impls for a variety of reasons.
255 // Primarily, the impls will be used to populate the documentation for this
256 // type being inlined, but impls can also be used when generating
257 // documentation for primitives (no way to find those specifically).
258 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
259 for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
260 populate_impls(cx, tcx, item.def, &mut impls);
263 fn populate_impls<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
264 def: cstore::DefLike,
265 impls: &mut Vec<clean::Item>) {
267 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
268 cstore::DlDef(Def::Mod(did)) => {
269 for item in tcx.sess.cstore.item_children(did) {
270 populate_impls(cx, tcx, item.def, impls)
281 pub fn build_impl<'a, 'tcx>(cx: &DocContext,
282 tcx: TyCtxt<'a, 'tcx, 'tcx>,
284 ret: &mut Vec<clean::Item>) {
285 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
289 let attrs = load_attrs(cx, tcx, did);
290 let associated_trait = tcx.impl_trait_ref(did);
292 // Only inline impl if the implemented trait is
293 // reachable in rustdoc generated documentation
294 if let Some(traitref) = associated_trait {
295 if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
300 // If this is a defaulted impl, then bail out early here
301 if tcx.sess.cstore.is_default_impl(did) {
302 return ret.push(clean::Item {
303 inner: clean::DefaultImplItem(clean::DefaultImpl {
304 // FIXME: this should be decoded
305 unsafety: hir::Unsafety::Normal,
306 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
307 clean::TraitBound(polyt, _) => polyt.trait_,
308 clean::RegionBound(..) => unreachable!(),
311 source: clean::Span::empty(),
314 visibility: Some(clean::Inherited),
315 stability: tcx.lookup_stability(did).clean(cx),
316 deprecation: tcx.lookup_deprecation(did).clean(cx),
321 let ty = tcx.lookup_item_type(did);
322 let for_ = ty.ty.clean(cx);
324 // Only inline impl if the implementing type is
325 // reachable in rustdoc generated documentation
326 if let Some(did) = for_.def_id() {
327 if !cx.access_levels.borrow().is_doc_reachable(did) {
332 let predicates = tcx.lookup_predicates(did);
333 let trait_items = tcx.sess.cstore.impl_items(did)
336 let did = did.def_id();
337 let impl_item = tcx.impl_or_trait_item(did);
339 ty::ConstTraitItem(ref assoc_const) => {
340 let did = assoc_const.def_id;
341 let type_scheme = tcx.lookup_item_type(did);
342 let default = if assoc_const.has_value {
343 Some(pprust::expr_to_string(
344 lookup_const_by_id(tcx, did, None).unwrap().0))
349 name: Some(assoc_const.name.clean(cx)),
350 inner: clean::AssociatedConstItem(
351 type_scheme.ty.clean(cx),
354 source: clean::Span::empty(),
357 stability: tcx.lookup_stability(did).clean(cx),
358 deprecation: tcx.lookup_deprecation(did).clean(cx),
362 ty::MethodTraitItem(method) => {
363 if method.vis != ty::Visibility::Public && associated_trait.is_none() {
366 let mut item = method.clean(cx);
367 item.inner = match item.inner.clone() {
368 clean::TyMethodItem(clean::TyMethod {
369 unsafety, decl, generics, abi
371 let constness = if tcx.sess.cstore.is_const_fn(did) {
372 hir::Constness::Const
374 hir::Constness::NotConst
377 clean::MethodItem(clean::Method {
379 constness: constness,
385 _ => panic!("not a tymethod"),
389 ty::TypeTraitItem(ref assoc_ty) => {
390 let did = assoc_ty.def_id;
391 let typedef = clean::Typedef {
392 type_: assoc_ty.ty.unwrap().clean(cx),
393 generics: clean::Generics {
396 where_predicates: vec![]
400 name: Some(assoc_ty.name.clean(cx)),
401 inner: clean::TypedefItem(typedef, true),
402 source: clean::Span::empty(),
405 stability: tcx.lookup_stability(did).clean(cx),
406 deprecation: tcx.lookup_deprecation(did).clean(cx),
411 }).collect::<Vec<_>>();
412 let polarity = tcx.trait_impl_polarity(did);
413 let trait_ = associated_trait.clean(cx).map(|bound| {
415 clean::TraitBound(polyt, _) => polyt.trait_,
416 clean::RegionBound(..) => unreachable!(),
419 if trait_.def_id() == cx.deref_trait_did.get() {
420 super::build_deref_target_impls(cx, &trait_items, ret);
423 let provided = trait_.def_id().map(|did| {
424 cx.tcx().provided_trait_methods(did)
426 .map(|meth| meth.name.to_string())
428 }).unwrap_or(HashSet::new());
430 ret.push(clean::Item {
431 inner: clean::ImplItem(clean::Impl {
432 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
433 provided_trait_methods: provided,
436 generics: (ty.generics, &predicates).clean(cx),
438 polarity: polarity.map(|p| { p.clean(cx) }),
440 source: clean::Span::empty(),
443 visibility: Some(clean::Inherited),
444 stability: tcx.lookup_stability(did).clean(cx),
445 deprecation: tcx.lookup_deprecation(did).clean(cx),
450 fn build_module<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
451 did: DefId) -> clean::Module {
452 let mut items = Vec::new();
453 fill_in(cx, tcx, did, &mut items);
454 return clean::Module {
459 fn fill_in<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
460 did: DefId, items: &mut Vec<clean::Item>) {
461 // If we're reexporting a reexport it may actually reexport something in
462 // two namespaces, so the target may be listed twice. Make sure we only
463 // visit each node at most once.
464 let mut visited = HashSet::new();
465 for item in tcx.sess.cstore.item_children(did) {
467 cstore::DlDef(Def::ForeignMod(did)) => {
468 fill_in(cx, tcx, did, items);
470 cstore::DlDef(def) if item.vis == ty::Visibility::Public => {
471 if !visited.insert(def) { continue }
472 if let Some(i) = try_inline_def(cx, tcx, def) {
476 cstore::DlDef(..) => {}
477 // All impls were inlined above
478 cstore::DlImpl(..) => {}
479 cstore::DlField => panic!("unimplemented field"),
485 fn build_const<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
486 did: DefId) -> clean::Constant {
487 let (expr, ty) = lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
488 panic!("expected lookup_const_by_id to succeed for {:?}", did);
490 debug!("converting constant expr {:?} to snippet", expr);
491 let sn = pprust::expr_to_string(expr);
492 debug!("got snippet {}", sn);
495 type_: ty.map(|t| t.clean(cx)).unwrap_or_else(|| tcx.lookup_item_type(did).ty.clean(cx)),
500 fn build_static<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
502 mutable: bool) -> clean::Static {
504 type_: tcx.lookup_item_type(did).ty.clean(cx),
505 mutability: if mutable {clean::Mutable} else {clean::Immutable},
506 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
510 /// A trait's generics clause actually contains all of the predicates for all of
511 /// its associated types as well. We specifically move these clauses to the
512 /// associated types instead when displaying, so when we're genering the
513 /// generics for the trait itself we need to be sure to remove them.
514 /// We also need to remove the implied "recursive" Self: Trait bound.
516 /// The inverse of this filtering logic can be found in the `Clean`
517 /// implementation for `AssociatedType`
518 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
520 for pred in &mut g.where_predicates {
522 clean::WherePredicate::BoundPredicate {
523 ty: clean::Generic(ref s),
525 } if *s == "Self" => {
526 bounds.retain(|bound| {
528 clean::TyParamBound::TraitBound(clean::PolyTrait {
529 trait_: clean::ResolvedPath { did, .. },
531 }, _) => did != trait_did,
540 g.where_predicates.retain(|pred| {
542 clean::WherePredicate::BoundPredicate {
544 self_type: box clean::Generic(ref s),
545 trait_: box clean::ResolvedPath { did, .. },
548 } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
555 /// Supertrait bounds for a trait are also listed in the generics coming from
556 /// the metadata for a crate, so we want to separate those out and create a new
557 /// list of explicit supertrait bounds to render nicely.
558 fn separate_supertrait_bounds(mut g: clean::Generics)
559 -> (clean::Generics, Vec<clean::TyParamBound>) {
560 let mut ty_bounds = Vec::new();
561 g.where_predicates.retain(|pred| {
563 clean::WherePredicate::BoundPredicate {
564 ty: clean::Generic(ref s),
566 } if *s == "Self" => {
567 ty_bounds.extend(bounds.iter().cloned());