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