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