]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
bd49e46f6fb54a40480bac64eccceb8841f1d0e0
[rust.git] / src / librustdoc / clean / inline.rs
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.
4 //
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.
10
11 //! Support for inlining external documentation into the current AST.
12
13 use std::collections::BTreeMap;
14 use std::io;
15 use std::iter::once;
16 use std::rc::Rc;
17
18 use syntax::ast;
19 use rustc::hir;
20
21 use rustc::hir::def::{Def, CtorKind};
22 use rustc::hir::def_id::DefId;
23 use rustc::ty;
24 use rustc::util::nodemap::FxHashSet;
25
26 use core::{DocContext, DocAccessLevels};
27 use doctree;
28 use clean::{self, GetDefId};
29
30 use super::Clean;
31
32 /// Attempt to inline a definition into this AST.
33 ///
34 /// This function will fetch the definition specified, and if it is
35 /// from another crate it will attempt to inline the documentation
36 /// from the other crate into this crate.
37 ///
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.
41 ///
42 /// The returned value is `None` if the definition could not be inlined,
43 /// and `Some` of a vector of items if it was successfully expanded.
44 pub fn try_inline(cx: &DocContext, def: Def, name: ast::Name)
45                   -> Option<Vec<clean::Item>> {
46     if def == Def::Err { return None }
47     let did = def.def_id();
48     if did.is_local() { return None }
49     let mut ret = Vec::new();
50     let inner = match def {
51         Def::Trait(did) => {
52             record_extern_fqn(cx, did, clean::TypeKind::Trait);
53             ret.extend(build_impls(cx, did));
54             clean::TraitItem(build_external_trait(cx, did))
55         }
56         Def::Fn(did) => {
57             record_extern_fqn(cx, did, clean::TypeKind::Function);
58             clean::FunctionItem(build_external_function(cx, did))
59         }
60         Def::Struct(did) => {
61             record_extern_fqn(cx, did, clean::TypeKind::Struct);
62             ret.extend(build_impls(cx, did));
63             clean::StructItem(build_struct(cx, did))
64         }
65         Def::Union(did) => {
66             record_extern_fqn(cx, did, clean::TypeKind::Union);
67             ret.extend(build_impls(cx, did));
68             clean::UnionItem(build_union(cx, did))
69         }
70         Def::TyAlias(did) => {
71             record_extern_fqn(cx, did, clean::TypeKind::Typedef);
72             ret.extend(build_impls(cx, did));
73             clean::TypedefItem(build_type_alias(cx, did), false)
74         }
75         Def::Enum(did) => {
76             record_extern_fqn(cx, did, clean::TypeKind::Enum);
77             ret.extend(build_impls(cx, did));
78             clean::EnumItem(build_enum(cx, did))
79         }
80         // Never inline enum variants but leave them shown as reexports.
81         Def::Variant(..) => return None,
82         // Assume that enum variants and struct types are reexported next to
83         // their constructors.
84         Def::VariantCtor(..) |
85         Def::StructCtor(..) => return Some(Vec::new()),
86         Def::Mod(did) => {
87             record_extern_fqn(cx, did, clean::TypeKind::Module);
88             clean::ModuleItem(build_module(cx, did))
89         }
90         Def::Static(did, mtbl) => {
91             record_extern_fqn(cx, did, clean::TypeKind::Static);
92             clean::StaticItem(build_static(cx, did, mtbl))
93         }
94         Def::Const(did) => {
95             record_extern_fqn(cx, did, clean::TypeKind::Const);
96             clean::ConstantItem(build_const(cx, did))
97         }
98         _ => return None,
99     };
100     cx.renderinfo.borrow_mut().inlined.insert(did);
101     ret.push(clean::Item {
102         source: cx.tcx.def_span(did).clean(cx),
103         name: Some(name.clean(cx)),
104         attrs: load_attrs(cx, did),
105         inner,
106         visibility: Some(clean::Public),
107         stability: cx.tcx.lookup_stability(did).clean(cx),
108         deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
109         def_id: did,
110     });
111     Some(ret)
112 }
113
114 pub fn load_attrs(cx: &DocContext, did: DefId) -> clean::Attributes {
115     cx.tcx.get_attrs(did).clean(cx)
116 }
117
118 /// Record an external fully qualified name in the external_paths cache.
119 ///
120 /// These names are used later on by HTML rendering to generate things like
121 /// source links back to the original item.
122 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
123     let crate_name = cx.tcx.sess.cstore.crate_name(did.krate).to_string();
124     let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
125         // extern blocks have an empty name
126         let s = elem.data.to_string();
127         if !s.is_empty() {
128             Some(s)
129         } else {
130             None
131         }
132     });
133     let fqn = once(crate_name).chain(relative).collect();
134     cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
135 }
136
137 pub fn build_external_trait(cx: &DocContext, did: DefId) -> clean::Trait {
138     let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
139     let predicates = cx.tcx.predicates_of(did);
140     let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
141     let generics = filter_non_trait_generics(did, generics);
142     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
143     clean::Trait {
144         unsafety: cx.tcx.trait_def(did).unsafety,
145         generics,
146         items: trait_items,
147         bounds: supertrait_bounds,
148     }
149 }
150
151 fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function {
152     let sig = cx.tcx.fn_sig(did);
153
154     let constness = if cx.tcx.is_const_fn(did) {
155         hir::Constness::Const
156     } else {
157         hir::Constness::NotConst
158     };
159
160     let predicates = cx.tcx.predicates_of(did);
161     clean::Function {
162         decl: (did, sig).clean(cx),
163         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
164         unsafety: sig.unsafety(),
165         constness,
166         abi: sig.abi(),
167     }
168 }
169
170 fn build_enum(cx: &DocContext, did: DefId) -> clean::Enum {
171     let predicates = cx.tcx.predicates_of(did);
172
173     clean::Enum {
174         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
175         variants_stripped: false,
176         variants: cx.tcx.adt_def(did).variants.clean(cx),
177     }
178 }
179
180 fn build_struct(cx: &DocContext, did: DefId) -> clean::Struct {
181     let predicates = cx.tcx.predicates_of(did);
182     let variant = cx.tcx.adt_def(did).struct_variant();
183
184     clean::Struct {
185         struct_type: match variant.ctor_kind {
186             CtorKind::Fictive => doctree::Plain,
187             CtorKind::Fn => doctree::Tuple,
188             CtorKind::Const => doctree::Unit,
189         },
190         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
191         fields: variant.fields.clean(cx),
192         fields_stripped: false,
193     }
194 }
195
196 fn build_union(cx: &DocContext, did: DefId) -> clean::Union {
197     let predicates = cx.tcx.predicates_of(did);
198     let variant = cx.tcx.adt_def(did).struct_variant();
199
200     clean::Union {
201         struct_type: doctree::Plain,
202         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
203         fields: variant.fields.clean(cx),
204         fields_stripped: false,
205     }
206 }
207
208 fn build_type_alias(cx: &DocContext, did: DefId) -> clean::Typedef {
209     let predicates = cx.tcx.predicates_of(did);
210
211     clean::Typedef {
212         type_: cx.tcx.type_of(did).clean(cx),
213         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
214     }
215 }
216
217 pub fn build_impls(cx: &DocContext, did: DefId) -> Vec<clean::Item> {
218     let tcx = cx.tcx;
219     let mut impls = Vec::new();
220
221     for &did in tcx.inherent_impls(did).iter() {
222         build_impl(cx, did, &mut impls);
223     }
224
225     // If this is the first time we've inlined something from another crate, then
226     // we inline *all* impls from all the crates into this crate. Note that there's
227     // currently no way for us to filter this based on type, and we likely need
228     // many impls for a variety of reasons.
229     //
230     // Primarily, the impls will be used to populate the documentation for this
231     // type being inlined, but impls can also be used when generating
232     // documentation for primitives (no way to find those specifically).
233     if cx.populated_all_crate_impls.get() {
234         return impls;
235     }
236
237     cx.populated_all_crate_impls.set(true);
238
239     for cnum in tcx.sess.cstore.crates() {
240         for did in tcx.all_trait_implementations(cnum).iter() {
241             build_impl(cx, *did, &mut impls);
242         }
243     }
244
245     // Also try to inline primitive impls from other crates.
246     let primitive_impls = [
247         tcx.lang_items.isize_impl(),
248         tcx.lang_items.i8_impl(),
249         tcx.lang_items.i16_impl(),
250         tcx.lang_items.i32_impl(),
251         tcx.lang_items.i64_impl(),
252         tcx.lang_items.i128_impl(),
253         tcx.lang_items.usize_impl(),
254         tcx.lang_items.u8_impl(),
255         tcx.lang_items.u16_impl(),
256         tcx.lang_items.u32_impl(),
257         tcx.lang_items.u64_impl(),
258         tcx.lang_items.u128_impl(),
259         tcx.lang_items.f32_impl(),
260         tcx.lang_items.f64_impl(),
261         tcx.lang_items.char_impl(),
262         tcx.lang_items.str_impl(),
263         tcx.lang_items.slice_impl(),
264         tcx.lang_items.const_ptr_impl(),
265         tcx.lang_items.mut_ptr_impl(),
266     ];
267
268     for def_id in primitive_impls.iter().filter_map(|&def_id| def_id) {
269         if !def_id.is_local() {
270             build_impl(cx, def_id, &mut impls);
271         }
272     }
273
274     impls
275 }
276
277 pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
278     if !cx.renderinfo.borrow_mut().inlined.insert(did) {
279         return
280     }
281
282     let attrs = load_attrs(cx, did);
283     let tcx = cx.tcx;
284     let associated_trait = tcx.impl_trait_ref(did);
285
286     // Only inline impl if the implemented trait is
287     // reachable in rustdoc generated documentation
288     if let Some(traitref) = associated_trait {
289         if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
290             return
291         }
292     }
293
294     // If this is a defaulted impl, then bail out early here
295     if tcx.is_default_impl(did) {
296         return ret.push(clean::Item {
297             inner: clean::DefaultImplItem(clean::DefaultImpl {
298                 // FIXME: this should be decoded
299                 unsafety: hir::Unsafety::Normal,
300                 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
301                     clean::TraitBound(polyt, _) => polyt.trait_,
302                     clean::RegionBound(..) => unreachable!(),
303                 },
304             }),
305             source: tcx.def_span(did).clean(cx),
306             name: None,
307             attrs,
308             visibility: Some(clean::Inherited),
309             stability: tcx.lookup_stability(did).clean(cx),
310             deprecation: tcx.lookup_deprecation(did).clean(cx),
311             def_id: did,
312         });
313     }
314
315     let for_ = tcx.type_of(did).clean(cx);
316
317     // Only inline impl if the implementing type is
318     // reachable in rustdoc generated documentation
319     if let Some(did) = for_.def_id() {
320         if !cx.access_levels.borrow().is_doc_reachable(did) {
321             return
322         }
323     }
324
325     let predicates = tcx.predicates_of(did);
326     let trait_items = tcx.associated_items(did).filter_map(|item| {
327         match item.kind {
328             ty::AssociatedKind::Const => {
329                 let default = if item.defaultness.has_value() {
330                     Some(print_inlined_const(cx, item.def_id))
331                 } else {
332                     None
333                 };
334                 Some(clean::Item {
335                     name: Some(item.name.clean(cx)),
336                     inner: clean::AssociatedConstItem(
337                         tcx.type_of(item.def_id).clean(cx),
338                         default,
339                     ),
340                     source: tcx.def_span(item.def_id).clean(cx),
341                     attrs: clean::Attributes::default(),
342                     visibility: None,
343                     stability: tcx.lookup_stability(item.def_id).clean(cx),
344                     deprecation: tcx.lookup_deprecation(item.def_id).clean(cx),
345                     def_id: item.def_id
346                 })
347             }
348             ty::AssociatedKind::Method => {
349                 if item.vis != ty::Visibility::Public && associated_trait.is_none() {
350                     return None
351                 }
352                 let mut cleaned = item.clean(cx);
353                 cleaned.inner = match cleaned.inner.clone() {
354                     clean::TyMethodItem(clean::TyMethod {
355                         unsafety, decl, generics, abi
356                     }) => {
357                         let constness = if tcx.is_const_fn(item.def_id) {
358                             hir::Constness::Const
359                         } else {
360                             hir::Constness::NotConst
361                         };
362
363                         clean::MethodItem(clean::Method {
364                             unsafety,
365                             constness,
366                             decl,
367                             generics,
368                             abi,
369                         })
370                     }
371                     ref r => panic!("not a tymethod: {:?}", r),
372                 };
373                 Some(cleaned)
374             }
375             ty::AssociatedKind::Type => {
376                 let typedef = clean::Typedef {
377                     type_: tcx.type_of(item.def_id).clean(cx),
378                     generics: clean::Generics {
379                         lifetimes: vec![],
380                         type_params: vec![],
381                         where_predicates: vec![]
382                     }
383                 };
384                 Some(clean::Item {
385                     name: Some(item.name.clean(cx)),
386                     inner: clean::TypedefItem(typedef, true),
387                     source: tcx.def_span(item.def_id).clean(cx),
388                     attrs: clean::Attributes::default(),
389                     visibility: None,
390                     stability: tcx.lookup_stability(item.def_id).clean(cx),
391                     deprecation: tcx.lookup_deprecation(item.def_id).clean(cx),
392                     def_id: item.def_id
393                 })
394             }
395         }
396     }).collect::<Vec<_>>();
397     let polarity = tcx.impl_polarity(did);
398     let trait_ = associated_trait.clean(cx).map(|bound| {
399         match bound {
400             clean::TraitBound(polyt, _) => polyt.trait_,
401             clean::RegionBound(..) => unreachable!(),
402         }
403     });
404     if trait_.def_id() == tcx.lang_items.deref_trait() {
405         super::build_deref_target_impls(cx, &trait_items, ret);
406     }
407
408     let provided = trait_.def_id().map(|did| {
409         tcx.provided_trait_methods(did)
410             .into_iter()
411             .map(|meth| meth.name.to_string())
412             .collect()
413     }).unwrap_or(FxHashSet());
414
415     ret.push(clean::Item {
416         inner: clean::ImplItem(clean::Impl {
417             unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
418             provided_trait_methods: provided,
419             trait_,
420             for_,
421             generics: (tcx.generics_of(did), &predicates).clean(cx),
422             items: trait_items,
423             polarity: Some(polarity.clean(cx)),
424         }),
425         source: tcx.def_span(did).clean(cx),
426         name: None,
427         attrs,
428         visibility: Some(clean::Inherited),
429         stability: tcx.lookup_stability(did).clean(cx),
430         deprecation: tcx.lookup_deprecation(did).clean(cx),
431         def_id: did,
432     });
433 }
434
435 fn build_module(cx: &DocContext, did: DefId) -> clean::Module {
436     let mut items = Vec::new();
437     fill_in(cx, did, &mut items);
438     return clean::Module {
439         items,
440         is_crate: false,
441     };
442
443     fn fill_in(cx: &DocContext, did: DefId, items: &mut Vec<clean::Item>) {
444         // If we're reexporting a reexport it may actually reexport something in
445         // two namespaces, so the target may be listed twice. Make sure we only
446         // visit each node at most once.
447         let mut visited = FxHashSet();
448         for item in cx.tcx.sess.cstore.item_children(did, cx.tcx.sess) {
449             let def_id = item.def.def_id();
450             if cx.tcx.sess.cstore.visibility(def_id) == ty::Visibility::Public {
451                 if !visited.insert(def_id) { continue }
452                 if let Some(i) = try_inline(cx, item.def, item.ident.name) {
453                     items.extend(i)
454                 }
455             }
456         }
457     }
458 }
459
460 struct InlinedConst {
461     nested_bodies: Rc<BTreeMap<hir::BodyId, hir::Body>>
462 }
463
464 impl hir::print::PpAnn for InlinedConst {
465     fn nested(&self, state: &mut hir::print::State, nested: hir::print::Nested)
466               -> io::Result<()> {
467         if let hir::print::Nested::Body(body) = nested {
468             state.print_expr(&self.nested_bodies[&body].value)
469         } else {
470             Ok(())
471         }
472     }
473 }
474
475 fn print_inlined_const(cx: &DocContext, did: DefId) -> String {
476     let body = cx.tcx.sess.cstore.item_body(cx.tcx, did);
477     let inlined = InlinedConst {
478         nested_bodies: cx.tcx.item_body_nested_bodies(did)
479     };
480     hir::print::to_string(&inlined, |s| s.print_expr(&body.value))
481 }
482
483 fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
484     clean::Constant {
485         type_: cx.tcx.type_of(did).clean(cx),
486         expr: print_inlined_const(cx, did)
487     }
488 }
489
490 fn build_static(cx: &DocContext, did: DefId, mutable: bool) -> clean::Static {
491     clean::Static {
492         type_: cx.tcx.type_of(did).clean(cx),
493         mutability: if mutable {clean::Mutable} else {clean::Immutable},
494         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
495     }
496 }
497
498 /// A trait's generics clause actually contains all of the predicates for all of
499 /// its associated types as well. We specifically move these clauses to the
500 /// associated types instead when displaying, so when we're generating the
501 /// generics for the trait itself we need to be sure to remove them.
502 /// We also need to remove the implied "recursive" Self: Trait bound.
503 ///
504 /// The inverse of this filtering logic can be found in the `Clean`
505 /// implementation for `AssociatedType`
506 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
507                              -> clean::Generics {
508     for pred in &mut g.where_predicates {
509         match *pred {
510             clean::WherePredicate::BoundPredicate {
511                 ty: clean::Generic(ref s),
512                 ref mut bounds
513             } if *s == "Self" => {
514                 bounds.retain(|bound| {
515                     match *bound {
516                         clean::TyParamBound::TraitBound(clean::PolyTrait {
517                             trait_: clean::ResolvedPath { did, .. },
518                             ..
519                         }, _) => did != trait_did,
520                         _ => true
521                     }
522                 });
523             }
524             _ => {}
525         }
526     }
527
528     g.where_predicates.retain(|pred| {
529         match *pred {
530             clean::WherePredicate::BoundPredicate {
531                 ty: clean::QPath {
532                     self_type: box clean::Generic(ref s),
533                     trait_: box clean::ResolvedPath { did, .. },
534                     name: ref _name,
535                 }, ref bounds
536             } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
537             _ => true,
538         }
539     });
540     g
541 }
542
543 /// Supertrait bounds for a trait are also listed in the generics coming from
544 /// the metadata for a crate, so we want to separate those out and create a new
545 /// list of explicit supertrait bounds to render nicely.
546 fn separate_supertrait_bounds(mut g: clean::Generics)
547                               -> (clean::Generics, Vec<clean::TyParamBound>) {
548     let mut ty_bounds = Vec::new();
549     g.where_predicates.retain(|pred| {
550         match *pred {
551             clean::WherePredicate::BoundPredicate {
552                 ty: clean::Generic(ref s),
553                 ref bounds
554             } if *s == "Self" => {
555                 ty_bounds.extend(bounds.iter().cloned());
556                 false
557             }
558             _ => true,
559         }
560     });
561     (g, ty_bounds)
562 }