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