1use std::iter::once;
4use std::sync::Arc;
5
6use rustc_attr_ir::{AttributeKind, DocInline, find_attr};
7use rustc_data_structures::fx::FxHashSet;
8use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
9use rustc_hir::def::{DefKind, MacroKinds, Res};
10use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId, LocalModId};
11use rustc_hir::{self as hir, HirId, Mutability};
12use rustc_metadata::creader::{CStore, LoadedMacro};
13use rustc_middle::middle::resolve::ModChild;
14use rustc_middle::ty::fast_reject::SimplifiedType;
15use rustc_middle::ty::{self, TyCtxt};
16use rustc_span::def_id::LOCAL_CRATE;
17use rustc_span::hygiene::MacroKind;
18use rustc_span::symbol::{Symbol, sym};
19use tracing::{debug, instrument, trace};
20
21use super::{Item, extract_cfg_from_attrs};
22use crate::clean::{
23 self, Attributes, CfgInfo, ImplKind, ItemId, ItemKind, Type, clean_bound_vars, clean_generics,
24 clean_impl_item, clean_middle_assoc_item, clean_middle_field, clean_middle_ty,
25 clean_poly_fn_sig, clean_trait_ref_with_constraints, clean_ty, clean_ty_alias_inner_type,
26 clean_ty_generics, clean_variant_def, utils,
27};
28use crate::core::DocContext;
29use crate::formats::item_type::ItemType;
30
31pub(crate) fn try_inline(
44 cx: &mut DocContext<'_>,
45 res: Res,
46 name: Symbol,
47 attrs: Option<(&[rustc_attr_ir::Attribute], Option<LocalDefId>)>,
48 visited: &mut DefIdSet,
49) -> Option<Vec<clean::Item>> {
50 fn try_inline_inner(
51 cx: &mut DocContext<'_>,
52 kind: ItemKind,
53 did: DefId,
54 name: Symbol,
55 import_def_id: Option<LocalDefId>,
56 ) -> clean::Item {
57 cx.inlined.insert(did.into());
58 let mut item = crate::clean::generate_item_with_correct_attrs(
59 cx,
60 kind,
61 did,
62 name,
63 import_def_id.as_slice(),
64 None,
65 );
66 item.inner.inline_stmt_id = import_def_id;
68 item
69 }
70
71 let did = res.opt_def_id()?;
72 if did.is_local() {
73 return None;
74 }
75 let mut ret = Vec::new();
76
77 debug!("attrs={attrs:?}");
78
79 let attrs_without_docs = attrs.map(|(attrs, def_id)| {
80 (
81 attrs
82 .iter()
83 .filter(|a| {
84 !matches!(a, rustc_attr_ir::Attribute::Parsed(AttributeKind::DocComment { .. }))
85 })
86 .cloned()
87 .collect::<Vec<_>>(),
88 def_id,
89 )
90 });
91 let attrs_without_docs =
92 attrs_without_docs.as_ref().map(|(attrs, def_id)| (&attrs[..], *def_id));
93
94 let import_def_id = attrs.and_then(|(_, def_id)| def_id);
95
96 let kind = match res {
97 Res::Def(DefKind::Trait, did) => {
98 record_extern_fqn(cx, did, ItemType::Trait);
99 cx.with_param_env(did, |cx| {
100 build_impls(cx, did, attrs_without_docs, &mut ret);
101 ItemKind::Trait(Box::new(build_trait(cx, did)))
102 })
103 }
104 Res::Def(DefKind::TraitAlias, did) => {
105 record_extern_fqn(cx, did, ItemType::TraitAlias);
106 cx.with_param_env(did, |cx| ItemKind::TraitAlias(build_trait_alias(cx, did)))
107 }
108 Res::Def(DefKind::Fn, did) => {
109 record_extern_fqn(cx, did, ItemType::Function);
110 cx.with_param_env(did, |cx| {
111 clean::enter_impl_trait(cx, |cx| {
112 let (generics, decl) = build_function(cx, did);
113 ItemKind::Function(Box::new(clean::Function { generics, decl }))
114 })
115 })
116 }
117 Res::Def(DefKind::Struct, did) => {
118 record_extern_fqn(cx, did, ItemType::Struct);
119 cx.with_param_env(did, |cx| {
120 build_impls(cx, did, attrs_without_docs, &mut ret);
121 ItemKind::Struct(build_struct(cx, did))
122 })
123 }
124 Res::Def(DefKind::Union, did) => {
125 record_extern_fqn(cx, did, ItemType::Union);
126 cx.with_param_env(did, |cx| {
127 build_impls(cx, did, attrs_without_docs, &mut ret);
128 ItemKind::Union(build_union(cx, did))
129 })
130 }
131 Res::Def(DefKind::TyAlias, did) => {
132 record_extern_fqn(cx, did, ItemType::TypeAlias);
133 cx.with_param_env(did, |cx| {
134 build_impls(cx, did, attrs_without_docs, &mut ret);
135 ItemKind::TypeAlias(build_type_alias(cx, did, &mut ret))
136 })
137 }
138 Res::Def(DefKind::Enum, did) => {
139 record_extern_fqn(cx, did, ItemType::Enum);
140 cx.with_param_env(did, |cx| {
141 build_impls(cx, did, attrs_without_docs, &mut ret);
142 ItemKind::Enum(build_enum(cx, did))
143 })
144 }
145 Res::Def(DefKind::ForeignTy, did) => {
146 record_extern_fqn(cx, did, ItemType::ForeignType);
147 cx.with_param_env(did, |cx| {
148 build_impls(cx, did, attrs_without_docs, &mut ret);
149 ItemKind::ForeignType
150 })
151 }
152 Res::Def(DefKind::Variant, _) => return None,
154 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
157 Res::Def(DefKind::Mod, did) => {
158 record_extern_fqn(cx, did, ItemType::Module);
159 ItemKind::Module(build_module(cx, did, name, visited))
160 }
161 Res::Def(DefKind::Static { .. }, did) => {
162 record_extern_fqn(cx, did, ItemType::Static);
163 cx.with_param_env(did, |cx| {
164 ItemKind::Static(build_static(cx, did, cx.tcx.is_mutable_static(did)))
165 })
166 }
167 Res::Def(DefKind::Const, did) => {
168 record_extern_fqn(cx, did, ItemType::Constant);
169 cx.with_param_env(did, |cx| {
170 let ct = build_const_item(cx, did);
171 ItemKind::Constant(Box::new(ct))
172 })
173 }
174 Res::Def(DefKind::Macro(kinds), did) => {
175 let mac = build_macro(cx.tcx, did, name, kinds);
176
177 let type_kind = match kinds {
178 MacroKinds::BANG => ItemType::Macro,
179 MacroKinds::ATTR => ItemType::ProcAttribute,
180 MacroKinds::DERIVE => ItemType::ProcDerive,
181 _ => ItemType::Macro,
183 };
184 record_extern_fqn(cx, did, type_kind);
185 ret.push(try_inline_inner(cx, mac, did, name, import_def_id));
186 return Some(ret);
187 }
188 _ => return None,
189 };
190
191 ret.push(try_inline_inner(cx, kind, did, name, import_def_id));
192 Some(ret)
193}
194
195pub(crate) fn try_inline_glob(
196 cx: &mut DocContext<'_>,
197 res: Res,
198 current_mod: LocalModId,
199 visited: &mut DefIdSet,
200 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
201 import_id: LocalDefId,
202 import_hir_id: HirId,
203) -> Option<Vec<clean::Item>> {
204 let did = res.opt_def_id()?;
205 if did.is_local() {
206 return None;
207 }
208
209 match res {
210 Res::Def(DefKind::Mod, did) => {
211 let reexports = cx
214 .tcx
215 .module_children_local(current_mod.to_local_def_id())
216 .iter()
217 .filter(|child| !child.reexport_chain.is_empty())
218 .filter_map(|child| child.res.opt_def_id())
219 .filter(|&def_id| !cx.tcx.is_doc_hidden(def_id))
220 .collect();
221 let attrs = cx.tcx.hir_attrs(import_hir_id);
222 let mut items = build_module_items(
223 cx,
224 did,
225 cx.tcx.item_name(did),
226 visited,
227 inlined_names,
228 Some(&reexports),
229 Some((attrs, Some(import_id))),
230 );
231 items.retain(|item| {
232 if let Some(name) = item.name {
233 inlined_names.insert((item.type_(), name))
236 } else {
237 true
238 }
239 });
240 Some(items)
241 }
242 _ => None,
244 }
245}
246
247pub(crate) fn load_attrs<'hir>(tcx: TyCtxt<'hir>, did: DefId) -> &'hir [rustc_attr_ir::Attribute] {
248 #[allow(deprecated)]
250 tcx.get_all_attrs(did)
251}
252
253pub(crate) fn item_relative_path(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<Symbol> {
254 tcx.def_path(def_id).data.into_iter().filter_map(|elem| elem.data.get_opt_name()).collect()
255}
256
257pub(crate) fn get_item_path(tcx: TyCtxt<'_>, def_id: DefId, kind: ItemType) -> Vec<Symbol> {
262 let crate_name = tcx.crate_name(def_id.krate);
263 let relative = item_relative_path(tcx, def_id);
264
265 if let ItemType::Macro = kind {
266 let is_macro_2_0_or_builtin = if let Some(local_def_id) = def_id.as_local() {
269 let (_, macro_def, _) = tcx.hir_expect_item(local_def_id).expect_macro();
270 !macro_def.macro_rules
271 } else {
272 matches!(
273 CStore::from_tcx(tcx).load_macro_untracked(tcx, def_id),
274 LoadedMacro::MacroDef { def, .. } if !def.macro_rules
275 )
276 };
277 if !is_macro_2_0_or_builtin {
278 return vec![crate_name, *relative.last().expect("relative was empty")];
279 }
280 }
281
282 once(crate_name).chain(relative).collect()
283}
284
285pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
290 if did.is_local() {
291 if cx.cache.exact_paths.contains_key(&did) {
292 return;
293 }
294 } else if cx.cache.external_paths.contains_key(&did) {
295 return;
296 }
297
298 let item_path = get_item_path(cx.tcx, did, kind);
299
300 if did.is_local() {
301 cx.cache.exact_paths.insert(did, item_path);
302 } else {
303 cx.cache.external_paths.insert(did, (item_path, kind));
304 }
305}
306
307pub(crate) fn build_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
308 let trait_items = cx
309 .tcx
310 .associated_items(did)
311 .in_definition_order()
312 .filter(|item| !item.is_impl_trait_in_trait())
313 .map(|item| clean_middle_assoc_item(item, cx))
314 .collect();
315
316 let generics = clean_ty_generics(cx, did);
317 let (generics, mut supertrait_bounds) = separate_self_bounds(generics);
318
319 supertrait_bounds.retain(|b| {
320 !b.is_meta_sized_bound(cx.tcx)
323 });
324
325 clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds }
326}
327
328fn build_trait_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::TraitAlias {
329 let generics = clean_ty_generics(cx, did);
330 let (generics, mut bounds) = separate_self_bounds(generics);
331
332 bounds.retain(|b| {
333 !b.is_meta_sized_bound(cx.tcx)
336 });
337
338 clean::TraitAlias { generics, bounds }
339}
340
341pub(super) fn build_function(
342 cx: &mut DocContext<'_>,
343 def_id: DefId,
344) -> (clean::Generics, clean::FnDecl) {
345 let sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
346 let mut generics = clean_ty_generics(cx, def_id);
348 let bound_vars = clean_bound_vars(sig.bound_vars(), cx.tcx);
349
350 let has_early_bound_params = !generics.params.is_empty();
360 let has_late_bound_params = !bound_vars.is_empty();
361 generics.params.extend(bound_vars);
362 if has_early_bound_params && has_late_bound_params {
363 generics.params.sort_by_key(|param| cx.tcx.def_ident_span(param.def_id).unwrap().lo_hi());
368 }
369
370 let decl = clean_poly_fn_sig(cx, Some(def_id), sig);
371
372 (generics, decl)
373}
374
375fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
376 clean::Enum {
377 generics: clean_ty_generics(cx, did),
378 variants: cx.tcx.adt_def(did).variants().iter().map(|v| clean_variant_def(v, cx)).collect(),
379 }
380}
381
382fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
383 let variant = cx.tcx.adt_def(did).non_enum_variant();
384
385 clean::Struct {
386 ctor_kind: variant.ctor_kind(),
387 generics: clean_ty_generics(cx, did),
388 fields: variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect(),
389 }
390}
391
392fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
393 let variant = cx.tcx.adt_def(did).non_enum_variant();
394
395 let generics = clean_ty_generics(cx, did);
396 let fields = variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect();
397 clean::Union { generics, fields }
398}
399
400fn build_type_alias(
401 cx: &mut DocContext<'_>,
402 did: DefId,
403 ret: &mut Vec<Item>,
404) -> Box<clean::TypeAlias> {
405 let ty = cx.tcx.type_of(did).instantiate_identity().skip_norm_wip();
406 let type_ = clean_middle_ty(ty::Binder::dummy(ty), cx, Some(did), None);
407 let inner_type = clean_ty_alias_inner_type(ty, cx, ret);
408
409 Box::new(clean::TypeAlias { type_, generics: clean_ty_generics(cx, did), inner_type })
410}
411
412pub(crate) fn build_impls(
414 cx: &mut DocContext<'_>,
415 did: DefId,
416 attrs: Option<(&[rustc_attr_ir::Attribute], Option<LocalDefId>)>,
417 ret: &mut Vec<clean::Item>,
418) {
419 let tcx = cx.tcx;
420 let _prof_timer = tcx.sess.prof.generic_activity("build_inherent_impls");
421
422 for &did in tcx.inherent_impls(did).iter() {
424 cx.with_param_env(did, |cx| {
425 build_impl(cx, did, attrs, ret);
426 });
427 }
428
429 if find_attr!(tcx, did, RustcHasIncoherentInherentImpls) {
436 let type_ =
437 if tcx.is_trait(did) { SimplifiedType::Trait(did) } else { SimplifiedType::Adt(did) };
438 for &did in tcx.incoherent_impls(type_).iter() {
439 cx.with_param_env(did, |cx| {
440 build_impl(cx, did, attrs, ret);
441 });
442 }
443 }
444}
445
446pub(crate) fn merge_attrs(
447 tcx: TyCtxt<'_>,
448 old_attrs: &[rustc_attr_ir::Attribute],
449 new_attrs: Option<(&[rustc_attr_ir::Attribute], Option<LocalDefId>)>,
450 cfg_info: &mut CfgInfo,
451) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
452 if let Some((inner, item_id)) = new_attrs {
457 let mut both = inner.to_vec();
458 both.extend_from_slice(old_attrs);
459 (
460 if let Some(item_id) = item_id {
461 Attributes::from_hir_with_additional(old_attrs, (inner, item_id.to_def_id()))
462 } else {
463 Attributes::from_hir(&both)
464 },
465 extract_cfg_from_attrs(both.iter(), tcx, cfg_info),
466 )
467 } else {
468 (Attributes::from_hir(old_attrs), extract_cfg_from_attrs(old_attrs.iter(), tcx, cfg_info))
469 }
470}
471
472#[instrument(level = "debug", skip(cx, ret))]
474pub(crate) fn build_impl(
475 cx: &mut DocContext<'_>,
476 did: DefId,
477 attrs: Option<(&[rustc_attr_ir::Attribute], Option<LocalDefId>)>,
478 ret: &mut Vec<clean::Item>,
479) {
480 if !cx.inlined.insert(did.into()) {
481 return;
482 }
483
484 let tcx = cx.tcx;
485 let _prof_timer = tcx.sess.prof.generic_activity("build_impl");
486
487 let associated_trait = tcx.impl_opt_trait_ref(did).map(ty::EarlyBinder::skip_binder);
488
489 let is_compiler_internal = |did| {
491 tcx.lookup_stability(did)
492 .is_some_and(|stab| stab.is_unstable() && stab.feature == sym::rustc_private)
493 };
494 let document_compiler_internal = is_compiler_internal(LOCAL_CRATE.as_def_id());
495 let is_directly_public = |cx: &mut DocContext<'_>, did| {
496 cx.cache.effective_visibilities.is_directly_public(tcx, did)
497 && (document_compiler_internal || !is_compiler_internal(did))
498 };
499
500 if !did.is_local()
503 && let Some(traitref) = associated_trait
504 && !is_directly_public(cx, traitref.def_id)
505 {
506 return;
507 }
508
509 let impl_item = match did.as_local() {
510 Some(did) => match &tcx.hir_expect_item(did).kind {
511 hir::ItemKind::Impl(impl_) => Some(impl_),
512 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
513 },
514 None => None,
515 };
516
517 let for_ = match &impl_item {
518 Some(impl_) => clean_ty(impl_.self_ty, cx),
519 None => clean_middle_ty(
520 ty::Binder::dummy(tcx.type_of(did).instantiate_identity().skip_norm_wip()),
521 cx,
522 Some(did),
523 None,
524 ),
525 };
526
527 if !did.is_local()
530 && let Some(did) = for_.def_id(&cx.cache)
531 && !is_directly_public(cx, did)
532 {
533 return;
534 }
535
536 let document_hidden = cx.document_hidden();
537 let (trait_items, generics) = match impl_item {
538 Some(impl_) => (
539 impl_
540 .items
541 .iter()
542 .map(|&item| tcx.hir_impl_item(item))
543 .filter(|item| !item.is_anon_const())
544 .filter(|item| {
545 if document_hidden {
552 return true;
553 }
554 if let Some(associated_trait) = associated_trait {
555 let assoc_tag = match item.kind {
556 hir::ImplItemKind::Const(..) => ty::AssocTag::Const,
557 hir::ImplItemKind::Fn(..) => ty::AssocTag::Fn,
558 hir::ImplItemKind::Type(..) => ty::AssocTag::Type,
559 };
560 let trait_item = tcx
561 .associated_items(associated_trait.def_id)
562 .find_by_ident_and_kind(
563 tcx,
564 item.ident,
565 assoc_tag,
566 associated_trait.def_id,
567 )
568 .unwrap(); !tcx.is_doc_hidden(trait_item.def_id)
570 } else {
571 true
572 }
573 })
574 .map(|item| clean_impl_item(item, cx))
575 .collect::<Vec<_>>(),
576 clean_generics(impl_.generics, cx),
577 ),
578 None => (
579 tcx.associated_items(did)
580 .in_definition_order()
581 .filter(|item| !item.is_impl_trait_in_trait())
582 .filter(|item| {
583 if let Some(associated_trait) = associated_trait {
587 let trait_item = tcx
588 .associated_items(associated_trait.def_id)
589 .find_by_ident_and_kind(
590 tcx,
591 item.ident(tcx),
592 item.tag(),
593 associated_trait.def_id,
594 )
595 .unwrap(); document_hidden || !tcx.is_doc_hidden(trait_item.def_id)
597 } else {
598 item.visibility(tcx).is_public()
599 }
600 })
601 .map(|item| clean_middle_assoc_item(item, cx))
602 .collect::<Vec<_>>(),
603 clean::enter_impl_trait(cx, |cx| clean_ty_generics(cx, did)),
604 ),
605 };
606 let polarity = if associated_trait.is_some() {
607 tcx.impl_polarity(did)
608 } else {
609 ty::ImplPolarity::Positive
610 };
611 let trait_ = associated_trait
612 .map(|t| clean_trait_ref_with_constraints(cx, ty::Binder::dummy(t), ThinVec::new()));
613 if trait_
614 .as_ref()
615 .is_some_and(|t| polarity != ty::ImplPolarity::Negative && t.is_deref_trait(tcx))
616 {
617 super::build_deref_target_impls(cx, &trait_items, ret);
618 }
619
620 if !document_hidden {
621 let mut stack: Vec<&Type> = vec![&for_];
623
624 if let Some(did) = trait_.as_ref().map(|t| t.def_id())
625 && tcx.is_doc_hidden(did)
626 {
627 return;
628 }
629
630 if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
631 stack.extend(generics);
632 }
633
634 while let Some(ty) = stack.pop() {
635 if let Some(did) = ty.def_id(&cx.cache)
636 && tcx.is_doc_hidden(did)
637 {
638 return;
639 }
640 if let Some(generics) = ty.generics() {
641 stack.extend(generics);
642 }
643 }
644 }
645
646 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
647 cx.with_param_env(did, |cx| {
648 record_extern_trait(cx, did);
649 });
650 }
651
652 let (merged_attrs, cfg) =
657 merge_attrs(cx.tcx, load_attrs(cx.tcx, did), attrs, &mut CfgInfo::default());
658 trace!("merged_attrs={merged_attrs:?}");
659
660 trace!(
661 "build_impl: impl {:?} for {:?}",
662 trait_.as_ref().map(|t| t.def_id()),
663 for_.def_id(&cx.cache)
664 );
665 ret.push(clean::Item::from_def_id_and_attrs_and_parts(
666 did,
667 None,
668 ItemKind::Impl(Box::new(clean::Impl {
669 safety: hir::Safety::Safe,
670 generics,
671 trait_,
672 for_,
673 items: trait_items,
674 polarity,
675 kind: if utils::has_doc_flag(tcx, did, |d| d.fake_variadic.is_some()) {
676 ImplKind::FakeVariadic
677 } else {
678 ImplKind::Normal
679 },
680 is_deprecated: tcx
681 .lookup_deprecation(did)
682 .is_some_and(|deprecation| deprecation.is_in_effect()),
683 })),
684 merged_attrs,
685 cfg,
686 ));
687}
688
689fn build_module(
690 cx: &mut DocContext<'_>,
691 did: DefId,
692 name: Symbol,
693 visited: &mut DefIdSet,
694) -> clean::Module {
695 let items = build_module_items(cx, did, name, visited, &mut FxHashSet::default(), None, None);
696
697 let span = clean::Span::new(cx.tcx.def_span(did));
698 clean::Module { items, span }
699}
700
701fn should_ignore_res(res: Res) -> bool {
704 !matches!(res, Res::Def(def_kind, _) if !should_ignore_def_kind(def_kind))
705}
706
707fn should_ignore_def_kind(kind: DefKind) -> bool {
708 !matches!(
709 kind,
710 DefKind::Trait
711 | DefKind::TraitAlias
712 | DefKind::Fn
713 | DefKind::Struct
714 | DefKind::Union
715 | DefKind::TyAlias
716 | DefKind::Enum
717 | DefKind::ForeignTy
718 | DefKind::Variant
719 | DefKind::Mod
720 | DefKind::Static { .. }
721 | DefKind::Const
722 | DefKind::Macro(_)
723 | DefKind::Use
724 )
725}
726
727fn build_module_items(
728 cx: &mut DocContext<'_>,
729 module_def_id: DefId,
730 module_name: Symbol,
731 visited: &mut DefIdSet,
732 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
733 allowed_def_ids: Option<&DefIdSet>,
734 attrs: Option<(&[rustc_attr_ir::Attribute], Option<LocalDefId>)>,
735) -> Vec<clean::Item> {
736 #[inline]
737 fn make_import_item(
738 tcx: TyCtxt<'_>,
739 module_def_id: DefId,
740 module_name: Symbol,
741 def_id: Option<DefId>,
742 items: &mut Vec<clean::Item>,
743 item: &ModChild,
744 res: Res,
745 ) {
746 if should_ignore_res(res) || matches!(res, Res::Def(DefKind::Use, _)) {
748 return;
749 }
750 let mut segments = ThinVec::new();
751 if !module_def_id.is_local() && !module_def_id.is_crate_root() {
752 segments.push(clean::PathSegment {
753 name: tcx.crate_name(module_def_id.krate),
754 args: clean::GenericArgs::empty_angle_bracketed(),
755 });
756 }
757 segments.push(clean::PathSegment {
758 name: module_name,
759 args: clean::GenericArgs::empty_angle_bracketed(),
760 });
761 segments.push(clean::PathSegment {
762 name: def_id.map(|def_id| tcx.item_name(def_id)).unwrap_or(item.ident.name),
763 args: clean::GenericArgs::empty_angle_bracketed(),
764 });
765 let item = Item::from_def_id_and_parts(
766 module_def_id,
767 None,
768 ItemKind::Import(clean::Import::new_simple(
769 item.ident.name,
770 clean::ImportSource { path: clean::Path { res, segments }, did: None },
771 true,
772 )),
773 tcx,
774 );
775 items.push(item);
776 }
777
778 let mut items = Vec::new();
779
780 for item in cx.tcx.module_children(module_def_id).iter() {
784 if !item.vis.is_public() {
785 continue;
786 }
787 let res = item.res.expect_non_local();
788 if let Some(def_id) = res.opt_def_id()
789 && let Some(allowed_def_ids) = allowed_def_ids
790 && !allowed_def_ids.contains(&def_id)
791 {
792 continue;
793 }
794 if let Some(def_id) = res.mod_def_id() {
795 if module_def_id == def_id
799 || inlined_names.contains(&(ItemType::Module, item.ident.name))
800 || !visited.insert(def_id)
801 {
802 continue;
803 }
804 }
805 if let Res::PrimTy(p) = res {
806 let prim_ty = clean::PrimitiveType::from(p);
808 items.push(clean::Item {
809 inner: Box::new(clean::ItemInner {
810 name: None,
811 item_id: ItemId::DefId(module_def_id),
814 attrs: Default::default(),
815 stability: None,
816 kind: ItemKind::Import(clean::Import::new_simple(
817 item.ident.name,
818 clean::ImportSource {
819 path: clean::Path {
820 res,
821 segments: thin_vec![clean::PathSegment {
822 name: prim_ty.as_sym(),
823 args: clean::GenericArgs::AngleBracketed {
824 args: Default::default(),
825 constraints: ThinVec::new(),
826 },
827 }],
828 },
829 did: None,
830 },
831 true,
832 )),
833 cfg: None,
834 inline_stmt_id: None,
835 }),
836 });
837 } else if item.ident.name == rustc_span::kw::Underscore {
838 make_import_item(
840 cx.tcx,
841 module_def_id,
842 module_name,
843 res.opt_def_id(),
844 &mut items,
845 item,
846 res,
847 );
848 } else if let Some(def_id) = res.opt_def_id()
849 && let Some(reexport) = item.reexport_chain.first()
850 && let Some(reexport_def_id) = reexport.id()
851 && !should_ignore_def_kind(cx.tcx.def_kind(reexport_def_id))
852 && find_attr!(
853 load_attrs(cx.tcx, reexport_def_id),
854 Doc(d)
855 if d.inline.is_some_and(|(inline, _)| inline == DocInline::NoInline)
856 )
857 {
858 make_import_item(
860 cx.tcx,
861 module_def_id,
862 module_name,
863 Some(def_id),
864 &mut items,
865 item,
866 res,
867 );
868 } else if let Some(i) = try_inline(cx, res, item.ident.name, attrs, visited) {
869 items.extend(i)
870 }
871 }
872
873 items
874}
875
876pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
877 if let Some(did) = did.as_local() {
878 let hir_id = tcx.local_def_id_to_hir_id(did);
879 rustc_hir_pretty::id_to_string(&tcx, hir_id)
880 } else {
881 tcx.rendered_const(did).clone()
882 }
883}
884
885fn build_const_item(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
886 let mut generics = clean_ty_generics(cx, def_id);
887 clean::simplify::move_bounds_to_generic_parameters(&mut generics);
888 let type_ = clean_middle_ty(
889 ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()),
890 cx,
891 None,
892 None,
893 );
894 clean::Constant { generics, type_, body: clean::ConstantExpr::Extern { def_id } }
895}
896
897fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
898 clean::Static {
899 type_: Box::new(clean_middle_ty(
900 ty::Binder::dummy(cx.tcx.type_of(did).instantiate_identity().skip_norm_wip()),
901 cx,
902 Some(did),
903 None,
904 )),
905 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
906 expr: None,
907 }
908}
909
910fn build_macro(tcx: TyCtxt<'_>, def_id: DefId, name: Symbol, macro_kinds: MacroKinds) -> ItemKind {
911 match CStore::from_tcx(tcx).load_macro_untracked(tcx, def_id) {
912 LoadedMacro::MacroDef { def, .. } => match macro_kinds {
913 MacroKinds::DERIVE => ItemKind::ProcMacro(clean::ProcMacro {
914 kind: MacroKind::Derive,
915 helpers: Vec::new(),
916 }),
917 MacroKinds::ATTR => {
918 ItemKind::ProcMacro(clean::ProcMacro { kind: MacroKind::Attr, helpers: Vec::new() })
919 }
920 _ => ItemKind::DeclMacro(
921 clean::DeclMacro {
922 source: utils::display_macro_source(tcx, name, &def),
923 macro_rules: def.macro_rules,
924 },
925 macro_kinds,
926 ),
927 },
928 LoadedMacro::ProcMacro(ext) => {
929 let kind = match ext.macro_kinds() {
931 MacroKinds::BANG => MacroKind::Bang,
932 MacroKinds::ATTR => MacroKind::Attr,
933 MacroKinds::DERIVE => MacroKind::Derive,
934 _ => unreachable!(),
935 };
936 ItemKind::ProcMacro(clean::ProcMacro { kind, helpers: ext.helper_attrs })
937 }
938 }
939}
940
941fn separate_self_bounds(mut g: clean::Generics) -> (clean::Generics, Vec<clean::GenericBound>) {
942 let mut ty_bounds = Vec::new();
943 g.where_predicates.retain(|pred| match *pred {
944 clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref bounds, .. } => {
945 ty_bounds.extend(bounds.iter().cloned());
946 false
947 }
948 _ => true,
949 });
950 (g, ty_bounds)
951}
952
953pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
954 if did.is_local()
955 || cx.external_traits.contains_key(&did)
956 || cx.active_extern_traits.contains(&did)
957 {
958 return;
959 }
960
961 cx.active_extern_traits.insert(did);
962
963 debug!("record_extern_trait: {did:?}");
964 let trait_ = build_trait(cx, did);
965
966 cx.external_traits.insert(did, trait_);
967 cx.active_extern_traits.remove(&did);
968}