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