]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/clean/inline.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / src / librustdoc / clean / inline.rs
1 //! Support for inlining external documentation into the current AST.
2
3 use std::iter::once;
4 use std::sync::Arc;
5
6 use thin_vec::{thin_vec, ThinVec};
7
8 use rustc_ast as ast;
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId};
13 use rustc_hir::Mutability;
14 use rustc_metadata::creader::{CStore, LoadedMacro};
15 use rustc_middle::ty::{self, TyCtxt};
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::symbol::{kw, sym, Symbol};
18
19 use crate::clean::{
20 self, clean_fn_decl_from_did_and_sig, clean_generics, clean_impl_item, clean_middle_assoc_item,
21 clean_middle_field, clean_middle_ty, clean_trait_ref_with_bindings, clean_ty,
22 clean_ty_generics, clean_variant_def, utils, Attributes, AttributesExt, ImplKind, ItemId, Type,
23 };
24 use crate::core::DocContext;
25 use crate::formats::item_type::ItemType;
26
27 /// Attempt to inline a definition into this AST.
28 ///
29 /// This function will fetch the definition specified, and if it is
30 /// from another crate it will attempt to inline the documentation
31 /// from the other crate into this crate.
32 ///
33 /// This is primarily used for `pub use` statements which are, in general,
34 /// implementation details. Inlining the documentation should help provide a
35 /// better experience when reading the documentation in this use case.
36 ///
37 /// The returned value is `None` if the definition could not be inlined,
38 /// and `Some` of a vector of items if it was successfully expanded.
39 pub(crate) fn try_inline(
40 cx: &mut DocContext<'_>,
41 res: Res,
42 name: Symbol,
43 attrs: Option<(&[ast::Attribute], Option<DefId>)>,
44 visited: &mut DefIdSet,
45 ) -> Option<Vec<clean::Item>> {
46 let did = res.opt_def_id()?;
47 if did.is_local() {
48 return None;
49 }
50 let mut ret = Vec::new();
51
52 debug!("attrs={:?}", attrs);
53
54 let attrs_without_docs = attrs.map(|(attrs, def_id)| {
55 (attrs.into_iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id)
56 });
57 let attrs_without_docs =
58 attrs_without_docs.as_ref().map(|(attrs, def_id)| (&attrs[..], *def_id));
59
60 let import_def_id = attrs.and_then(|(_, def_id)| def_id);
61 let kind = match res {
62 Res::Def(DefKind::Trait, did) => {
63 record_extern_fqn(cx, did, ItemType::Trait);
64 build_impls(cx, did, attrs_without_docs, &mut ret);
65 clean::TraitItem(Box::new(build_external_trait(cx, did)))
66 }
67 Res::Def(DefKind::Fn, did) => {
68 record_extern_fqn(cx, did, ItemType::Function);
69 clean::FunctionItem(build_external_function(cx, did))
70 }
71 Res::Def(DefKind::Struct, did) => {
72 record_extern_fqn(cx, did, ItemType::Struct);
73 build_impls(cx, did, attrs_without_docs, &mut ret);
74 clean::StructItem(build_struct(cx, did))
75 }
76 Res::Def(DefKind::Union, did) => {
77 record_extern_fqn(cx, did, ItemType::Union);
78 build_impls(cx, did, attrs_without_docs, &mut ret);
79 clean::UnionItem(build_union(cx, did))
80 }
81 Res::Def(DefKind::TyAlias, did) => {
82 record_extern_fqn(cx, did, ItemType::Typedef);
83 build_impls(cx, did, attrs_without_docs, &mut ret);
84 clean::TypedefItem(build_type_alias(cx, did))
85 }
86 Res::Def(DefKind::Enum, did) => {
87 record_extern_fqn(cx, did, ItemType::Enum);
88 build_impls(cx, did, attrs_without_docs, &mut ret);
89 clean::EnumItem(build_enum(cx, did))
90 }
91 Res::Def(DefKind::ForeignTy, did) => {
92 record_extern_fqn(cx, did, ItemType::ForeignType);
93 build_impls(cx, did, attrs_without_docs, &mut ret);
94 clean::ForeignTypeItem
95 }
96 // Never inline enum variants but leave them shown as re-exports.
97 Res::Def(DefKind::Variant, _) => return None,
98 // Assume that enum variants and struct types are re-exported next to
99 // their constructors.
100 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
101 Res::Def(DefKind::Mod, did) => {
102 record_extern_fqn(cx, did, ItemType::Module);
103 clean::ModuleItem(build_module(cx, did, visited))
104 }
105 Res::Def(DefKind::Static(_), did) => {
106 record_extern_fqn(cx, did, ItemType::Static);
107 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
108 }
109 Res::Def(DefKind::Const, did) => {
110 record_extern_fqn(cx, did, ItemType::Constant);
111 clean::ConstantItem(build_const(cx, did))
112 }
113 Res::Def(DefKind::Macro(kind), did) => {
114 let mac = build_macro(cx, did, name, import_def_id, kind);
115
116 let type_kind = match kind {
117 MacroKind::Bang => ItemType::Macro,
118 MacroKind::Attr => ItemType::ProcAttribute,
119 MacroKind::Derive => ItemType::ProcDerive,
120 };
121 record_extern_fqn(cx, did, type_kind);
122 mac
123 }
124 _ => return None,
125 };
126
127 let (attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs);
128 cx.inlined.insert(did.into());
129 let mut item =
130 clean::Item::from_def_id_and_attrs_and_parts(did, Some(name), kind, Box::new(attrs), cfg);
131 // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
132 item.inline_stmt_id = import_def_id;
133 ret.push(item);
134 Some(ret)
135 }
136
137 pub(crate) fn try_inline_glob(
138 cx: &mut DocContext<'_>,
139 res: Res,
140 current_mod: LocalDefId,
141 visited: &mut DefIdSet,
142 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
143 ) -> Option<Vec<clean::Item>> {
144 let did = res.opt_def_id()?;
145 if did.is_local() {
146 return None;
147 }
148
149 match res {
150 Res::Def(DefKind::Mod, did) => {
151 // Use the set of module reexports to filter away names that are not actually
152 // reexported by the glob, e.g. because they are shadowed by something else.
153 let reexports = cx
154 .tcx
155 .module_children_reexports(current_mod)
156 .iter()
157 .filter_map(|child| child.res.opt_def_id())
158 .collect();
159 let mut items = build_module_items(cx, did, visited, inlined_names, Some(&reexports));
160 items.drain_filter(|item| {
161 if let Some(name) = item.name {
162 // If an item with the same type and name already exists,
163 // it takes priority over the inlined stuff.
164 !inlined_names.insert((item.type_(), name))
165 } else {
166 false
167 }
168 });
169 Some(items)
170 }
171 // glob imports on things like enums aren't inlined even for local exports, so just bail
172 _ => None,
173 }
174 }
175
176 pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> &'hir [ast::Attribute] {
177 cx.tcx.get_attrs_unchecked(did)
178 }
179
180 /// Record an external fully qualified name in the external_paths cache.
181 ///
182 /// These names are used later on by HTML rendering to generate things like
183 /// source links back to the original item.
184 pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
185 let crate_name = cx.tcx.crate_name(did.krate);
186
187 let relative =
188 cx.tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
189 let fqn = if let ItemType::Macro = kind {
190 // Check to see if it is a macro 2.0 or built-in macro
191 if matches!(
192 CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
193 LoadedMacro::MacroDef(def, _)
194 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
195 if !ast_def.macro_rules)
196 ) {
197 once(crate_name).chain(relative).collect()
198 } else {
199 vec![crate_name, relative.last().expect("relative was empty")]
200 }
201 } else {
202 once(crate_name).chain(relative).collect()
203 };
204
205 if did.is_local() {
206 cx.cache.exact_paths.insert(did, fqn);
207 } else {
208 cx.cache.external_paths.insert(did, (fqn, kind));
209 }
210 }
211
212 pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
213 let trait_items = cx
214 .tcx
215 .associated_items(did)
216 .in_definition_order()
217 .map(|item| clean_middle_assoc_item(item, cx))
218 .collect();
219
220 let predicates = cx.tcx.predicates_of(did);
221 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
222 let generics = filter_non_trait_generics(did, generics);
223 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
224 clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds }
225 }
226
227 fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box<clean::Function> {
228 let sig = cx.tcx.fn_sig(did).subst_identity();
229
230 let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var {
231 ty::BoundVariableKind::Region(ty::BrNamed(_, name)) if name != kw::UnderscoreLifetime => {
232 Some(clean::GenericParamDef::lifetime(name))
233 }
234 _ => None,
235 });
236
237 let predicates = cx.tcx.explicit_predicates_of(did);
238 let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
239 // NOTE: generics need to be cleaned before the decl!
240 let mut generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
241 // FIXME: This does not place parameters in source order (late-bound ones come last)
242 generics.params.extend(late_bound_regions);
243 let decl = clean_fn_decl_from_did_and_sig(cx, Some(did), sig);
244 (generics, decl)
245 });
246 Box::new(clean::Function { decl, generics })
247 }
248
249 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
250 let predicates = cx.tcx.explicit_predicates_of(did);
251
252 clean::Enum {
253 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
254 variants: cx.tcx.adt_def(did).variants().iter().map(|v| clean_variant_def(v, cx)).collect(),
255 }
256 }
257
258 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
259 let predicates = cx.tcx.explicit_predicates_of(did);
260 let variant = cx.tcx.adt_def(did).non_enum_variant();
261
262 clean::Struct {
263 ctor_kind: variant.ctor_kind(),
264 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
265 fields: variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect(),
266 }
267 }
268
269 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
270 let predicates = cx.tcx.explicit_predicates_of(did);
271 let variant = cx.tcx.adt_def(did).non_enum_variant();
272
273 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
274 let fields = variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect();
275 clean::Union { generics, fields }
276 }
277
278 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> Box<clean::Typedef> {
279 let predicates = cx.tcx.explicit_predicates_of(did);
280 let type_ =
281 clean_middle_ty(ty::Binder::dummy(cx.tcx.type_of(did).subst_identity()), cx, Some(did));
282
283 Box::new(clean::Typedef {
284 type_,
285 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
286 item_type: None,
287 })
288 }
289
290 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
291 pub(crate) fn build_impls(
292 cx: &mut DocContext<'_>,
293 did: DefId,
294 attrs: Option<(&[ast::Attribute], Option<DefId>)>,
295 ret: &mut Vec<clean::Item>,
296 ) {
297 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_inherent_impls");
298 let tcx = cx.tcx;
299
300 // for each implementation of an item represented by `did`, build the clean::Item for that impl
301 for &did in tcx.inherent_impls(did).iter() {
302 build_impl(cx, did, attrs, ret);
303 }
304
305 // This pretty much exists expressly for `dyn Error` traits that exist in the `alloc` crate.
306 // See also:
307 //
308 // * https://github.com/rust-lang/rust/issues/103170 — where it didn't used to get documented
309 // * https://github.com/rust-lang/rust/pull/99917 — where the feature got used
310 // * https://github.com/rust-lang/rust/issues/53487 — overall tracking issue for Error
311 if tcx.has_attr(did, sym::rustc_has_incoherent_inherent_impls) {
312 use rustc_middle::ty::fast_reject::SimplifiedType::*;
313 let type_ =
314 if tcx.is_trait(did) { TraitSimplifiedType(did) } else { AdtSimplifiedType(did) };
315 for &did in tcx.incoherent_impls(type_) {
316 build_impl(cx, did, attrs, ret);
317 }
318 }
319 }
320
321 pub(crate) fn merge_attrs(
322 cx: &mut DocContext<'_>,
323 old_attrs: &[ast::Attribute],
324 new_attrs: Option<(&[ast::Attribute], Option<DefId>)>,
325 ) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
326 // NOTE: If we have additional attributes (from a re-export),
327 // always insert them first. This ensure that re-export
328 // doc comments show up before the original doc comments
329 // when we render them.
330 if let Some((inner, item_id)) = new_attrs {
331 let mut both = inner.to_vec();
332 both.extend_from_slice(old_attrs);
333 (
334 if let Some(item_id) = item_id {
335 Attributes::from_ast_with_additional(old_attrs, (inner, item_id))
336 } else {
337 Attributes::from_ast(&both)
338 },
339 both.cfg(cx.tcx, &cx.cache.hidden_cfg),
340 )
341 } else {
342 (Attributes::from_ast(&old_attrs), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg))
343 }
344 }
345
346 /// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
347 pub(crate) fn build_impl(
348 cx: &mut DocContext<'_>,
349 did: DefId,
350 attrs: Option<(&[ast::Attribute], Option<DefId>)>,
351 ret: &mut Vec<clean::Item>,
352 ) {
353 if !cx.inlined.insert(did.into()) {
354 return;
355 }
356
357 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_impl");
358
359 let tcx = cx.tcx;
360 let associated_trait = tcx.impl_trait_ref(did).map(ty::EarlyBinder::skip_binder);
361
362 // Only inline impl if the implemented trait is
363 // reachable in rustdoc generated documentation
364 if !did.is_local() && let Some(traitref) = associated_trait {
365 let did = traitref.def_id;
366 if !cx.cache.effective_visibilities.is_directly_public(tcx, did) {
367 return;
368 }
369
370 if let Some(stab) = tcx.lookup_stability(did) &&
371 stab.is_unstable() &&
372 stab.feature == sym::rustc_private
373 {
374 return;
375 }
376 }
377
378 let impl_item = match did.as_local() {
379 Some(did) => match &tcx.hir().expect_item(did).kind {
380 hir::ItemKind::Impl(impl_) => Some(impl_),
381 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
382 },
383 None => None,
384 };
385
386 let for_ = match &impl_item {
387 Some(impl_) => clean_ty(impl_.self_ty, cx),
388 None => {
389 clean_middle_ty(ty::Binder::dummy(tcx.type_of(did).subst_identity()), cx, Some(did))
390 }
391 };
392
393 // Only inline impl if the implementing type is
394 // reachable in rustdoc generated documentation
395 if !did.is_local() {
396 if let Some(did) = for_.def_id(&cx.cache) {
397 if !cx.cache.effective_visibilities.is_directly_public(tcx, did) {
398 return;
399 }
400
401 if let Some(stab) = tcx.lookup_stability(did) {
402 if stab.is_unstable() && stab.feature == sym::rustc_private {
403 return;
404 }
405 }
406 }
407 }
408
409 let document_hidden = cx.render_options.document_hidden;
410 let predicates = tcx.explicit_predicates_of(did);
411 let (trait_items, generics) = match impl_item {
412 Some(impl_) => (
413 impl_
414 .items
415 .iter()
416 .map(|item| tcx.hir().impl_item(item.id))
417 .filter(|item| {
418 // Filter out impl items whose corresponding trait item has `doc(hidden)`
419 // not to document such impl items.
420 // For inherent impls, we don't do any filtering, because that's already done in strip_hidden.rs.
421
422 // When `--document-hidden-items` is passed, we don't
423 // do any filtering, too.
424 if document_hidden {
425 return true;
426 }
427 if let Some(associated_trait) = associated_trait {
428 let assoc_kind = match item.kind {
429 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
430 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
431 hir::ImplItemKind::Type(..) => ty::AssocKind::Type,
432 };
433 let trait_item = tcx
434 .associated_items(associated_trait.def_id)
435 .find_by_name_and_kind(
436 tcx,
437 item.ident,
438 assoc_kind,
439 associated_trait.def_id,
440 )
441 .unwrap(); // SAFETY: For all impl items there exists trait item that has the same name.
442 !tcx.is_doc_hidden(trait_item.def_id)
443 } else {
444 true
445 }
446 })
447 .map(|item| clean_impl_item(item, cx))
448 .collect::<Vec<_>>(),
449 clean_generics(impl_.generics, cx),
450 ),
451 None => (
452 tcx.associated_items(did)
453 .in_definition_order()
454 .filter(|item| {
455 // If this is a trait impl, filter out associated items whose corresponding item
456 // in the associated trait is marked `doc(hidden)`.
457 // If this is an inherent impl, filter out private associated items.
458 if let Some(associated_trait) = associated_trait {
459 let trait_item = tcx
460 .associated_items(associated_trait.def_id)
461 .find_by_name_and_kind(
462 tcx,
463 item.ident(tcx),
464 item.kind,
465 associated_trait.def_id,
466 )
467 .unwrap(); // corresponding associated item has to exist
468 !tcx.is_doc_hidden(trait_item.def_id)
469 } else {
470 item.visibility(tcx).is_public()
471 }
472 })
473 .map(|item| clean_middle_assoc_item(item, cx))
474 .collect::<Vec<_>>(),
475 clean::enter_impl_trait(cx, |cx| {
476 clean_ty_generics(cx, tcx.generics_of(did), predicates)
477 }),
478 ),
479 };
480 let polarity = tcx.impl_polarity(did);
481 let trait_ = associated_trait
482 .map(|t| clean_trait_ref_with_bindings(cx, ty::Binder::dummy(t), ThinVec::new()));
483 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
484 super::build_deref_target_impls(cx, &trait_items, ret);
485 }
486
487 // Return if the trait itself or any types of the generic parameters are doc(hidden).
488 let mut stack: Vec<&Type> = vec![&for_];
489
490 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
491 if tcx.is_doc_hidden(did) {
492 return;
493 }
494 }
495 if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
496 stack.extend(generics);
497 }
498
499 while let Some(ty) = stack.pop() {
500 if let Some(did) = ty.def_id(&cx.cache) && tcx.is_doc_hidden(did) {
501 return;
502 }
503 if let Some(generics) = ty.generics() {
504 stack.extend(generics);
505 }
506 }
507
508 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
509 record_extern_trait(cx, did);
510 }
511
512 let (merged_attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs);
513 trace!("merged_attrs={:?}", merged_attrs);
514
515 trace!(
516 "build_impl: impl {:?} for {:?}",
517 trait_.as_ref().map(|t| t.def_id()),
518 for_.def_id(&cx.cache)
519 );
520 ret.push(clean::Item::from_def_id_and_attrs_and_parts(
521 did,
522 None,
523 clean::ImplItem(Box::new(clean::Impl {
524 unsafety: hir::Unsafety::Normal,
525 generics,
526 trait_,
527 for_,
528 items: trait_items,
529 polarity,
530 kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) {
531 ImplKind::FakeVaradic
532 } else {
533 ImplKind::Normal
534 },
535 })),
536 Box::new(merged_attrs),
537 cfg,
538 ));
539 }
540
541 fn build_module(cx: &mut DocContext<'_>, did: DefId, visited: &mut DefIdSet) -> clean::Module {
542 let items = build_module_items(cx, did, visited, &mut FxHashSet::default(), None);
543
544 let span = clean::Span::new(cx.tcx.def_span(did));
545 clean::Module { items, span }
546 }
547
548 fn build_module_items(
549 cx: &mut DocContext<'_>,
550 did: DefId,
551 visited: &mut DefIdSet,
552 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
553 allowed_def_ids: Option<&DefIdSet>,
554 ) -> Vec<clean::Item> {
555 let mut items = Vec::new();
556
557 // If we're re-exporting a re-export it may actually re-export something in
558 // two namespaces, so the target may be listed twice. Make sure we only
559 // visit each node at most once.
560 for item in cx.tcx.module_children(did).iter() {
561 if item.vis.is_public() {
562 let res = item.res.expect_non_local();
563 if let Some(def_id) = res.opt_def_id()
564 && let Some(allowed_def_ids) = allowed_def_ids
565 && !allowed_def_ids.contains(&def_id) {
566 continue;
567 }
568 if let Some(def_id) = res.mod_def_id() {
569 // If we're inlining a glob import, it's possible to have
570 // two distinct modules with the same name. We don't want to
571 // inline it, or mark any of its contents as visited.
572 if did == def_id
573 || inlined_names.contains(&(ItemType::Module, item.ident.name))
574 || !visited.insert(def_id)
575 {
576 continue;
577 }
578 }
579 if let Res::PrimTy(p) = res {
580 // Primitive types can't be inlined so generate an import instead.
581 let prim_ty = clean::PrimitiveType::from(p);
582 items.push(clean::Item {
583 name: None,
584 attrs: Box::new(clean::Attributes::default()),
585 // We can use the item's `DefId` directly since the only information ever used
586 // from it is `DefId.krate`.
587 item_id: ItemId::DefId(did),
588 kind: Box::new(clean::ImportItem(clean::Import::new_simple(
589 item.ident.name,
590 clean::ImportSource {
591 path: clean::Path {
592 res,
593 segments: thin_vec![clean::PathSegment {
594 name: prim_ty.as_sym(),
595 args: clean::GenericArgs::AngleBracketed {
596 args: Default::default(),
597 bindings: ThinVec::new(),
598 },
599 }],
600 },
601 did: None,
602 },
603 true,
604 ))),
605 cfg: None,
606 inline_stmt_id: None,
607 });
608 } else if let Some(i) = try_inline(cx, res, item.ident.name, None, visited) {
609 items.extend(i)
610 }
611 }
612 }
613
614 items
615 }
616
617 pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
618 if let Some(did) = did.as_local() {
619 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
620 rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
621 } else {
622 tcx.rendered_const(did).clone()
623 }
624 }
625
626 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
627 clean::Constant {
628 type_: clean_middle_ty(
629 ty::Binder::dummy(cx.tcx.type_of(def_id).subst_identity()),
630 cx,
631 Some(def_id),
632 ),
633 kind: clean::ConstantKind::Extern { def_id },
634 }
635 }
636
637 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
638 clean::Static {
639 type_: clean_middle_ty(
640 ty::Binder::dummy(cx.tcx.type_of(did).subst_identity()),
641 cx,
642 Some(did),
643 ),
644 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
645 expr: None,
646 }
647 }
648
649 fn build_macro(
650 cx: &mut DocContext<'_>,
651 def_id: DefId,
652 name: Symbol,
653 import_def_id: Option<DefId>,
654 macro_kind: MacroKind,
655 ) -> clean::ItemKind {
656 match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
657 LoadedMacro::MacroDef(item_def, _) => match macro_kind {
658 MacroKind::Bang => {
659 if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
660 let vis = cx.tcx.visibility(import_def_id.unwrap_or(def_id));
661 clean::MacroItem(clean::Macro {
662 source: utils::display_macro_source(cx, name, def, def_id, vis),
663 })
664 } else {
665 unreachable!()
666 }
667 }
668 MacroKind::Derive | MacroKind::Attr => {
669 clean::ProcMacroItem(clean::ProcMacro { kind: macro_kind, helpers: Vec::new() })
670 }
671 },
672 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
673 kind: ext.macro_kind(),
674 helpers: ext.helper_attrs,
675 }),
676 }
677 }
678
679 /// A trait's generics clause actually contains all of the predicates for all of
680 /// its associated types as well. We specifically move these clauses to the
681 /// associated types instead when displaying, so when we're generating the
682 /// generics for the trait itself we need to be sure to remove them.
683 /// We also need to remove the implied "recursive" Self: Trait bound.
684 ///
685 /// The inverse of this filtering logic can be found in the `Clean`
686 /// implementation for `AssociatedType`
687 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
688 for pred in &mut g.where_predicates {
689 match *pred {
690 clean::WherePredicate::BoundPredicate {
691 ty: clean::Generic(ref s),
692 ref mut bounds,
693 ..
694 } if *s == kw::SelfUpper => {
695 bounds.retain(|bound| match bound {
696 clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => {
697 trait_.def_id() != trait_did
698 }
699 _ => true,
700 });
701 }
702 _ => {}
703 }
704 }
705
706 g.where_predicates.retain(|pred| match pred {
707 clean::WherePredicate::BoundPredicate {
708 ty: clean::QPath(box clean::QPathData { self_type: clean::Generic(ref s), trait_, .. }),
709 bounds,
710 ..
711 } => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
712 _ => true,
713 });
714 g
715 }
716
717 /// Supertrait bounds for a trait are also listed in the generics coming from
718 /// the metadata for a crate, so we want to separate those out and create a new
719 /// list of explicit supertrait bounds to render nicely.
720 fn separate_supertrait_bounds(
721 mut g: clean::Generics,
722 ) -> (clean::Generics, Vec<clean::GenericBound>) {
723 let mut ty_bounds = Vec::new();
724 g.where_predicates.retain(|pred| match *pred {
725 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
726 if *s == kw::SelfUpper =>
727 {
728 ty_bounds.extend(bounds.iter().cloned());
729 false
730 }
731 _ => true,
732 });
733 (g, ty_bounds)
734 }
735
736 pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
737 if did.is_local() {
738 return;
739 }
740
741 {
742 if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
743 {
744 return;
745 }
746 }
747
748 {
749 cx.active_extern_traits.insert(did);
750 }
751
752 debug!("record_extern_trait: {:?}", did);
753 let trait_ = build_external_trait(cx, did);
754
755 cx.external_traits.borrow_mut().insert(did, trait_);
756 cx.active_extern_traits.remove(&did);
757 }