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
;
17 use syntax
::attr
::AttrMetaMethods
;
20 use rustc
::middle
::cstore
::{self, CrateStore}
;
21 use rustc
::hir
::def
::Def
;
22 use rustc
::hir
::def_id
::DefId
;
23 use rustc
::ty
::{self, TyCtxt}
;
25 use rustc
::middle
::stability
;
27 use rustc_const_eval
::lookup_const_by_id
;
31 use clean
::{self, Attributes, GetDefId}
;
33 use super::{Clean, ToSource}
;
35 /// Attempt to inline the definition of a local node id into this AST.
37 /// This function will fetch the definition of the id specified, and if it is
38 /// from another crate it will attempt to inline the documentation from the
39 /// other crate into this crate.
41 /// This is primarily used for `pub use` statements which are, in general,
42 /// implementation details. Inlining the documentation should help provide a
43 /// better experience when reading the documentation in this use case.
45 /// The returned value is `None` if the `id` could not be inlined, and `Some`
46 /// of a vector of items if it was successfully expanded.
47 pub fn try_inline(cx
: &DocContext
, id
: ast
::NodeId
, into
: Option
<ast
::Name
>)
48 -> Option
<Vec
<clean
::Item
>> {
49 let tcx
= match cx
.tcx_opt() {
53 let def
= match tcx
.def_map
.borrow().get(&id
) {
54 Some(d
) => d
.full_def(),
57 let did
= def
.def_id();
58 if did
.is_local() { return None }
59 try_inline_def(cx
, tcx
, def
).map(|vec
| {
60 vec
.into_iter().map(|mut item
| {
62 Some(into
) if item
.name
.is_some() => {
63 item
.name
= Some(into
.clean(cx
));
72 fn try_inline_def(cx
: &DocContext
, tcx
: &TyCtxt
,
73 def
: Def
) -> Option
<Vec
<clean
::Item
>> {
74 let mut ret
= Vec
::new();
75 let did
= def
.def_id();
76 let inner
= match def
{
78 record_extern_fqn(cx
, did
, clean
::TypeTrait
);
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
.inlined
.borrow_mut().as_mut().unwrap().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(hir
::Public
),
126 stability
: stability
::lookup_stability(tcx
, did
).clean(cx
),
127 deprecation
: stability
::lookup_deprecation(tcx
, did
).clean(cx
),
133 pub fn load_attrs(cx
: &DocContext
, tcx
: &TyCtxt
,
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
.external_paths
.borrow_mut().as_mut().unwrap().insert(did
, (fqn
, kind
));
153 pub fn build_external_trait(cx
: &DocContext
, tcx
: &TyCtxt
,
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(cx
: &DocContext
, tcx
: &TyCtxt
, did
: DefId
) -> clean
::Function
{
170 let t
= tcx
.lookup_item_type(did
);
171 let (decl
, style
, abi
) = match t
.ty
.sty
{
172 ty
::TyFnDef(_
, _
, ref f
) => ((did
, &f
.sig
).clean(cx
), f
.unsafety
, f
.abi
),
173 _
=> panic
!("bad function"),
176 let constness
= if tcx
.sess
.cstore
.is_const_fn(did
) {
177 hir
::Constness
::Const
179 hir
::Constness
::NotConst
182 let predicates
= tcx
.lookup_predicates(did
);
185 generics
: (&t
.generics
, &predicates
, subst
::FnSpace
).clean(cx
),
187 constness
: constness
,
192 fn build_struct(cx
: &DocContext
, tcx
: &TyCtxt
, did
: DefId
) -> clean
::Struct
{
193 let t
= tcx
.lookup_item_type(did
);
194 let predicates
= tcx
.lookup_predicates(did
);
195 let variant
= tcx
.lookup_adt_def(did
).struct_variant();
198 struct_type
: match &*variant
.fields
{
200 [_
] if variant
.kind
== ty
::VariantKind
::Tuple
=> doctree
::Newtype
,
201 [..] if variant
.kind
== ty
::VariantKind
::Tuple
=> doctree
::Tuple
,
204 generics
: (&t
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
205 fields
: variant
.fields
.clean(cx
),
206 fields_stripped
: false,
210 fn build_type(cx
: &DocContext
, tcx
: &TyCtxt
, did
: DefId
) -> clean
::ItemEnum
{
211 let t
= tcx
.lookup_item_type(did
);
212 let predicates
= tcx
.lookup_predicates(did
);
214 ty
::TyEnum(edef
, _
) if !tcx
.sess
.cstore
.is_typedef(did
) => {
215 return clean
::EnumItem(clean
::Enum
{
216 generics
: (&t
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
217 variants_stripped
: false,
218 variants
: edef
.variants
.clean(cx
),
224 clean
::TypedefItem(clean
::Typedef
{
225 type_
: t
.ty
.clean(cx
),
226 generics
: (&t
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
230 pub fn build_impls(cx
: &DocContext
,
232 did
: DefId
) -> Vec
<clean
::Item
> {
233 tcx
.populate_inherent_implementations_for_type_if_necessary(did
);
234 let mut impls
= Vec
::new();
236 if let Some(i
) = tcx
.inherent_impls
.borrow().get(&did
) {
237 for &did
in i
.iter() {
238 build_impl(cx
, tcx
, did
, &mut impls
);
242 // If this is the first time we've inlined something from this crate, then
243 // we inline *all* impls from the crate into this crate. Note that there's
244 // currently no way for us to filter this based on type, and we likely need
245 // many impls for a variety of reasons.
247 // Primarily, the impls will be used to populate the documentation for this
248 // type being inlined, but impls can also be used when generating
249 // documentation for primitives (no way to find those specifically).
250 if !cx
.all_crate_impls
.borrow_mut().contains_key(&did
.krate
) {
251 let mut impls
= Vec
::new();
252 for item
in tcx
.sess
.cstore
.crate_top_level_items(did
.krate
) {
253 populate_impls(cx
, tcx
, item
.def
, &mut impls
);
255 cx
.all_crate_impls
.borrow_mut().insert(did
.krate
, impls
);
257 fn populate_impls(cx
: &DocContext
, tcx
: &TyCtxt
,
258 def
: cstore
::DefLike
,
259 impls
: &mut Vec
<clean
::Item
>) {
261 cstore
::DlImpl(did
) => build_impl(cx
, tcx
, did
, impls
),
262 cstore
::DlDef(Def
::Mod(did
)) => {
263 // Don't recurse if this is a #[doc(hidden)] module
264 if load_attrs(cx
, tcx
, did
).list("doc").has_word("hidden") {
268 for item
in tcx
.sess
.cstore
.item_children(did
) {
269 populate_impls(cx
, tcx
, item
.def
, impls
)
277 let mut candidates
= cx
.all_crate_impls
.borrow_mut();
278 let candidates
= candidates
.get_mut(&did
.krate
).unwrap();
279 for i
in (0..candidates
.len()).rev() {
280 let remove
= match candidates
[i
].inner
{
281 clean
::ImplItem(ref i
) => {
282 i
.for_
.def_id() == Some(did
) || i
.for_
.primitive_type().is_some()
287 impls
.push(candidates
.swap_remove(i
));
294 pub fn build_impl(cx
: &DocContext
,
297 ret
: &mut Vec
<clean
::Item
>) {
298 if !cx
.inlined
.borrow_mut().as_mut().unwrap().insert(did
) {
302 let attrs
= load_attrs(cx
, tcx
, did
);
303 let associated_trait
= tcx
.impl_trait_ref(did
);
304 if let Some(ref t
) = associated_trait
{
305 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
306 let trait_attrs
= load_attrs(cx
, tcx
, t
.def_id
);
307 if trait_attrs
.list("doc").has_word("hidden") {
312 // If this is a defaulted impl, then bail out early here
313 if tcx
.sess
.cstore
.is_default_impl(did
) {
314 return ret
.push(clean
::Item
{
315 inner
: clean
::DefaultImplItem(clean
::DefaultImpl
{
316 // FIXME: this should be decoded
317 unsafety
: hir
::Unsafety
::Normal
,
318 trait_
: match associated_trait
.as_ref().unwrap().clean(cx
) {
319 clean
::TraitBound(polyt
, _
) => polyt
.trait_
,
320 clean
::RegionBound(..) => unreachable
!(),
323 source
: clean
::Span
::empty(),
326 visibility
: Some(hir
::Inherited
),
327 stability
: stability
::lookup_stability(tcx
, did
).clean(cx
),
328 deprecation
: stability
::lookup_deprecation(tcx
, did
).clean(cx
),
333 let predicates
= tcx
.lookup_predicates(did
);
334 let trait_items
= tcx
.sess
.cstore
.impl_items(did
)
337 let did
= did
.def_id();
338 let impl_item
= tcx
.impl_or_trait_item(did
);
340 ty
::ConstTraitItem(ref assoc_const
) => {
341 let did
= assoc_const
.def_id
;
342 let type_scheme
= tcx
.lookup_item_type(did
);
343 let default = if assoc_const
.has_value
{
344 Some(lookup_const_by_id(tcx
, did
, None
)
345 .unwrap().0.span
.to_src(cx
))
350 name
: Some(assoc_const
.name
.clean(cx
)),
351 inner
: clean
::AssociatedConstItem(
352 type_scheme
.ty
.clean(cx
),
355 source
: clean
::Span
::empty(),
358 stability
: stability
::lookup_stability(tcx
, did
).clean(cx
),
359 deprecation
: stability
::lookup_deprecation(tcx
, did
).clean(cx
),
363 ty
::MethodTraitItem(method
) => {
364 if method
.vis
!= ty
::Visibility
::Public
&& associated_trait
.is_none() {
367 let mut item
= method
.clean(cx
);
368 item
.inner
= match item
.inner
.clone() {
369 clean
::TyMethodItem(clean
::TyMethod
{
370 unsafety
, decl
, self_
, generics
, abi
372 let constness
= if tcx
.sess
.cstore
.is_const_fn(did
) {
373 hir
::Constness
::Const
375 hir
::Constness
::NotConst
378 clean
::MethodItem(clean
::Method
{
380 constness
: constness
,
387 _
=> panic
!("not a tymethod"),
391 ty
::TypeTraitItem(ref assoc_ty
) => {
392 let did
= assoc_ty
.def_id
;
393 let type_scheme
= ty
::TypeScheme
{
394 ty
: assoc_ty
.ty
.unwrap(),
395 generics
: ty
::Generics
::empty()
397 // Not sure the choice of ParamSpace actually matters here,
398 // because an associated type won't have generics on the LHS
399 let typedef
= (type_scheme
, ty
::GenericPredicates
::empty(),
400 subst
::ParamSpace
::TypeSpace
).clean(cx
);
402 name
: Some(assoc_ty
.name
.clean(cx
)),
403 inner
: clean
::TypedefItem(typedef
, true),
404 source
: clean
::Span
::empty(),
407 stability
: stability
::lookup_stability(tcx
, did
).clean(cx
),
408 deprecation
: stability
::lookup_deprecation(tcx
, did
).clean(cx
),
413 }).collect
::<Vec
<_
>>();
414 let polarity
= tcx
.trait_impl_polarity(did
);
415 let ty
= tcx
.lookup_item_type(did
);
416 let trait_
= associated_trait
.clean(cx
).map(|bound
| {
418 clean
::TraitBound(polyt
, _
) => polyt
.trait_
,
419 clean
::RegionBound(..) => unreachable
!(),
422 if trait_
.def_id() == cx
.deref_trait_did
.get() {
423 super::build_deref_target_impls(cx
, &trait_items
, ret
);
426 let provided
= trait_
.def_id().map(|did
| {
427 cx
.tcx().provided_trait_methods(did
)
429 .map(|meth
| meth
.name
.to_string())
431 }).unwrap_or(HashSet
::new());
433 ret
.push(clean
::Item
{
434 inner
: clean
::ImplItem(clean
::Impl
{
435 unsafety
: hir
::Unsafety
::Normal
, // FIXME: this should be decoded
436 derived
: clean
::detect_derived(&attrs
),
437 provided_trait_methods
: provided
,
439 for_
: ty
.ty
.clean(cx
),
440 generics
: (&ty
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
442 polarity
: polarity
.map(|p
| { p.clean(cx) }
),
444 source
: clean
::Span
::empty(),
447 visibility
: Some(hir
::Inherited
),
448 stability
: stability
::lookup_stability(tcx
, did
).clean(cx
),
449 deprecation
: stability
::lookup_deprecation(tcx
, did
).clean(cx
),
454 fn build_module(cx
: &DocContext
, tcx
: &TyCtxt
,
455 did
: DefId
) -> clean
::Module
{
456 let mut items
= Vec
::new();
457 fill_in(cx
, tcx
, did
, &mut items
);
458 return clean
::Module
{
463 fn fill_in(cx
: &DocContext
, tcx
: &TyCtxt
, did
: DefId
,
464 items
: &mut Vec
<clean
::Item
>) {
465 // If we're reexporting a reexport it may actually reexport something in
466 // two namespaces, so the target may be listed twice. Make sure we only
467 // visit each node at most once.
468 let mut visited
= HashSet
::new();
469 for item
in tcx
.sess
.cstore
.item_children(did
) {
471 cstore
::DlDef(Def
::ForeignMod(did
)) => {
472 fill_in(cx
, tcx
, did
, items
);
474 cstore
::DlDef(def
) if item
.vis
== ty
::Visibility
::Public
=> {
475 if !visited
.insert(def
) { continue }
476 if let Some(i
) = try_inline_def(cx
, tcx
, def
) {
480 cstore
::DlDef(..) => {}
481 // All impls were inlined above
482 cstore
::DlImpl(..) => {}
483 cstore
::DlField
=> panic
!("unimplemented field"),
489 fn build_const(cx
: &DocContext
, tcx
: &TyCtxt
,
490 did
: DefId
) -> clean
::Constant
{
491 use rustc
::hir
::print
as pprust
;
493 let (expr
, ty
) = lookup_const_by_id(tcx
, did
, None
).unwrap_or_else(|| {
494 panic
!("expected lookup_const_by_id to succeed for {:?}", did
);
496 debug
!("converting constant expr {:?} to snippet", expr
);
497 let sn
= pprust
::expr_to_string(expr
);
498 debug
!("got snippet {}", sn
);
501 type_
: ty
.map(|t
| t
.clean(cx
)).unwrap_or_else(|| tcx
.lookup_item_type(did
).ty
.clean(cx
)),
506 fn build_static(cx
: &DocContext
, tcx
: &TyCtxt
,
508 mutable
: bool
) -> clean
::Static
{
510 type_
: tcx
.lookup_item_type(did
).ty
.clean(cx
),
511 mutability
: if mutable {clean::Mutable}
else {clean::Immutable}
,
512 expr
: "\n\n\n".to_string(), // trigger the "[definition]" links
516 /// A trait's generics clause actually contains all of the predicates for all of
517 /// its associated types as well. We specifically move these clauses to the
518 /// associated types instead when displaying, so when we're genering the
519 /// generics for the trait itself we need to be sure to remove them.
521 /// The inverse of this filtering logic can be found in the `Clean`
522 /// implementation for `AssociatedType`
523 fn filter_non_trait_generics(trait_did
: DefId
, mut g
: clean
::Generics
)
525 g
.where_predicates
.retain(|pred
| {
527 clean
::WherePredicate
::BoundPredicate
{
529 self_type
: box clean
::Generic(ref s
),
530 trait_
: box clean
::ResolvedPath { did, .. }
,
533 } => *s
!= "Self" || did
!= trait_did
,
540 /// Supertrait bounds for a trait are also listed in the generics coming from
541 /// the metadata for a crate, so we want to separate those out and create a new
542 /// list of explicit supertrait bounds to render nicely.
543 fn separate_supertrait_bounds(mut g
: clean
::Generics
)
544 -> (clean
::Generics
, Vec
<clean
::TyParamBound
>) {
545 let mut ty_bounds
= Vec
::new();
546 g
.where_predicates
.retain(|pred
| {
548 clean
::WherePredicate
::BoundPredicate
{
549 ty
: clean
::Generic(ref s
),
551 } if *s
== "Self" => {
552 ty_bounds
.extend(bounds
.iter().cloned());