]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
rustdoc: import cross-crate macros alongside everything else
[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::iter::once;
14
15 use syntax::ast;
16 use syntax::ext::base::MacroKind;
17 use syntax_pos::Span;
18
19 use rustc::hir;
20 use rustc::hir::def::{Def, CtorKind};
21 use rustc::hir::def_id::DefId;
22 use rustc::middle::cstore::LoadedMacro;
23 use rustc::ty;
24 use rustc::util::nodemap::FxHashSet;
25
26 use core::{DocContext, DocAccessLevels};
27 use doctree;
28 use clean::{self, GetDefId, ToSource, 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, visited: &mut FxHashSet<DefId>)
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, visited))
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         // FIXME(misdreavus): if attributes/derives come down here we should probably document them
104         // separately
105         Def::Macro(did, MacroKind::Bang) => {
106             record_extern_fqn(cx, did, clean::TypeKind::Macro);
107             clean::MacroItem(build_macro(cx, did))
108         }
109         _ => return None,
110     };
111     cx.renderinfo.borrow_mut().inlined.insert(did);
112     ret.push(clean::Item {
113         source: cx.tcx.def_span(did).clean(cx),
114         name: Some(name.clean(cx)),
115         attrs: load_attrs(cx, did),
116         inner,
117         visibility: Some(clean::Public),
118         stability: cx.tcx.lookup_stability(did).clean(cx),
119         deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
120         def_id: did,
121     });
122     Some(ret)
123 }
124
125 pub fn try_inline_glob(cx: &DocContext, def: Def, visited: &mut FxHashSet<DefId>)
126     -> Option<Vec<clean::Item>>
127 {
128     if def == Def::Err { return None }
129     let did = def.def_id();
130     if did.is_local() { return None }
131
132     match def {
133         Def::Mod(did) => {
134             let m = build_module(cx, did, visited);
135             Some(m.items)
136         }
137         // glob imports on things like enums aren't inlined even for local exports, so just bail
138         _ => None,
139     }
140 }
141
142 pub fn load_attrs(cx: &DocContext, did: DefId) -> clean::Attributes {
143     cx.tcx.get_attrs(did).clean(cx)
144 }
145
146 /// Record an external fully qualified name in the external_paths cache.
147 ///
148 /// These names are used later on by HTML rendering to generate things like
149 /// source links back to the original item.
150 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
151     if did.is_local() {
152         debug!("record_extern_fqn(did={:?}, kind+{:?}): def_id is local, aborting", did, kind);
153         return;
154     }
155
156     let crate_name = cx.tcx.crate_name(did.krate).to_string();
157     let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
158         // extern blocks have an empty name
159         let s = elem.data.to_string();
160         if !s.is_empty() {
161             Some(s)
162         } else {
163             None
164         }
165     });
166     let fqn = if let clean::TypeKind::Macro = kind {
167         vec![crate_name, relative.last().unwrap()]
168     } else {
169         once(crate_name).chain(relative).collect()
170     };
171     cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
172 }
173
174 pub fn build_external_trait(cx: &DocContext, did: DefId) -> clean::Trait {
175     let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
176     let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
177     let predicates = cx.tcx.predicates_of(did);
178     let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
179     let generics = filter_non_trait_generics(did, generics);
180     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
181     let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
182     let is_auto = cx.tcx.trait_is_auto(did);
183     clean::Trait {
184         auto: auto_trait,
185         unsafety: cx.tcx.trait_def(did).unsafety,
186         generics,
187         items: trait_items,
188         bounds: supertrait_bounds,
189         is_spotlight,
190         is_auto,
191     }
192 }
193
194 fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function {
195     let sig = cx.tcx.fn_sig(did);
196
197     let constness = if cx.tcx.is_const_fn(did) {
198         hir::Constness::Const
199     } else {
200         hir::Constness::NotConst
201     };
202
203     let predicates = cx.tcx.predicates_of(did);
204     clean::Function {
205         decl: (did, sig).clean(cx),
206         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
207         unsafety: sig.unsafety(),
208         constness,
209         abi: sig.abi(),
210     }
211 }
212
213 fn build_enum(cx: &DocContext, did: DefId) -> clean::Enum {
214     let predicates = cx.tcx.predicates_of(did);
215
216     clean::Enum {
217         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
218         variants_stripped: false,
219         variants: cx.tcx.adt_def(did).variants.clean(cx),
220     }
221 }
222
223 fn build_struct(cx: &DocContext, did: DefId) -> clean::Struct {
224     let predicates = cx.tcx.predicates_of(did);
225     let variant = cx.tcx.adt_def(did).non_enum_variant();
226
227     clean::Struct {
228         struct_type: match variant.ctor_kind {
229             CtorKind::Fictive => doctree::Plain,
230             CtorKind::Fn => doctree::Tuple,
231             CtorKind::Const => doctree::Unit,
232         },
233         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
234         fields: variant.fields.clean(cx),
235         fields_stripped: false,
236     }
237 }
238
239 fn build_union(cx: &DocContext, did: DefId) -> clean::Union {
240     let predicates = cx.tcx.predicates_of(did);
241     let variant = cx.tcx.adt_def(did).non_enum_variant();
242
243     clean::Union {
244         struct_type: doctree::Plain,
245         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
246         fields: variant.fields.clean(cx),
247         fields_stripped: false,
248     }
249 }
250
251 fn build_type_alias(cx: &DocContext, did: DefId) -> clean::Typedef {
252     let predicates = cx.tcx.predicates_of(did);
253
254     clean::Typedef {
255         type_: cx.tcx.type_of(did).clean(cx),
256         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
257     }
258 }
259
260 pub fn build_impls(cx: &DocContext, did: DefId, auto_traits: bool) -> Vec<clean::Item> {
261     let tcx = cx.tcx;
262     let mut impls = Vec::new();
263
264     for &did in tcx.inherent_impls(did).iter() {
265         build_impl(cx, did, &mut impls);
266     }
267
268     if auto_traits {
269         let auto_impls = get_auto_traits_with_def_id(cx, did);
270         let mut renderinfo = cx.renderinfo.borrow_mut();
271
272         let new_impls: Vec<clean::Item> = auto_impls.into_iter()
273             .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
274
275         impls.extend(new_impls);
276     }
277
278     // If this is the first time we've inlined something from another crate, then
279     // we inline *all* impls from all the crates into this crate. Note that there's
280     // currently no way for us to filter this based on type, and we likely need
281     // many impls for a variety of reasons.
282     //
283     // Primarily, the impls will be used to populate the documentation for this
284     // type being inlined, but impls can also be used when generating
285     // documentation for primitives (no way to find those specifically).
286     if cx.populated_all_crate_impls.get() {
287         return impls;
288     }
289
290     cx.populated_all_crate_impls.set(true);
291
292     for &cnum in tcx.crates().iter() {
293         for did in tcx.all_trait_implementations(cnum).iter() {
294             build_impl(cx, *did, &mut impls);
295         }
296     }
297
298     // Also try to inline primitive impls from other crates.
299     let lang_items = tcx.lang_items();
300     let primitive_impls = [
301         lang_items.isize_impl(),
302         lang_items.i8_impl(),
303         lang_items.i16_impl(),
304         lang_items.i32_impl(),
305         lang_items.i64_impl(),
306         lang_items.i128_impl(),
307         lang_items.usize_impl(),
308         lang_items.u8_impl(),
309         lang_items.u16_impl(),
310         lang_items.u32_impl(),
311         lang_items.u64_impl(),
312         lang_items.u128_impl(),
313         lang_items.f32_impl(),
314         lang_items.f64_impl(),
315         lang_items.f32_runtime_impl(),
316         lang_items.f64_runtime_impl(),
317         lang_items.char_impl(),
318         lang_items.str_impl(),
319         lang_items.slice_impl(),
320         lang_items.slice_u8_impl(),
321         lang_items.str_alloc_impl(),
322         lang_items.slice_alloc_impl(),
323         lang_items.slice_u8_alloc_impl(),
324         lang_items.const_ptr_impl(),
325         lang_items.mut_ptr_impl(),
326     ];
327
328     for def_id in primitive_impls.iter().filter_map(|&def_id| def_id) {
329         if !def_id.is_local() {
330             build_impl(cx, def_id, &mut impls);
331
332             let auto_impls = get_auto_traits_with_def_id(cx, def_id);
333             let mut renderinfo = cx.renderinfo.borrow_mut();
334
335             let new_impls: Vec<clean::Item> = auto_impls.into_iter()
336                 .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
337
338             impls.extend(new_impls);
339         }
340     }
341
342     impls
343 }
344
345 pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
346     if !cx.renderinfo.borrow_mut().inlined.insert(did) {
347         return
348     }
349
350     let attrs = load_attrs(cx, did);
351     let tcx = cx.tcx;
352     let associated_trait = tcx.impl_trait_ref(did);
353
354     // Only inline impl if the implemented trait is
355     // reachable in rustdoc generated documentation
356     if let Some(traitref) = associated_trait {
357         if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
358             return
359         }
360     }
361
362     let for_ = tcx.type_of(did).clean(cx);
363
364     // Only inline impl if the implementing type is
365     // reachable in rustdoc generated documentation
366     if let Some(did) = for_.def_id() {
367         if !cx.access_levels.borrow().is_doc_reachable(did) {
368             return
369         }
370     }
371
372     let predicates = tcx.predicates_of(did);
373     let trait_items = tcx.associated_items(did).filter_map(|item| {
374         if associated_trait.is_some() || item.vis == ty::Visibility::Public {
375             Some(item.clean(cx))
376         } else {
377             None
378         }
379     }).collect::<Vec<_>>();
380     let polarity = tcx.impl_polarity(did);
381     let trait_ = associated_trait.clean(cx).map(|bound| {
382         match bound {
383             clean::TraitBound(polyt, _) => polyt.trait_,
384             clean::RegionBound(..) => unreachable!(),
385         }
386     });
387     if trait_.def_id() == tcx.lang_items().deref_trait() {
388         super::build_deref_target_impls(cx, &trait_items, ret);
389     }
390     if let Some(trait_did) = trait_.def_id() {
391         record_extern_trait(cx, trait_did);
392     }
393
394     let provided = trait_.def_id().map(|did| {
395         tcx.provided_trait_methods(did)
396             .into_iter()
397             .map(|meth| meth.name.to_string())
398             .collect()
399     }).unwrap_or(FxHashSet());
400
401     ret.push(clean::Item {
402         inner: clean::ImplItem(clean::Impl {
403             unsafety: hir::Unsafety::Normal,
404             generics: (tcx.generics_of(did), &predicates).clean(cx),
405             provided_trait_methods: provided,
406             trait_,
407             for_,
408             items: trait_items,
409             polarity: Some(polarity.clean(cx)),
410             synthetic: false,
411         }),
412         source: tcx.def_span(did).clean(cx),
413         name: None,
414         attrs,
415         visibility: Some(clean::Inherited),
416         stability: tcx.lookup_stability(did).clean(cx),
417         deprecation: tcx.lookup_deprecation(did).clean(cx),
418         def_id: did,
419     });
420 }
421
422 fn build_module(cx: &DocContext, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
423     let mut items = Vec::new();
424     fill_in(cx, did, &mut items, visited);
425     return clean::Module {
426         items,
427         is_crate: false,
428     };
429
430     fn fill_in(cx: &DocContext, did: DefId, items: &mut Vec<clean::Item>,
431                visited: &mut FxHashSet<DefId>) {
432         // If we're re-exporting a re-export it may actually re-export something in
433         // two namespaces, so the target may be listed twice. Make sure we only
434         // visit each node at most once.
435         for &item in cx.tcx.item_children(did).iter() {
436             let def_id = item.def.def_id();
437             if item.vis == ty::Visibility::Public {
438                 if did == def_id || !visited.insert(def_id) { continue }
439                 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
440                     items.extend(i)
441                 }
442             }
443         }
444     }
445 }
446
447 pub fn print_inlined_const(cx: &DocContext, did: DefId) -> String {
448     cx.tcx.rendered_const(did)
449 }
450
451 fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
452     clean::Constant {
453         type_: cx.tcx.type_of(did).clean(cx),
454         expr: print_inlined_const(cx, did)
455     }
456 }
457
458 fn build_static(cx: &DocContext, did: DefId, mutable: bool) -> clean::Static {
459     clean::Static {
460         type_: cx.tcx.type_of(did).clean(cx),
461         mutability: if mutable {clean::Mutable} else {clean::Immutable},
462         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
463     }
464 }
465
466 fn build_macro(cx: &DocContext, did: DefId) -> clean::Macro {
467     let imported_from = cx.tcx.original_crate_name(did.krate);
468     let def = match cx.cstore.load_macro_untracked(did, cx.sess()) {
469         LoadedMacro::MacroDef(macro_def) => macro_def,
470         // FIXME(jseyfried): document proc macro re-exports
471         LoadedMacro::ProcMacro(..) => panic!("attempting to document proc-macro re-export"),
472     };
473
474     let matchers: hir::HirVec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.node {
475         let tts: Vec<_> = def.stream().into_trees().collect();
476         tts.chunks(4).map(|arm| arm[0].span()).collect()
477     } else {
478         unreachable!()
479     };
480
481     let source = format!("macro_rules! {} {{\n{}}}",
482                          def.ident.name.clean(cx),
483                          matchers.iter().map(|span| {
484                              format!("    {} => {{ ... }};\n", span.to_src(cx))
485                          }).collect::<String>());
486
487     clean::Macro {
488         source,
489         imported_from: Some(imported_from).clean(cx),
490     }
491 }
492
493 /// A trait's generics clause actually contains all of the predicates for all of
494 /// its associated types as well. We specifically move these clauses to the
495 /// associated types instead when displaying, so when we're generating the
496 /// generics for the trait itself we need to be sure to remove them.
497 /// We also need to remove the implied "recursive" Self: Trait bound.
498 ///
499 /// The inverse of this filtering logic can be found in the `Clean`
500 /// implementation for `AssociatedType`
501 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
502     for pred in &mut g.where_predicates {
503         match *pred {
504             clean::WherePredicate::BoundPredicate {
505                 ty: clean::Generic(ref s),
506                 ref mut bounds
507             } if *s == "Self" => {
508                 bounds.retain(|bound| {
509                     match *bound {
510                         clean::TyParamBound::TraitBound(clean::PolyTrait {
511                             trait_: clean::ResolvedPath { did, .. },
512                             ..
513                         }, _) => did != trait_did,
514                         _ => true
515                     }
516                 });
517             }
518             _ => {}
519         }
520     }
521
522     g.where_predicates.retain(|pred| {
523         match *pred {
524             clean::WherePredicate::BoundPredicate {
525                 ty: clean::QPath {
526                     self_type: box clean::Generic(ref s),
527                     trait_: box clean::ResolvedPath { did, .. },
528                     name: ref _name,
529                 }, ref bounds
530             } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
531             _ => true,
532         }
533     });
534     g
535 }
536
537 /// Supertrait bounds for a trait are also listed in the generics coming from
538 /// the metadata for a crate, so we want to separate those out and create a new
539 /// list of explicit supertrait bounds to render nicely.
540 fn separate_supertrait_bounds(mut g: clean::Generics)
541                               -> (clean::Generics, Vec<clean::TyParamBound>) {
542     let mut ty_bounds = Vec::new();
543     g.where_predicates.retain(|pred| {
544         match *pred {
545             clean::WherePredicate::BoundPredicate {
546                 ty: clean::Generic(ref s),
547                 ref bounds
548             } if *s == "Self" => {
549                 ty_bounds.extend(bounds.iter().cloned());
550                 false
551             }
552             _ => true,
553         }
554     });
555     (g, ty_bounds)
556 }
557
558 pub fn record_extern_trait(cx: &DocContext, did: DefId) {
559     if cx.external_traits.borrow().contains_key(&did) ||
560         cx.active_extern_traits.borrow().contains(&did)
561     {
562         return;
563     }
564
565     cx.active_extern_traits.borrow_mut().push(did);
566
567     let trait_ = build_external_trait(cx, did);
568
569     cx.external_traits.borrow_mut().insert(did, trait_);
570     cx.active_extern_traits.borrow_mut().remove_item(&did);
571 }