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