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