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