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
;
19 use rustc
::metadata
::csearch
;
20 use rustc
::metadata
::decoder
;
21 use rustc
::middle
::def
;
22 use rustc
::middle
::ty
;
23 use rustc
::middle
::subst
;
24 use rustc
::middle
::stability
;
32 /// Attempt to inline the definition of a local node id into this AST.
34 /// This function will fetch the definition of the id specified, and if it is
35 /// from another crate it will attempt to inline the documentation from the
36 /// other crate into this crate.
38 /// This is primarily used for `pub use` statements which are, in general,
39 /// implementation details. Inlining the documentation should help provide a
40 /// better experience when reading the documentation in this use case.
42 /// The returned value is `None` if the `id` could not be inlined, and `Some`
43 /// of a vector of items if it was successfully expanded.
44 pub fn try_inline(cx
: &DocContext
, id
: ast
::NodeId
, into
: Option
<ast
::Ident
>)
45 -> Option
<Vec
<clean
::Item
>> {
46 let tcx
= match cx
.tcx_opt() {
50 let def
= match tcx
.def_map
.borrow().get(&id
) {
51 Some(d
) => d
.full_def(),
54 let did
= def
.def_id();
55 if ast_util
::is_local(did
) { return None }
56 try_inline_def(cx
, tcx
, def
).map(|vec
| {
57 vec
.into_iter().map(|mut item
| {
59 Some(into
) if item
.name
.is_some() => {
60 item
.name
= Some(into
.clean(cx
));
69 fn try_inline_def(cx
: &DocContext
, tcx
: &ty
::ctxt
,
70 def
: def
::Def
) -> Option
<Vec
<clean
::Item
>> {
71 let mut ret
= Vec
::new();
72 let did
= def
.def_id();
73 let inner
= match def
{
74 def
::DefTrait(did
) => {
75 record_extern_fqn(cx
, did
, clean
::TypeTrait
);
76 clean
::TraitItem(build_external_trait(cx
, tcx
, did
))
78 def
::DefFn(did
, false) => {
79 // If this function is a tuple struct constructor, we just skip it
80 record_extern_fqn(cx
, did
, clean
::TypeFunction
);
81 clean
::FunctionItem(build_external_function(cx
, tcx
, did
))
83 def
::DefStruct(did
) => {
84 record_extern_fqn(cx
, did
, clean
::TypeStruct
);
85 ret
.extend(build_impls(cx
, tcx
, did
).into_iter());
86 clean
::StructItem(build_struct(cx
, tcx
, did
))
88 def
::DefTy(did
, false) => {
89 record_extern_fqn(cx
, did
, clean
::TypeTypedef
);
90 ret
.extend(build_impls(cx
, tcx
, did
).into_iter());
91 build_type(cx
, tcx
, did
)
93 def
::DefTy(did
, true) => {
94 record_extern_fqn(cx
, did
, clean
::TypeEnum
);
95 ret
.extend(build_impls(cx
, tcx
, did
).into_iter());
96 build_type(cx
, tcx
, did
)
98 // Assume that the enum type is reexported next to the variant, and
99 // variants don't show up in documentation specially.
100 def
::DefVariant(..) => return Some(Vec
::new()),
101 def
::DefMod(did
) => {
102 record_extern_fqn(cx
, did
, clean
::TypeModule
);
103 clean
::ModuleItem(build_module(cx
, tcx
, did
))
105 def
::DefStatic(did
, mtbl
) => {
106 record_extern_fqn(cx
, did
, clean
::TypeStatic
);
107 clean
::StaticItem(build_static(cx
, tcx
, did
, mtbl
))
109 def
::DefConst(did
) => {
110 record_extern_fqn(cx
, did
, clean
::TypeConst
);
111 clean
::ConstantItem(build_const(cx
, tcx
, did
))
115 let fqn
= csearch
::get_item_path(tcx
, did
);
116 cx
.inlined
.borrow_mut().as_mut().unwrap().insert(did
);
117 ret
.push(clean
::Item
{
118 source
: clean
::Span
::empty(),
119 name
: Some(fqn
.last().unwrap().to_string()),
120 attrs
: load_attrs(cx
, tcx
, did
),
122 visibility
: Some(ast
::Public
),
123 stability
: stability
::lookup(tcx
, did
).clean(cx
),
129 pub fn load_attrs(cx
: &DocContext
, tcx
: &ty
::ctxt
,
130 did
: ast
::DefId
) -> Vec
<clean
::Attribute
> {
131 let attrs
= csearch
::get_item_attrs(&tcx
.sess
.cstore
, did
);
132 attrs
.into_iter().map(|a
| a
.clean(cx
)).collect()
135 /// Record an external fully qualified name in the external_paths cache.
137 /// These names are used later on by HTML rendering to generate things like
138 /// source links back to the original item.
139 pub fn record_extern_fqn(cx
: &DocContext
, did
: ast
::DefId
, kind
: clean
::TypeKind
) {
142 let fqn
= csearch
::get_item_path(tcx
, did
);
143 let fqn
= fqn
.into_iter().map(|i
| i
.to_string()).collect();
144 cx
.external_paths
.borrow_mut().as_mut().unwrap().insert(did
, (fqn
, kind
));
150 pub fn build_external_trait(cx
: &DocContext
, tcx
: &ty
::ctxt
,
151 did
: ast
::DefId
) -> clean
::Trait
{
152 let def
= ty
::lookup_trait_def(tcx
, did
);
153 let trait_items
= ty
::trait_items(tcx
, did
).clean(cx
);
154 let predicates
= ty
::lookup_predicates(tcx
, did
);
155 let generics
= (&def
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
);
156 let generics
= filter_non_trait_generics(did
, generics
);
157 let (generics
, supertrait_bounds
) = separate_supertrait_bounds(generics
);
159 unsafety
: def
.unsafety
,
162 bounds
: supertrait_bounds
,
166 fn build_external_function(cx
: &DocContext
, tcx
: &ty
::ctxt
, did
: ast
::DefId
) -> clean
::Function
{
167 let t
= ty
::lookup_item_type(tcx
, did
);
168 let (decl
, style
, abi
) = match t
.ty
.sty
{
169 ty
::ty_bare_fn(_
, ref f
) => ((did
, &f
.sig
).clean(cx
), f
.unsafety
, f
.abi
),
170 _
=> panic
!("bad function"),
172 let predicates
= ty
::lookup_predicates(tcx
, did
);
175 generics
: (&t
.generics
, &predicates
, subst
::FnSpace
).clean(cx
),
181 fn build_struct(cx
: &DocContext
, tcx
: &ty
::ctxt
, did
: ast
::DefId
) -> clean
::Struct
{
182 use syntax
::parse
::token
::special_idents
::unnamed_field
;
184 let t
= ty
::lookup_item_type(tcx
, did
);
185 let predicates
= ty
::lookup_predicates(tcx
, did
);
186 let fields
= ty
::lookup_struct_fields(tcx
, did
);
189 struct_type
: match &*fields
{
191 [ref f
] if f
.name
== unnamed_field
.name
=> doctree
::Newtype
,
192 [ref f
, ..] if f
.name
== unnamed_field
.name
=> doctree
::Tuple
,
195 generics
: (&t
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
196 fields
: fields
.clean(cx
),
197 fields_stripped
: false,
201 fn build_type(cx
: &DocContext
, tcx
: &ty
::ctxt
, did
: ast
::DefId
) -> clean
::ItemEnum
{
202 let t
= ty
::lookup_item_type(tcx
, did
);
203 let predicates
= ty
::lookup_predicates(tcx
, did
);
205 ty
::ty_enum(edid
, _
) if !csearch
::is_typedef(&tcx
.sess
.cstore
, did
) => {
206 return clean
::EnumItem(clean
::Enum
{
207 generics
: (&t
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
208 variants_stripped
: false,
209 variants
: ty
::enum_variants(tcx
, edid
).clean(cx
),
215 clean
::TypedefItem(clean
::Typedef
{
216 type_
: t
.ty
.clean(cx
),
217 generics
: (&t
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
221 fn build_impls(cx
: &DocContext
, tcx
: &ty
::ctxt
,
222 did
: ast
::DefId
) -> Vec
<clean
::Item
> {
223 ty
::populate_implementations_for_type_if_necessary(tcx
, did
);
224 let mut impls
= Vec
::new();
226 match tcx
.inherent_impls
.borrow().get(&did
) {
229 impls
.extend(i
.iter().map(|&did
| { build_impl(cx, tcx, did) }
));
233 // If this is the first time we've inlined something from this crate, then
234 // we inline *all* impls from the crate into this crate. Note that there's
235 // currently no way for us to filter this based on type, and we likely need
236 // many impls for a variety of reasons.
238 // Primarily, the impls will be used to populate the documentation for this
239 // type being inlined, but impls can also be used when generating
240 // documentation for primitives (no way to find those specifically).
241 if cx
.populated_crate_impls
.borrow_mut().insert(did
.krate
) {
242 csearch
::each_top_level_item_of_crate(&tcx
.sess
.cstore
,
245 populate_impls(cx
, tcx
, def
, &mut impls
)
248 fn populate_impls(cx
: &DocContext
, tcx
: &ty
::ctxt
,
249 def
: decoder
::DefLike
,
250 impls
: &mut Vec
<Option
<clean
::Item
>>) {
252 decoder
::DlImpl(did
) => impls
.push(build_impl(cx
, tcx
, did
)),
253 decoder
::DlDef(def
::DefMod(did
)) => {
254 csearch
::each_child_of_item(&tcx
.sess
.cstore
,
257 populate_impls(cx
, tcx
, def
, impls
)
265 impls
.into_iter().filter_map(|a
| a
).collect()
268 fn build_impl(cx
: &DocContext
,
270 did
: ast
::DefId
) -> Option
<clean
::Item
> {
271 if !cx
.inlined
.borrow_mut().as_mut().unwrap().insert(did
) {
275 let attrs
= load_attrs(cx
, tcx
, did
);
276 let associated_trait
= csearch
::get_impl_trait(tcx
, did
);
277 if let Some(ref t
) = associated_trait
{
278 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
279 let trait_attrs
= load_attrs(cx
, tcx
, t
.def_id
);
280 if trait_attrs
.iter().any(|a
| is_doc_hidden(a
)) {
285 // If this is a defaulted impl, then bail out early here
286 if csearch
::is_default_impl(&tcx
.sess
.cstore
, did
) {
287 return Some(clean
::Item
{
288 inner
: clean
::DefaultImplItem(clean
::DefaultImpl
{
289 // FIXME: this should be decoded
290 unsafety
: ast
::Unsafety
::Normal
,
291 trait_
: match associated_trait
.as_ref().unwrap().clean(cx
) {
292 clean
::TraitBound(polyt
, _
) => polyt
.trait_
,
293 clean
::RegionBound(..) => unreachable
!(),
296 source
: clean
::Span
::empty(),
299 visibility
: Some(ast
::Inherited
),
300 stability
: stability
::lookup(tcx
, did
).clean(cx
),
305 let predicates
= ty
::lookup_predicates(tcx
, did
);
306 let trait_items
= csearch
::get_impl_items(&tcx
.sess
.cstore
, did
)
309 let did
= did
.def_id();
310 let impl_item
= ty
::impl_or_trait_item(tcx
, did
);
312 ty
::MethodTraitItem(method
) => {
313 if method
.vis
!= ast
::Public
&& associated_trait
.is_none() {
316 if method
.provided_source
.is_some() {
319 let mut item
= method
.clean(cx
);
320 item
.inner
= match item
.inner
.clone() {
321 clean
::TyMethodItem(clean
::TyMethod
{
322 unsafety
, decl
, self_
, generics
, abi
324 clean
::MethodItem(clean
::Method
{
332 _
=> panic
!("not a tymethod"),
336 ty
::TypeTraitItem(ref assoc_ty
) => {
337 let did
= assoc_ty
.def_id
;
338 let type_scheme
= ty
::lookup_item_type(tcx
, did
);
339 let predicates
= ty
::lookup_predicates(tcx
, did
);
340 // Not sure the choice of ParamSpace actually matters here,
341 // because an associated type won't have generics on the LHS
342 let typedef
= (type_scheme
, predicates
,
343 subst
::ParamSpace
::TypeSpace
).clean(cx
);
345 name
: Some(assoc_ty
.name
.clean(cx
)),
346 inner
: clean
::TypedefItem(typedef
),
347 source
: clean
::Span
::empty(),
350 stability
: stability
::lookup(tcx
, did
).clean(cx
),
356 let polarity
= csearch
::get_impl_polarity(tcx
, did
);
357 let ty
= ty
::lookup_item_type(tcx
, did
);
358 return Some(clean
::Item
{
359 inner
: clean
::ImplItem(clean
::Impl
{
360 unsafety
: ast
::Unsafety
::Normal
, // FIXME: this should be decoded
361 derived
: clean
::detect_derived(&attrs
),
362 trait_
: associated_trait
.clean(cx
).map(|bound
| {
364 clean
::TraitBound(polyt
, _
) => polyt
.trait_
,
365 clean
::RegionBound(..) => unreachable
!(),
368 for_
: ty
.ty
.clean(cx
),
369 generics
: (&ty
.generics
, &predicates
, subst
::TypeSpace
).clean(cx
),
371 polarity
: polarity
.map(|p
| { p.clean(cx) }
),
373 source
: clean
::Span
::empty(),
376 visibility
: Some(ast
::Inherited
),
377 stability
: stability
::lookup(tcx
, did
).clean(cx
),
381 fn is_doc_hidden(a
: &clean
::Attribute
) -> bool
{
383 clean
::List(ref name
, ref inner
) if *name
== "doc" => {
384 inner
.iter().any(|a
| {
386 clean
::Word(ref s
) => *s
== "hidden",
396 fn build_module(cx
: &DocContext
, tcx
: &ty
::ctxt
,
397 did
: ast
::DefId
) -> clean
::Module
{
398 let mut items
= Vec
::new();
399 fill_in(cx
, tcx
, did
, &mut items
);
400 return clean
::Module
{
405 fn fill_in(cx
: &DocContext
, tcx
: &ty
::ctxt
, did
: ast
::DefId
,
406 items
: &mut Vec
<clean
::Item
>) {
407 // If we're reexporting a reexport it may actually reexport something in
408 // two namespaces, so the target may be listed twice. Make sure we only
409 // visit each node at most once.
410 let mut visited
= HashSet
::new();
411 csearch
::each_child_of_item(&tcx
.sess
.cstore
, did
, |def
, _
, vis
| {
413 decoder
::DlDef(def
::DefForeignMod(did
)) => {
414 fill_in(cx
, tcx
, did
, items
);
416 decoder
::DlDef(def
) if vis
== ast
::Public
=> {
417 if !visited
.insert(def
) { return }
418 match try_inline_def(cx
, tcx
, def
) {
419 Some(i
) => items
.extend(i
.into_iter()),
423 decoder
::DlDef(..) => {}
424 // All impls were inlined above
425 decoder
::DlImpl(..) => {}
426 decoder
::DlField
=> panic
!("unimplemented field"),
432 fn build_const(cx
: &DocContext
, tcx
: &ty
::ctxt
,
433 did
: ast
::DefId
) -> clean
::Constant
{
434 use rustc
::middle
::const_eval
;
435 use syntax
::print
::pprust
;
437 let expr
= const_eval
::lookup_const_by_id(tcx
, did
).unwrap_or_else(|| {
438 panic
!("expected lookup_const_by_id to succeed for {:?}", did
);
440 debug
!("converting constant expr {:?} to snippet", expr
);
441 let sn
= pprust
::expr_to_string(expr
);
442 debug
!("got snippet {}", sn
);
445 type_
: ty
::lookup_item_type(tcx
, did
).ty
.clean(cx
),
450 fn build_static(cx
: &DocContext
, tcx
: &ty
::ctxt
,
452 mutable
: bool
) -> clean
::Static
{
454 type_
: ty
::lookup_item_type(tcx
, did
).ty
.clean(cx
),
455 mutability
: if mutable {clean::Mutable}
else {clean::Immutable}
,
456 expr
: "\n\n\n".to_string(), // trigger the "[definition]" links
460 /// A trait's generics clause actually contains all of the predicates for all of
461 /// its associated types as well. We specifically move these clauses to the
462 /// associated types instead when displaying, so when we're genering the
463 /// generics for the trait itself we need to be sure to remove them.
465 /// The inverse of this filtering logic can be found in the `Clean`
466 /// implementation for `AssociatedType`
467 fn filter_non_trait_generics(trait_did
: ast
::DefId
, mut g
: clean
::Generics
)
469 g
.where_predicates
.retain(|pred
| {
471 clean
::WherePredicate
::BoundPredicate
{
473 self_type
: box clean
::Generic(ref s
),
474 trait_
: box clean
::ResolvedPath { did, .. }
,
477 } => *s
!= "Self" || did
!= trait_did
,
484 /// Supertrait bounds for a trait are also listed in the generics coming from
485 /// the metadata for a crate, so we want to separate those out and create a new
486 /// list of explicit supertrait bounds to render nicely.
487 fn separate_supertrait_bounds(mut g
: clean
::Generics
)
488 -> (clean
::Generics
, Vec
<clean
::TyParamBound
>) {
489 let mut ty_bounds
= Vec
::new();
490 g
.where_predicates
.retain(|pred
| {
492 clean
::WherePredicate
::BoundPredicate
{
493 ty
: clean
::Generic(ref s
),
495 } if *s
== "Self" => {
496 ty_bounds
.extend(bounds
.iter().cloned());