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