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