]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Improve some compiletest documentation
[rust.git] / src / librustdoc / clean / inline.rs
1 //! Support for inlining external documentation into the current AST.
2
3 use std::iter::once;
4
5 use syntax::ast;
6 use syntax::ext::base::{MacroKind, SyntaxExtension};
7 use syntax_pos::Span;
8
9 use rustc::hir;
10 use rustc::hir::def::{Def, CtorKind};
11 use rustc::hir::def_id::DefId;
12 use rustc_metadata::cstore::LoadedMacro;
13 use rustc::ty;
14 use rustc::util::nodemap::FxHashSet;
15
16 use crate::core::{DocContext, DocAccessLevels};
17 use crate::doctree;
18 use crate::clean::{
19     self,
20     GetDefId,
21     ToSource,
22 };
23
24 use super::Clean;
25
26 /// Attempt to inline a definition into this AST.
27 ///
28 /// This function will fetch the definition specified, and if it is
29 /// from another crate it will attempt to inline the documentation
30 /// from the other crate into this crate.
31 ///
32 /// This is primarily used for `pub use` statements which are, in general,
33 /// implementation details. Inlining the documentation should help provide a
34 /// better experience when reading the documentation in this use case.
35 ///
36 /// The returned value is `None` if the definition could not be inlined,
37 /// and `Some` of a vector of items if it was successfully expanded.
38 pub fn try_inline(
39     cx: &DocContext<'_>,
40     def: Def,
41     name: ast::Name,
42     visited: &mut FxHashSet<DefId>
43 )
44                   -> Option<Vec<clean::Item>> {
45     let did = if let Some(did) = def.opt_def_id() {
46         did
47     } else {
48         return None;
49     };
50     if did.is_local() { return None }
51     let mut ret = Vec::new();
52     let inner = match def {
53         Def::Trait(did) => {
54             record_extern_fqn(cx, did, clean::TypeKind::Trait);
55             ret.extend(build_impls(cx, did));
56             clean::TraitItem(build_external_trait(cx, did))
57         }
58         Def::Fn(did) => {
59             record_extern_fqn(cx, did, clean::TypeKind::Function);
60             clean::FunctionItem(build_external_function(cx, did))
61         }
62         Def::Struct(did) => {
63             record_extern_fqn(cx, did, clean::TypeKind::Struct);
64             ret.extend(build_impls(cx, did));
65             clean::StructItem(build_struct(cx, did))
66         }
67         Def::Union(did) => {
68             record_extern_fqn(cx, did, clean::TypeKind::Union);
69             ret.extend(build_impls(cx, did));
70             clean::UnionItem(build_union(cx, did))
71         }
72         Def::TyAlias(did) => {
73             record_extern_fqn(cx, did, clean::TypeKind::Typedef);
74             ret.extend(build_impls(cx, did));
75             clean::TypedefItem(build_type_alias(cx, did), false)
76         }
77         Def::Enum(did) => {
78             record_extern_fqn(cx, did, clean::TypeKind::Enum);
79             ret.extend(build_impls(cx, did));
80             clean::EnumItem(build_enum(cx, did))
81         }
82         Def::ForeignTy(did) => {
83             record_extern_fqn(cx, did, clean::TypeKind::Foreign);
84             ret.extend(build_impls(cx, did));
85             clean::ForeignTypeItem
86         }
87         // Never inline enum variants but leave them shown as re-exports.
88         Def::Variant(..) => return None,
89         // Assume that enum variants and struct types are re-exported next to
90         // their constructors.
91         Def::VariantCtor(..) |
92         Def::StructCtor(..) |
93         Def::SelfCtor(..) => return Some(Vec::new()),
94         Def::Mod(did) => {
95             record_extern_fqn(cx, did, clean::TypeKind::Module);
96             clean::ModuleItem(build_module(cx, did, visited))
97         }
98         Def::Static(did, mtbl) => {
99             record_extern_fqn(cx, did, clean::TypeKind::Static);
100             clean::StaticItem(build_static(cx, did, mtbl))
101         }
102         Def::Const(did) => {
103             record_extern_fqn(cx, did, clean::TypeKind::Const);
104             clean::ConstantItem(build_const(cx, did))
105         }
106         // FIXME: proc-macros don't propagate attributes or spans across crates, so they look empty
107         Def::Macro(did, MacroKind::Bang) => {
108             let mac = build_macro(cx, did, name);
109             if let clean::MacroItem(..) = mac {
110                 record_extern_fqn(cx, did, clean::TypeKind::Macro);
111                 mac
112             } else {
113                 return None;
114             }
115         }
116         _ => return None,
117     };
118     cx.renderinfo.borrow_mut().inlined.insert(did);
119     ret.push(clean::Item {
120         source: cx.tcx.def_span(did).clean(cx),
121         name: Some(name.clean(cx)),
122         attrs: load_attrs(cx, did),
123         inner,
124         visibility: Some(clean::Public),
125         stability: cx.tcx.lookup_stability(did).clean(cx),
126         deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
127         def_id: did,
128     });
129     Some(ret)
130 }
131
132 pub fn try_inline_glob(cx: &DocContext<'_>, def: Def, visited: &mut FxHashSet<DefId>)
133     -> Option<Vec<clean::Item>>
134 {
135     if def == Def::Err { return None }
136     let did = def.def_id();
137     if did.is_local() { return None }
138
139     match def {
140         Def::Mod(did) => {
141             let m = build_module(cx, did, visited);
142             Some(m.items)
143         }
144         // glob imports on things like enums aren't inlined even for local exports, so just bail
145         _ => None,
146     }
147 }
148
149 pub fn load_attrs(cx: &DocContext<'_>, did: DefId) -> clean::Attributes {
150     cx.tcx.get_attrs(did).clean(cx)
151 }
152
153 /// Record an external fully qualified name in the external_paths cache.
154 ///
155 /// These names are used later on by HTML rendering to generate things like
156 /// source links back to the original item.
157 pub fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
158     let mut crate_name = cx.tcx.crate_name(did.krate).to_string();
159     if did.is_local() {
160         crate_name = cx.crate_name.clone().unwrap_or(crate_name);
161     }
162
163     let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
164         // extern blocks have an empty name
165         let s = elem.data.to_string();
166         if !s.is_empty() {
167             Some(s)
168         } else {
169             None
170         }
171     });
172     let fqn = if let clean::TypeKind::Macro = kind {
173         vec![crate_name, relative.last().expect("relative was empty")]
174     } else {
175         once(crate_name).chain(relative).collect()
176     };
177
178     if did.is_local() {
179         cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
180     } else {
181         cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
182     }
183 }
184
185 pub fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
186     let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
187     let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
188     let predicates = cx.tcx.predicates_of(did);
189     let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
190     let generics = filter_non_trait_generics(did, generics);
191     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
192     let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
193     let is_auto = cx.tcx.trait_is_auto(did);
194     clean::Trait {
195         auto: auto_trait,
196         unsafety: cx.tcx.trait_def(did).unsafety,
197         generics,
198         items: trait_items,
199         bounds: supertrait_bounds,
200         is_spotlight,
201         is_auto,
202     }
203 }
204
205 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
206     let sig = cx.tcx.fn_sig(did);
207
208     let constness = if cx.tcx.is_min_const_fn(did) {
209         hir::Constness::Const
210     } else {
211         hir::Constness::NotConst
212     };
213
214     let predicates = cx.tcx.predicates_of(did);
215     clean::Function {
216         decl: (did, sig).clean(cx),
217         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
218         header: hir::FnHeader {
219             unsafety: sig.unsafety(),
220             abi: sig.abi(),
221             constness,
222             asyncness: hir::IsAsync::NotAsync,
223         }
224     }
225 }
226
227 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
228     let predicates = cx.tcx.predicates_of(did);
229
230     clean::Enum {
231         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
232         variants_stripped: false,
233         variants: cx.tcx.adt_def(did).variants.clean(cx),
234     }
235 }
236
237 fn build_struct(cx: &DocContext<'_>, did: DefId) -> clean::Struct {
238     let predicates = cx.tcx.predicates_of(did);
239     let variant = cx.tcx.adt_def(did).non_enum_variant();
240
241     clean::Struct {
242         struct_type: match variant.ctor_kind {
243             CtorKind::Fictive => doctree::Plain,
244             CtorKind::Fn => doctree::Tuple,
245             CtorKind::Const => doctree::Unit,
246         },
247         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
248         fields: variant.fields.clean(cx),
249         fields_stripped: false,
250     }
251 }
252
253 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
254     let predicates = cx.tcx.predicates_of(did);
255     let variant = cx.tcx.adt_def(did).non_enum_variant();
256
257     clean::Union {
258         struct_type: doctree::Plain,
259         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
260         fields: variant.fields.clean(cx),
261         fields_stripped: false,
262     }
263 }
264
265 fn build_type_alias(cx: &DocContext<'_>, did: DefId) -> clean::Typedef {
266     let predicates = cx.tcx.predicates_of(did);
267
268     clean::Typedef {
269         type_: cx.tcx.type_of(did).clean(cx),
270         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
271     }
272 }
273
274 pub fn build_impls(cx: &DocContext<'_>, did: DefId) -> Vec<clean::Item> {
275     let tcx = cx.tcx;
276     let mut impls = Vec::new();
277
278     for &did in tcx.inherent_impls(did).iter() {
279         build_impl(cx, did, &mut impls);
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 !did.is_local() {
297         if let Some(traitref) = associated_trait {
298             if !cx.renderinfo.borrow().access_levels.is_doc_reachable(traitref.def_id) {
299                 return
300             }
301         }
302     }
303
304     let for_ = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
305         match tcx.hir().expect_item_by_hir_id(hir_id).node {
306             hir::ItemKind::Impl(.., ref t, _) => {
307                 t.clean(cx)
308             }
309             _ => panic!("did given to build_impl was not an impl"),
310         }
311     } else {
312         tcx.type_of(did).clean(cx)
313     };
314
315     // Only inline impl if the implementing type is
316     // reachable in rustdoc generated documentation
317     if !did.is_local() {
318         if let Some(did) = for_.def_id() {
319             if !cx.renderinfo.borrow().access_levels.is_doc_reachable(did) {
320                 return
321             }
322         }
323     }
324
325     let predicates = tcx.predicates_of(did);
326     let (trait_items, generics) = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
327         match tcx.hir().expect_item_by_hir_id(hir_id).node {
328             hir::ItemKind::Impl(.., ref gen, _, _, ref item_ids) => {
329                 (
330                     item_ids.iter()
331                             .map(|ii| tcx.hir().impl_item(ii.id).clean(cx))
332                             .collect::<Vec<_>>(),
333                     gen.clean(cx),
334                 )
335             }
336             _ => panic!("did given to build_impl was not an impl"),
337         }
338     } else {
339         (
340             tcx.associated_items(did).filter_map(|item| {
341                 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
342                     Some(item.clean(cx))
343                 } else {
344                     None
345                 }
346             }).collect::<Vec<_>>(),
347             (tcx.generics_of(did), &predicates).clean(cx),
348         )
349     };
350     let polarity = tcx.impl_polarity(did);
351     let trait_ = associated_trait.clean(cx).map(|bound| {
352         match bound {
353             clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
354             clean::GenericBound::Outlives(..) => unreachable!(),
355         }
356     });
357     if trait_.def_id() == tcx.lang_items().deref_trait() {
358         super::build_deref_target_impls(cx, &trait_items, ret);
359     }
360     if let Some(trait_did) = trait_.def_id() {
361         record_extern_trait(cx, trait_did);
362     }
363
364     let provided = trait_.def_id().map(|did| {
365         tcx.provided_trait_methods(did)
366            .into_iter()
367            .map(|meth| meth.ident.to_string())
368            .collect()
369     }).unwrap_or_default();
370
371     debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
372
373     ret.push(clean::Item {
374         inner: clean::ImplItem(clean::Impl {
375             unsafety: hir::Unsafety::Normal,
376             generics,
377             provided_trait_methods: provided,
378             trait_,
379             for_,
380             items: trait_items,
381             polarity: Some(polarity.clean(cx)),
382             synthetic: false,
383             blanket_impl: None,
384         }),
385         source: tcx.def_span(did).clean(cx),
386         name: None,
387         attrs,
388         visibility: Some(clean::Inherited),
389         stability: tcx.lookup_stability(did).clean(cx),
390         deprecation: tcx.lookup_deprecation(did).clean(cx),
391         def_id: did,
392     });
393 }
394
395 fn build_module(
396     cx: &DocContext<'_>,
397     did: DefId,
398     visited: &mut FxHashSet<DefId>
399 ) -> clean::Module {
400     let mut items = Vec::new();
401     fill_in(cx, did, &mut items, visited);
402     return clean::Module {
403         items,
404         is_crate: false,
405     };
406
407     fn fill_in(cx: &DocContext<'_>, did: DefId, items: &mut Vec<clean::Item>,
408                visited: &mut FxHashSet<DefId>) {
409         // If we're re-exporting a re-export it may actually re-export something in
410         // two namespaces, so the target may be listed twice. Make sure we only
411         // visit each node at most once.
412         for &item in cx.tcx.item_children(did).iter() {
413             let def_id = item.def.def_id();
414             if item.vis == ty::Visibility::Public {
415                 if did == def_id || !visited.insert(def_id) { continue }
416                 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
417                     items.extend(i)
418                 }
419             }
420         }
421     }
422 }
423
424 pub fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
425     if let Some(node_id) = cx.tcx.hir().as_local_hir_id(did) {
426         cx.tcx.hir().hir_to_pretty_string(node_id)
427     } else {
428         cx.tcx.rendered_const(did)
429     }
430 }
431
432 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
433     clean::Constant {
434         type_: cx.tcx.type_of(did).clean(cx),
435         expr: print_inlined_const(cx, did)
436     }
437 }
438
439 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
440     clean::Static {
441         type_: cx.tcx.type_of(did).clean(cx),
442         mutability: if mutable {clean::Mutable} else {clean::Immutable},
443         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
444     }
445 }
446
447 fn build_macro(cx: &DocContext<'_>, did: DefId, name: ast::Name) -> clean::ItemEnum {
448     let imported_from = cx.tcx.original_crate_name(did.krate);
449     match cx.cstore.load_macro_untracked(did, cx.sess()) {
450         LoadedMacro::MacroDef(def) => {
451             let matchers: hir::HirVec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.node {
452                 let tts: Vec<_> = def.stream().into_trees().collect();
453                 tts.chunks(4).map(|arm| arm[0].span()).collect()
454             } else {
455                 unreachable!()
456             };
457
458             let source = format!("macro_rules! {} {{\n{}}}",
459                                  name.clean(cx),
460                                  matchers.iter().map(|span| {
461                                      format!("    {} => {{ ... }};\n", span.to_src(cx))
462                                  }).collect::<String>());
463
464             clean::MacroItem(clean::Macro {
465                 source,
466                 imported_from: Some(imported_from).clean(cx),
467             })
468         }
469         LoadedMacro::ProcMacro(ext) => {
470             let helpers = match &*ext {
471                 &SyntaxExtension::ProcMacroDerive(_, ref syms, ..) => { syms.clean(cx) }
472                 _ => Vec::new(),
473             };
474
475             clean::ProcMacroItem(clean::ProcMacro {
476                 kind: ext.kind(),
477                 helpers,
478             })
479         }
480     }
481
482 }
483
484 /// A trait's generics clause actually contains all of the predicates for all of
485 /// its associated types as well. We specifically move these clauses to the
486 /// associated types instead when displaying, so when we're generating the
487 /// generics for the trait itself we need to be sure to remove them.
488 /// We also need to remove the implied "recursive" Self: Trait bound.
489 ///
490 /// The inverse of this filtering logic can be found in the `Clean`
491 /// implementation for `AssociatedType`
492 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
493     for pred in &mut g.where_predicates {
494         match *pred {
495             clean::WherePredicate::BoundPredicate {
496                 ty: clean::Generic(ref s),
497                 ref mut bounds
498             } if *s == "Self" => {
499                 bounds.retain(|bound| {
500                     match *bound {
501                         clean::GenericBound::TraitBound(clean::PolyTrait {
502                             trait_: clean::ResolvedPath { did, .. },
503                             ..
504                         }, _) => did != trait_did,
505                         _ => true
506                     }
507                 });
508             }
509             _ => {}
510         }
511     }
512
513     g.where_predicates.retain(|pred| {
514         match *pred {
515             clean::WherePredicate::BoundPredicate {
516                 ty: clean::QPath {
517                     self_type: box clean::Generic(ref s),
518                     trait_: box clean::ResolvedPath { did, .. },
519                     name: ref _name,
520                 }, ref bounds
521             } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
522             _ => true,
523         }
524     });
525     g
526 }
527
528 /// Supertrait bounds for a trait are also listed in the generics coming from
529 /// the metadata for a crate, so we want to separate those out and create a new
530 /// list of explicit supertrait bounds to render nicely.
531 fn separate_supertrait_bounds(mut g: clean::Generics)
532                               -> (clean::Generics, Vec<clean::GenericBound>) {
533     let mut ty_bounds = Vec::new();
534     g.where_predicates.retain(|pred| {
535         match *pred {
536             clean::WherePredicate::BoundPredicate {
537                 ty: clean::Generic(ref s),
538                 ref bounds
539             } if *s == "Self" => {
540                 ty_bounds.extend(bounds.iter().cloned());
541                 false
542             }
543             _ => true,
544         }
545     });
546     (g, ty_bounds)
547 }
548
549 pub fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
550     if did.is_local() {
551         return;
552     }
553
554     {
555         let external_traits = cx.external_traits.lock();
556         if external_traits.borrow().contains_key(&did) ||
557             cx.active_extern_traits.borrow().contains(&did)
558         {
559             return;
560         }
561     }
562
563     cx.active_extern_traits.borrow_mut().push(did);
564
565     debug!("record_extern_trait: {:?}", did);
566     let trait_ = build_external_trait(cx, did);
567
568     {
569         let external_traits = cx.external_traits.lock();
570         external_traits.borrow_mut().insert(did, trait_);
571     }
572     cx.active_extern_traits.borrow_mut().remove_item(&did);
573 }