1mod auto_trait;
25mod blanket_impl;
26pub(crate) mod cfg;
27pub(crate) mod inline;
28mod render_macro_matchers;
29mod simplify;
30pub(crate) mod types;
31pub(crate) mod utils;
32
33use std::borrow::Cow;
34use std::collections::BTreeMap;
35use std::mem;
36
37use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry};
38use rustc_data_structures::thin_vec::ThinVec;
39use rustc_errors::codes::*;
40use rustc_errors::{FatalError, struct_span_code_err};
41use rustc_hir as hir;
42use rustc_hir::attrs::{AttributeKind, DocAttribute, DocInline};
43use rustc_hir::def::{CtorKind, DefKind, MacroKinds, Res};
44use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE, LocalDefId};
45use rustc_hir::{LangItem, PredicateOrigin, find_attr};
46use rustc_hir_analysis::hir_ty_lowering::FeedConstTy;
47use rustc_hir_analysis::{lower_const_arg_for_rustdoc, lower_ty};
48use rustc_middle::metadata::Reexport;
49use rustc_middle::middle::resolve_bound_vars as rbv;
50use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode};
51use rustc_middle::{bug, span_bug};
52use rustc_span::ExpnKind;
53use rustc_span::hygiene::{AstPass, MacroKind};
54use rustc_span::symbol::{Ident, Symbol, kw, sym};
55use rustc_trait_selection::traits::wf::object_region_bounds;
56use tracing::{debug, instrument};
57use utils::*;
58
59pub(crate) use self::cfg::{CfgInfo, extract_cfg_from_attrs};
60pub(crate) use self::types::*;
61pub(crate) use self::utils::{krate, register_res, synthesize_auto_trait_and_blanket_impls};
62use crate::core::DocContext;
63use crate::formats::item_type::ItemType;
64use crate::visit_ast::Module as DocModule;
65
66pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
67 let mut items: Vec<Item> = vec![];
68 let mut inserted = FxHashSet::default();
69 items.extend(doc.foreigns.iter().map(|(item, renamed, import_id)| {
70 let item = clean_maybe_renamed_foreign_item(cx, item, *renamed, *import_id);
71 if let Some(name) = item.name
72 && (cx.document_hidden() || !item.is_doc_hidden())
73 {
74 inserted.insert((item.type_(), name));
75 }
76 item
77 }));
78 items.extend(doc.mods.iter().filter_map(|x| {
79 if !inserted.insert((ItemType::Module, x.name)) {
80 return None;
81 }
82 let item = clean_doc_module(x, cx);
83 if !cx.document_hidden() && item.is_doc_hidden() {
84 inserted.remove(&(ItemType::Module, x.name));
88 }
89 Some(item)
90 }));
91
92 items.extend(doc.items.values().flat_map(|(item, renamed, import_ids)| {
98 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
100 return Vec::new();
101 }
102 let v = clean_maybe_renamed_item(cx, item, *renamed, import_ids);
103 for item in &v {
104 if let Some(name) = item.name
105 && (cx.document_hidden() || !item.is_doc_hidden())
106 {
107 inserted.insert((item.type_(), name));
108 }
109 }
110 v
111 }));
112 items.extend(doc.inlined_foreigns.iter().flat_map(|((_, renamed), (res, local_import_id))| {
113 let Some(def_id) = res.opt_def_id() else { return Vec::new() };
114 let name = renamed.unwrap_or_else(|| cx.tcx.item_name(def_id));
115 let import = cx.tcx.hir_expect_item(*local_import_id);
116 match import.kind {
117 hir::ItemKind::Use(path, kind) => {
118 let hir::UsePath { segments, span, .. } = *path;
119 let path = hir::Path { segments, res: *res, span };
120 clean_use_statement_inner(
121 import,
122 Some(name),
123 &path,
124 kind,
125 cx,
126 &mut Default::default(),
127 )
128 }
129 _ => unreachable!(),
130 }
131 }));
132 items.extend(doc.items.values().flat_map(|(item, renamed, _)| {
133 if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
135 clean_use_statement(item, *renamed, path, hir::UseKind::Glob, cx, &mut inserted)
136 } else {
137 Vec::new()
139 }
140 }));
141
142 let span = Span::new({
146 let where_outer = doc.where_outer(cx.tcx);
147 let sm = cx.sess().source_map();
148 let outer = sm.lookup_char_pos(where_outer.lo());
149 let inner = sm.lookup_char_pos(doc.where_inner.lo());
150 if outer.file.start_pos == inner.file.start_pos {
151 where_outer
153 } else {
154 doc.where_inner
156 }
157 });
158
159 let kind = ModuleItem(Module { items, span });
160 generate_item_with_correct_attrs(
161 cx,
162 kind,
163 doc.def_id.to_def_id(),
164 doc.name,
165 doc.import_id.as_slice(),
166 doc.renamed,
167 )
168}
169
170fn is_glob_import(tcx: TyCtxt<'_>, import_id: LocalDefId) -> bool {
171 if let hir::Node::Item(item) = tcx.hir_node_by_def_id(import_id)
172 && let hir::ItemKind::Use(_, use_kind) = item.kind
173 {
174 use_kind == hir::UseKind::Glob
175 } else {
176 false
177 }
178}
179
180fn generate_item_with_correct_attrs(
181 cx: &mut DocContext<'_>,
182 kind: ItemKind,
183 def_id: DefId,
184 name: Symbol,
185 import_ids: &[LocalDefId],
186 renamed: Option<Symbol>,
187) -> Item {
188 let target_attrs = inline::load_attrs(cx, def_id);
189 let attrs = if !import_ids.is_empty() {
190 let mut attrs = Vec::with_capacity(import_ids.len());
191 let mut is_inline = false;
192
193 for import_id in import_ids.iter().copied() {
194 let import_is_inline = find_attr!(
200 inline::load_attrs(cx, import_id.to_def_id()),
201 AttributeKind::Doc(d)
202 if d.inline.first().is_some_and(|(inline, _)| *inline == DocInline::Inline)
203 ) || (is_glob_import(cx.tcx, import_id)
204 && (cx.document_hidden() || !cx.tcx.is_doc_hidden(def_id)));
205 attrs.extend(get_all_import_attributes(cx, import_id, def_id, is_inline));
206 is_inline = is_inline || import_is_inline;
207 }
208 add_without_unwanted_attributes(&mut attrs, target_attrs, is_inline, None);
209 attrs
210 } else {
211 target_attrs.iter().map(|attr| (Cow::Borrowed(attr), None)).collect()
213 };
214 let attrs = Attributes::from_hir_iter(attrs.iter().map(|(attr, did)| (&**attr, *did)), false);
215
216 let name = renamed.or(Some(name));
217 let mut item = Item::from_def_id_and_attrs_and_parts(def_id, name, kind, attrs, None);
218 item.inner.inline_stmt_id = import_ids.first().copied();
220 item
221}
222
223fn clean_generic_bound<'tcx>(
224 bound: &hir::GenericBound<'tcx>,
225 cx: &mut DocContext<'tcx>,
226) -> Option<GenericBound> {
227 Some(match bound {
228 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
229 hir::GenericBound::Trait(t) => {
230 if let hir::BoundConstness::Maybe(_) = t.modifiers.constness
232 && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
233 {
234 return None;
235 }
236
237 GenericBound::TraitBound(clean_poly_trait_ref(t, cx), t.modifiers)
238 }
239 hir::GenericBound::Use(args, ..) => {
240 GenericBound::Use(args.iter().map(|arg| clean_precise_capturing_arg(arg, cx)).collect())
241 }
242 })
243}
244
245pub(crate) fn clean_trait_ref_with_constraints<'tcx>(
246 cx: &mut DocContext<'tcx>,
247 trait_ref: ty::PolyTraitRef<'tcx>,
248 constraints: ThinVec<AssocItemConstraint>,
249) -> Path {
250 let kind = ItemType::from_def_id(trait_ref.def_id(), cx.tcx);
251 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
252 span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {kind:?}");
253 }
254 inline::record_extern_fqn(cx, trait_ref.def_id(), kind);
255 let path = clean_middle_path(
256 cx,
257 trait_ref.def_id(),
258 true,
259 constraints,
260 trait_ref.map_bound(|tr| tr.args),
261 );
262
263 debug!(?trait_ref);
264
265 path
266}
267
268fn clean_poly_trait_ref_with_constraints<'tcx>(
269 cx: &mut DocContext<'tcx>,
270 poly_trait_ref: ty::PolyTraitRef<'tcx>,
271 constraints: ThinVec<AssocItemConstraint>,
272) -> GenericBound {
273 GenericBound::TraitBound(
274 PolyTrait {
275 trait_: clean_trait_ref_with_constraints(cx, poly_trait_ref, constraints),
276 generic_params: clean_bound_vars(poly_trait_ref.bound_vars(), cx),
277 },
278 hir::TraitBoundModifiers::NONE,
279 )
280}
281
282fn clean_lifetime(lifetime: &hir::Lifetime, cx: &DocContext<'_>) -> Lifetime {
283 if let Some(
284 rbv::ResolvedArg::EarlyBound(did)
285 | rbv::ResolvedArg::LateBound(_, _, did)
286 | rbv::ResolvedArg::Free(_, did),
287 ) = cx.tcx.named_bound_var(lifetime.hir_id)
288 && let Some(lt) = cx.args.get(&did.to_def_id()).and_then(|arg| arg.as_lt())
289 {
290 return *lt;
291 }
292 Lifetime(lifetime.ident.name)
293}
294
295pub(crate) fn clean_precise_capturing_arg(
296 arg: &hir::PreciseCapturingArg<'_>,
297 cx: &DocContext<'_>,
298) -> PreciseCapturingArg {
299 match arg {
300 hir::PreciseCapturingArg::Lifetime(lt) => {
301 PreciseCapturingArg::Lifetime(clean_lifetime(lt, cx))
302 }
303 hir::PreciseCapturingArg::Param(param) => PreciseCapturingArg::Param(param.ident.name),
304 }
305}
306
307pub(crate) fn clean_const_item_rhs<'tcx>(
308 ct_rhs: hir::ConstItemRhs<'tcx>,
309 parent: DefId,
310) -> ConstantKind {
311 match ct_rhs {
312 hir::ConstItemRhs::Body(body) => ConstantKind::Local { def_id: parent, body },
313 hir::ConstItemRhs::TypeConst(ct) => clean_const(ct),
314 }
315}
316
317pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg<'tcx>) -> ConstantKind {
318 match &constant.kind {
319 hir::ConstArgKind::Path(qpath) => {
320 ConstantKind::Path { path: qpath_to_string(qpath).into() }
321 }
322 hir::ConstArgKind::Anon(anon) => ConstantKind::Anonymous { body: anon.body },
323 hir::ConstArgKind::Infer(..) | hir::ConstArgKind::Error(..) => ConstantKind::Infer,
324 }
325}
326
327pub(crate) fn clean_middle_const<'tcx>(
328 constant: ty::Binder<'tcx, ty::Const<'tcx>>,
329 _cx: &mut DocContext<'tcx>,
330) -> ConstantKind {
331 ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() }
333}
334
335pub(crate) fn clean_middle_region<'tcx>(
336 region: ty::Region<'tcx>,
337 cx: &mut DocContext<'tcx>,
338) -> Option<Lifetime> {
339 region.get_name(cx.tcx).map(Lifetime)
340}
341
342fn clean_where_predicate<'tcx>(
343 predicate: &hir::WherePredicate<'tcx>,
344 cx: &mut DocContext<'tcx>,
345) -> Option<WherePredicate> {
346 if !predicate.kind.in_where_clause() {
347 return None;
348 }
349 Some(match predicate.kind {
350 hir::WherePredicateKind::BoundPredicate(wbp) => {
351 let bound_params = wbp
352 .bound_generic_params
353 .iter()
354 .map(|param| clean_generic_param(cx, None, param))
355 .collect();
356 WherePredicate::BoundPredicate {
357 ty: clean_ty(wbp.bounded_ty, cx),
358 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
359 bound_params,
360 }
361 }
362
363 hir::WherePredicateKind::RegionPredicate(wrp) => WherePredicate::RegionPredicate {
364 lifetime: clean_lifetime(wrp.lifetime, cx),
365 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
366 },
367
368 hir::WherePredicateKind::EqPredicate(_) => bug!("EqPredicate"),
371 })
372}
373
374pub(crate) fn clean_predicate<'tcx>(
375 predicate: ty::Clause<'tcx>,
376 cx: &mut DocContext<'tcx>,
377) -> Option<WherePredicate> {
378 let bound_predicate = predicate.kind();
379 match bound_predicate.skip_binder() {
380 ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_predicate.rebind(pred), cx),
381 ty::ClauseKind::RegionOutlives(pred) => Some(clean_region_outlives_predicate(pred, cx)),
382 ty::ClauseKind::TypeOutlives(pred) => {
383 Some(clean_type_outlives_predicate(bound_predicate.rebind(pred), cx))
384 }
385 ty::ClauseKind::Projection(pred) => {
386 Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
387 }
388 ty::ClauseKind::ConstEvaluatable(..)
390 | ty::ClauseKind::WellFormed(..)
391 | ty::ClauseKind::ConstArgHasType(..)
392 | ty::ClauseKind::UnstableFeature(..)
393 | ty::ClauseKind::HostEffect(_) => None,
395 }
396}
397
398fn clean_poly_trait_predicate<'tcx>(
399 pred: ty::PolyTraitPredicate<'tcx>,
400 cx: &mut DocContext<'tcx>,
401) -> Option<WherePredicate> {
402 if Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait() {
405 return None;
406 }
407
408 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
409 Some(WherePredicate::BoundPredicate {
410 ty: clean_middle_ty(poly_trait_ref.self_ty(), cx, None, None),
411 bounds: vec![clean_poly_trait_ref_with_constraints(cx, poly_trait_ref, ThinVec::new())],
412 bound_params: Vec::new(),
413 })
414}
415
416fn clean_region_outlives_predicate<'tcx>(
417 pred: ty::RegionOutlivesPredicate<'tcx>,
418 cx: &mut DocContext<'tcx>,
419) -> WherePredicate {
420 let ty::OutlivesPredicate(a, b) = pred;
421
422 WherePredicate::RegionPredicate {
423 lifetime: clean_middle_region(a, cx).expect("failed to clean lifetime"),
424 bounds: vec![GenericBound::Outlives(
425 clean_middle_region(b, cx).expect("failed to clean bounds"),
426 )],
427 }
428}
429
430fn clean_type_outlives_predicate<'tcx>(
431 pred: ty::Binder<'tcx, ty::TypeOutlivesPredicate<'tcx>>,
432 cx: &mut DocContext<'tcx>,
433) -> WherePredicate {
434 let ty::OutlivesPredicate(ty, lt) = pred.skip_binder();
435
436 WherePredicate::BoundPredicate {
437 ty: clean_middle_ty(pred.rebind(ty), cx, None, None),
438 bounds: vec![GenericBound::Outlives(
439 clean_middle_region(lt, cx).expect("failed to clean lifetimes"),
440 )],
441 bound_params: Vec::new(),
442 }
443}
444
445fn clean_middle_term<'tcx>(
446 term: ty::Binder<'tcx, ty::Term<'tcx>>,
447 cx: &mut DocContext<'tcx>,
448) -> Term {
449 match term.skip_binder().kind() {
450 ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(term.rebind(ty), cx, None, None)),
451 ty::TermKind::Const(c) => Term::Constant(clean_middle_const(term.rebind(c), cx)),
452 }
453}
454
455fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
456 match term {
457 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
458 hir::Term::Const(c) => {
459 let ct = lower_const_arg_for_rustdoc(cx.tcx, c, FeedConstTy::No);
460 Term::Constant(clean_middle_const(ty::Binder::dummy(ct), cx))
461 }
462 }
463}
464
465fn clean_projection_predicate<'tcx>(
466 pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
467 cx: &mut DocContext<'tcx>,
468) -> WherePredicate {
469 WherePredicate::EqPredicate {
470 lhs: clean_projection(pred.map_bound(|p| p.projection_term), cx, None),
471 rhs: clean_middle_term(pred.map_bound(|p| p.term), cx),
472 }
473}
474
475fn clean_projection<'tcx>(
476 proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
477 cx: &mut DocContext<'tcx>,
478 parent_def_id: Option<DefId>,
479) -> QPathData {
480 let trait_ = clean_trait_ref_with_constraints(
481 cx,
482 proj.map_bound(|proj| proj.trait_ref(cx.tcx)),
483 ThinVec::new(),
484 );
485 let self_type = clean_middle_ty(proj.map_bound(|proj| proj.self_ty()), cx, None, None);
486 let self_def_id = match parent_def_id {
487 Some(parent_def_id) => cx.tcx.opt_parent(parent_def_id).or(Some(parent_def_id)),
488 None => self_type.def_id(&cx.cache),
489 };
490 let should_fully_qualify = should_fully_qualify_path(self_def_id, &trait_, &self_type);
491
492 QPathData {
493 assoc: projection_to_path_segment(proj, cx),
494 self_type,
495 should_fully_qualify,
496 trait_: Some(trait_),
497 }
498}
499
500fn should_fully_qualify_path(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
501 !trait_.segments.is_empty()
502 && self_def_id
503 .zip(Some(trait_.def_id()))
504 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
505}
506
507fn projection_to_path_segment<'tcx>(
508 proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
509 cx: &mut DocContext<'tcx>,
510) -> PathSegment {
511 let def_id = proj.skip_binder().def_id;
512 let generics = cx.tcx.generics_of(def_id);
513 PathSegment {
514 name: cx.tcx.item_name(def_id),
515 args: GenericArgs::AngleBracketed {
516 args: clean_middle_generic_args(
517 cx,
518 proj.map_bound(|ty| &ty.args[generics.parent_count..]),
519 false,
520 def_id,
521 ),
522 constraints: Default::default(),
523 },
524 }
525}
526
527fn clean_generic_param_def(
528 def: &ty::GenericParamDef,
529 defaults: ParamDefaults,
530 cx: &mut DocContext<'_>,
531) -> GenericParamDef {
532 let (name, kind) = match def.kind {
533 ty::GenericParamDefKind::Lifetime => {
534 (def.name, GenericParamDefKind::Lifetime { outlives: ThinVec::new() })
535 }
536 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
537 let default = if let ParamDefaults::Yes = defaults
538 && has_default
539 {
540 Some(clean_middle_ty(
541 ty::Binder::dummy(cx.tcx.type_of(def.def_id).instantiate_identity()),
542 cx,
543 Some(def.def_id),
544 None,
545 ))
546 } else {
547 None
548 };
549 (
550 def.name,
551 GenericParamDefKind::Type {
552 bounds: ThinVec::new(), default: default.map(Box::new),
554 synthetic,
555 },
556 )
557 }
558 ty::GenericParamDefKind::Const { has_default } => (
559 def.name,
560 GenericParamDefKind::Const {
561 ty: Box::new(clean_middle_ty(
562 ty::Binder::dummy(cx.tcx.type_of(def.def_id).instantiate_identity()),
563 cx,
564 Some(def.def_id),
565 None,
566 )),
567 default: if let ParamDefaults::Yes = defaults
568 && has_default
569 {
570 Some(Box::new(
571 cx.tcx.const_param_default(def.def_id).instantiate_identity().to_string(),
572 ))
573 } else {
574 None
575 },
576 },
577 ),
578 };
579
580 GenericParamDef { name, def_id: def.def_id, kind }
581}
582
583enum ParamDefaults {
585 Yes,
586 No,
587}
588
589fn clean_generic_param<'tcx>(
590 cx: &mut DocContext<'tcx>,
591 generics: Option<&hir::Generics<'tcx>>,
592 param: &hir::GenericParam<'tcx>,
593) -> GenericParamDef {
594 let (name, kind) = match param.kind {
595 hir::GenericParamKind::Lifetime { .. } => {
596 let outlives = if let Some(generics) = generics {
597 generics
598 .outlives_for_param(param.def_id)
599 .filter(|bp| !bp.in_where_clause)
600 .flat_map(|bp| bp.bounds)
601 .map(|bound| match bound {
602 hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
603 _ => panic!(),
604 })
605 .collect()
606 } else {
607 ThinVec::new()
608 };
609 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
610 }
611 hir::GenericParamKind::Type { ref default, synthetic } => {
612 let bounds = if let Some(generics) = generics {
613 generics
614 .bounds_for_param(param.def_id)
615 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
616 .flat_map(|bp| bp.bounds)
617 .filter_map(|x| clean_generic_bound(x, cx))
618 .collect()
619 } else {
620 ThinVec::new()
621 };
622 (
623 param.name.ident().name,
624 GenericParamDefKind::Type {
625 bounds,
626 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
627 synthetic,
628 },
629 )
630 }
631 hir::GenericParamKind::Const { ty, default } => (
632 param.name.ident().name,
633 GenericParamDefKind::Const {
634 ty: Box::new(clean_ty(ty, cx)),
635 default: default.map(|ct| {
636 Box::new(lower_const_arg_for_rustdoc(cx.tcx, ct, FeedConstTy::No).to_string())
637 }),
638 },
639 ),
640 };
641
642 GenericParamDef { name, def_id: param.def_id.to_def_id(), kind }
643}
644
645fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
649 match param.kind {
650 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
651 _ => false,
652 }
653}
654
655fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
659 matches!(
660 param.kind,
661 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) }
662 )
663}
664
665pub(crate) fn clean_generics<'tcx>(
666 gens: &hir::Generics<'tcx>,
667 cx: &mut DocContext<'tcx>,
668) -> Generics {
669 let impl_trait_params = gens
670 .params
671 .iter()
672 .filter(|param| is_impl_trait(param))
673 .map(|param| {
674 let param = clean_generic_param(cx, Some(gens), param);
675 match param.kind {
676 GenericParamDefKind::Lifetime { .. } => unreachable!(),
677 GenericParamDefKind::Type { ref bounds, .. } => {
678 cx.impl_trait_bounds.insert(param.def_id.into(), bounds.to_vec());
679 }
680 GenericParamDefKind::Const { .. } => unreachable!(),
681 }
682 param
683 })
684 .collect::<Vec<_>>();
685
686 let mut bound_predicates = FxIndexMap::default();
687 let mut region_predicates = FxIndexMap::default();
688 let mut eq_predicates = ThinVec::default();
689 for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
690 match pred {
691 WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
692 match bound_predicates.entry(ty) {
693 IndexEntry::Vacant(v) => {
694 v.insert((bounds, bound_params));
695 }
696 IndexEntry::Occupied(mut o) => {
697 for bound in bounds {
699 if !o.get().0.contains(&bound) {
700 o.get_mut().0.push(bound);
701 }
702 }
703 for bound_param in bound_params {
704 if !o.get().1.contains(&bound_param) {
705 o.get_mut().1.push(bound_param);
706 }
707 }
708 }
709 }
710 }
711 WherePredicate::RegionPredicate { lifetime, bounds } => {
712 match region_predicates.entry(lifetime) {
713 IndexEntry::Vacant(v) => {
714 v.insert(bounds);
715 }
716 IndexEntry::Occupied(mut o) => {
717 for bound in bounds {
719 if !o.get().contains(&bound) {
720 o.get_mut().push(bound);
721 }
722 }
723 }
724 }
725 }
726 WherePredicate::EqPredicate { lhs, rhs } => {
727 eq_predicates.push(WherePredicate::EqPredicate { lhs, rhs });
728 }
729 }
730 }
731
732 let mut params = ThinVec::with_capacity(gens.params.len());
733 for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
737 let mut p = clean_generic_param(cx, Some(gens), p);
738 match &mut p.kind {
739 GenericParamDefKind::Lifetime { outlives } => {
740 if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
741 for outlive in outlives.drain(..) {
743 let outlive = GenericBound::Outlives(outlive);
744 if !region_pred.contains(&outlive) {
745 region_pred.push(outlive);
746 }
747 }
748 }
749 }
750 GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
751 if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
752 for bound in bounds.drain(..) {
754 if !bound_pred.0.contains(&bound) {
755 bound_pred.0.push(bound);
756 }
757 }
758 }
759 }
760 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
761 }
763 }
764 params.push(p);
765 }
766 params.extend(impl_trait_params);
767
768 Generics {
769 params,
770 where_predicates: bound_predicates
771 .into_iter()
772 .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
773 ty,
774 bounds,
775 bound_params,
776 })
777 .chain(
778 region_predicates
779 .into_iter()
780 .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
781 )
782 .chain(eq_predicates)
783 .collect(),
784 }
785}
786
787fn clean_ty_generics<'tcx>(cx: &mut DocContext<'tcx>, def_id: DefId) -> Generics {
788 clean_ty_generics_inner(cx, cx.tcx.generics_of(def_id), cx.tcx.explicit_predicates_of(def_id))
789}
790
791fn clean_ty_generics_inner<'tcx>(
792 cx: &mut DocContext<'tcx>,
793 gens: &ty::Generics,
794 preds: ty::GenericPredicates<'tcx>,
795) -> Generics {
796 let mut impl_trait = BTreeMap::<u32, Vec<GenericBound>>::default();
799
800 let params: ThinVec<_> = gens
801 .own_params
802 .iter()
803 .filter(|param| match param.kind {
804 ty::GenericParamDefKind::Lifetime => !param.is_anonymous_lifetime(),
805 ty::GenericParamDefKind::Type { synthetic, .. } => {
806 if param.name == kw::SelfUpper {
807 debug_assert_eq!(param.index, 0);
808 return false;
809 }
810 if synthetic {
811 impl_trait.insert(param.index, vec![]);
812 return false;
813 }
814 true
815 }
816 ty::GenericParamDefKind::Const { .. } => true,
817 })
818 .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx))
819 .collect();
820
821 let mut impl_trait_proj =
823 FxHashMap::<u32, Vec<(DefId, PathSegment, ty::Binder<'_, ty::Term<'_>>)>>::default();
824
825 let where_predicates = preds
826 .predicates
827 .iter()
828 .flat_map(|(pred, _)| {
829 let mut proj_pred = None;
830 let param_idx = {
831 let bound_p = pred.kind();
832 match bound_p.skip_binder() {
833 ty::ClauseKind::Trait(pred) if let ty::Param(param) = pred.self_ty().kind() => {
834 Some(param.index)
835 }
836 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg))
837 if let ty::Param(param) = ty.kind() =>
838 {
839 Some(param.index)
840 }
841 ty::ClauseKind::Projection(p)
842 if let ty::Param(param) = p.projection_term.self_ty().kind() =>
843 {
844 proj_pred = Some(bound_p.rebind(p));
845 Some(param.index)
846 }
847 _ => None,
848 }
849 };
850
851 if let Some(param_idx) = param_idx
852 && let Some(bounds) = impl_trait.get_mut(¶m_idx)
853 {
854 let pred = clean_predicate(*pred, cx)?;
855
856 bounds.extend(pred.get_bounds().into_iter().flatten().cloned());
857
858 if let Some(pred) = proj_pred {
859 let lhs = clean_projection(pred.map_bound(|p| p.projection_term), cx, None);
860 impl_trait_proj.entry(param_idx).or_default().push((
861 lhs.trait_.unwrap().def_id(),
862 lhs.assoc,
863 pred.map_bound(|p| p.term),
864 ));
865 }
866
867 return None;
868 }
869
870 Some(pred)
871 })
872 .collect::<Vec<_>>();
873
874 for (idx, mut bounds) in impl_trait {
875 let mut has_sized = false;
876 bounds.retain(|b| {
877 if b.is_sized_bound(cx) {
878 has_sized = true;
879 false
880 } else if b.is_meta_sized_bound(cx) {
881 false
884 } else {
885 true
886 }
887 });
888 if !has_sized {
889 bounds.push(GenericBound::maybe_sized(cx));
890 }
891
892 bounds.sort_by_key(|b| !b.is_trait_bound());
894
895 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
898 bounds.insert(0, GenericBound::sized(cx));
899 }
900
901 if let Some(proj) = impl_trait_proj.remove(&idx) {
902 for (trait_did, name, rhs) in proj {
903 let rhs = clean_middle_term(rhs, cx);
904 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
905 }
906 }
907
908 cx.impl_trait_bounds.insert(idx.into(), bounds);
909 }
910
911 let where_predicates =
914 where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect();
915
916 let mut generics = Generics { params, where_predicates };
917 simplify::sized_bounds(cx, &mut generics);
918 generics.where_predicates = simplify::where_clauses(cx, generics.where_predicates);
919 generics
920}
921
922fn clean_ty_alias_inner_type<'tcx>(
923 ty: Ty<'tcx>,
924 cx: &mut DocContext<'tcx>,
925 ret: &mut Vec<Item>,
926) -> Option<TypeAliasInnerType> {
927 let ty::Adt(adt_def, args) = ty.kind() else {
928 return None;
929 };
930
931 if !adt_def.did().is_local() {
932 cx.with_param_env(adt_def.did(), |cx| {
933 inline::build_impls(cx, adt_def.did(), None, ret);
934 });
935 }
936
937 Some(if adt_def.is_enum() {
938 let variants: rustc_index::IndexVec<_, _> = adt_def
939 .variants()
940 .iter()
941 .map(|variant| clean_variant_def_with_args(variant, args, cx))
942 .collect();
943
944 if !adt_def.did().is_local() {
945 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Enum);
946 }
947
948 TypeAliasInnerType::Enum {
949 variants,
950 is_non_exhaustive: adt_def.is_variant_list_non_exhaustive(),
951 }
952 } else {
953 let variant = adt_def
954 .variants()
955 .iter()
956 .next()
957 .unwrap_or_else(|| bug!("a struct or union should always have one variant def"));
958
959 let fields: Vec<_> =
960 clean_variant_def_with_args(variant, args, cx).kind.inner_items().cloned().collect();
961
962 if adt_def.is_struct() {
963 if !adt_def.did().is_local() {
964 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Struct);
965 }
966 TypeAliasInnerType::Struct { ctor_kind: variant.ctor_kind(), fields }
967 } else {
968 if !adt_def.did().is_local() {
969 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Union);
970 }
971 TypeAliasInnerType::Union { fields }
972 }
973 })
974}
975
976fn clean_proc_macro<'tcx>(
977 item: &hir::Item<'tcx>,
978 name: &mut Symbol,
979 kind: MacroKind,
980 cx: &mut DocContext<'tcx>,
981) -> ItemKind {
982 if kind != MacroKind::Derive {
983 return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
984 }
985 let attrs = cx.tcx.hir_attrs(item.hir_id());
986 let Some((trait_name, helper_attrs)) = find_attr!(attrs, AttributeKind::ProcMacroDerive { trait_name, helper_attrs, ..} => (*trait_name, helper_attrs))
987 else {
988 return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
989 };
990 *name = trait_name;
991 let helpers = helper_attrs.iter().copied().collect();
992
993 ProcMacroItem(ProcMacro { kind, helpers })
994}
995
996fn clean_fn_or_proc_macro<'tcx>(
997 item: &hir::Item<'tcx>,
998 sig: &hir::FnSig<'tcx>,
999 generics: &hir::Generics<'tcx>,
1000 body_id: hir::BodyId,
1001 name: &mut Symbol,
1002 cx: &mut DocContext<'tcx>,
1003) -> ItemKind {
1004 let attrs = cx.tcx.hir_attrs(item.hir_id());
1005 let macro_kind = if find_attr!(attrs, AttributeKind::ProcMacro(..)) {
1006 Some(MacroKind::Bang)
1007 } else if find_attr!(attrs, AttributeKind::ProcMacroDerive { .. }) {
1008 Some(MacroKind::Derive)
1009 } else if find_attr!(attrs, AttributeKind::ProcMacroAttribute(..)) {
1010 Some(MacroKind::Attr)
1011 } else {
1012 None
1013 };
1014
1015 match macro_kind {
1016 Some(kind) => clean_proc_macro(item, name, kind, cx),
1017 None => {
1018 let mut func = clean_function(cx, sig, generics, ParamsSrc::Body(body_id));
1019 clean_fn_decl_legacy_const_generics(&mut func, attrs);
1020 FunctionItem(func)
1021 }
1022 }
1023}
1024
1025fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) {
1029 let Some(indexes) =
1030 find_attr!(attrs, AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes)
1031 else {
1032 return;
1033 };
1034
1035 for (pos, (index, _)) in indexes.iter().enumerate() {
1036 let GenericParamDef { name, kind, .. } = func.generics.params.remove(0);
1037 if let GenericParamDefKind::Const { ty, .. } = kind {
1038 func.decl
1039 .inputs
1040 .insert(*index, Parameter { name: Some(name), type_: *ty, is_const: true });
1041 } else {
1042 panic!("unexpected non const in position {pos}");
1043 }
1044 }
1045}
1046
1047enum ParamsSrc<'tcx> {
1048 Body(hir::BodyId),
1049 Idents(&'tcx [Option<Ident>]),
1050}
1051
1052fn clean_function<'tcx>(
1053 cx: &mut DocContext<'tcx>,
1054 sig: &hir::FnSig<'tcx>,
1055 generics: &hir::Generics<'tcx>,
1056 params: ParamsSrc<'tcx>,
1057) -> Box<Function> {
1058 let (generics, decl) = enter_impl_trait(cx, |cx| {
1059 let generics = clean_generics(generics, cx);
1061 let params = match params {
1062 ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl.inputs, body_id),
1063 ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents, |ident| {
1065 Some(ident.map_or(kw::Underscore, |ident| ident.name))
1066 }),
1067 };
1068 let decl = clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params);
1069 (generics, decl)
1070 });
1071 Box::new(Function { decl, generics })
1072}
1073
1074fn clean_params<'tcx>(
1075 cx: &mut DocContext<'tcx>,
1076 types: &[hir::Ty<'tcx>],
1077 idents: &[Option<Ident>],
1078 postprocess: impl Fn(Option<Ident>) -> Option<Symbol>,
1079) -> Vec<Parameter> {
1080 types
1081 .iter()
1082 .enumerate()
1083 .map(|(i, ty)| Parameter {
1084 name: postprocess(idents[i]),
1085 type_: clean_ty(ty, cx),
1086 is_const: false,
1087 })
1088 .collect()
1089}
1090
1091fn clean_params_via_body<'tcx>(
1092 cx: &mut DocContext<'tcx>,
1093 types: &[hir::Ty<'tcx>],
1094 body_id: hir::BodyId,
1095) -> Vec<Parameter> {
1096 types
1097 .iter()
1098 .zip(cx.tcx.hir_body(body_id).params)
1099 .map(|(ty, param)| Parameter {
1100 name: Some(name_from_pat(param.pat)),
1101 type_: clean_ty(ty, cx),
1102 is_const: false,
1103 })
1104 .collect()
1105}
1106
1107fn clean_fn_decl_with_params<'tcx>(
1108 cx: &mut DocContext<'tcx>,
1109 decl: &hir::FnDecl<'tcx>,
1110 header: Option<&hir::FnHeader>,
1111 params: Vec<Parameter>,
1112) -> FnDecl {
1113 let mut output = match decl.output {
1114 hir::FnRetTy::Return(typ) => clean_ty(typ, cx),
1115 hir::FnRetTy::DefaultReturn(..) => Type::Tuple(Vec::new()),
1116 };
1117 if let Some(header) = header
1118 && header.is_async()
1119 {
1120 output = output.sugared_async_return_type();
1121 }
1122 FnDecl { inputs: params, output, c_variadic: decl.c_variadic }
1123}
1124
1125fn clean_poly_fn_sig<'tcx>(
1126 cx: &mut DocContext<'tcx>,
1127 did: Option<DefId>,
1128 sig: ty::PolyFnSig<'tcx>,
1129) -> FnDecl {
1130 let mut output = clean_middle_ty(sig.output(), cx, None, None);
1131
1132 if let Some(did) = did
1136 && let Type::ImplTrait(_) = output
1137 && cx.tcx.asyncness(did).is_async()
1138 {
1139 output = output.sugared_async_return_type();
1140 }
1141
1142 let mut idents = did.map(|did| cx.tcx.fn_arg_idents(did)).unwrap_or_default().iter().copied();
1143
1144 let fallback = did.map(|_| kw::Underscore);
1149
1150 let params = sig
1151 .inputs()
1152 .iter()
1153 .map(|ty| Parameter {
1154 name: idents.next().flatten().map(|ident| ident.name).or(fallback),
1155 type_: clean_middle_ty(ty.map_bound(|ty| *ty), cx, None, None),
1156 is_const: false,
1157 })
1158 .collect();
1159
1160 FnDecl { inputs: params, output, c_variadic: sig.skip_binder().c_variadic }
1161}
1162
1163fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1164 let path = clean_path(trait_ref.path, cx);
1165 register_res(cx, path.res);
1166 path
1167}
1168
1169fn clean_poly_trait_ref<'tcx>(
1170 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1171 cx: &mut DocContext<'tcx>,
1172) -> PolyTrait {
1173 PolyTrait {
1174 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1175 generic_params: poly_trait_ref
1176 .bound_generic_params
1177 .iter()
1178 .filter(|p| !is_elided_lifetime(p))
1179 .map(|x| clean_generic_param(cx, None, x))
1180 .collect(),
1181 }
1182}
1183
1184fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1185 let local_did = trait_item.owner_id.to_def_id();
1186 cx.with_param_env(local_did, |cx| {
1187 let inner = match trait_item.kind {
1188 hir::TraitItemKind::Const(ty, Some(default)) => {
1189 ProvidedAssocConstItem(Box::new(Constant {
1190 generics: enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)),
1191 kind: clean_const_item_rhs(default, local_did),
1192 type_: clean_ty(ty, cx),
1193 }))
1194 }
1195 hir::TraitItemKind::Const(ty, None) => {
1196 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1197 RequiredAssocConstItem(generics, Box::new(clean_ty(ty, cx)))
1198 }
1199 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1200 let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Body(body));
1201 MethodItem(m, None)
1202 }
1203 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(idents)) => {
1204 let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Idents(idents));
1205 RequiredMethodItem(m)
1206 }
1207 hir::TraitItemKind::Type(bounds, Some(default)) => {
1208 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1209 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1210 let item_type =
1211 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, default)), cx, None, None);
1212 AssocTypeItem(
1213 Box::new(TypeAlias {
1214 type_: clean_ty(default, cx),
1215 generics,
1216 inner_type: None,
1217 item_type: Some(item_type),
1218 }),
1219 bounds,
1220 )
1221 }
1222 hir::TraitItemKind::Type(bounds, None) => {
1223 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1224 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1225 RequiredAssocTypeItem(generics, bounds)
1226 }
1227 };
1228 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx)
1229 })
1230}
1231
1232pub(crate) fn clean_impl_item<'tcx>(
1233 impl_: &hir::ImplItem<'tcx>,
1234 cx: &mut DocContext<'tcx>,
1235) -> Item {
1236 let local_did = impl_.owner_id.to_def_id();
1237 cx.with_param_env(local_did, |cx| {
1238 let inner = match impl_.kind {
1239 hir::ImplItemKind::Const(ty, expr) => ImplAssocConstItem(Box::new(Constant {
1240 generics: clean_generics(impl_.generics, cx),
1241 kind: clean_const_item_rhs(expr, local_did),
1242 type_: clean_ty(ty, cx),
1243 })),
1244 hir::ImplItemKind::Fn(ref sig, body) => {
1245 let m = clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body));
1246 let defaultness = match impl_.impl_kind {
1247 hir::ImplItemImplKind::Inherent { .. } => hir::Defaultness::Final,
1248 hir::ImplItemImplKind::Trait { defaultness, .. } => defaultness,
1249 };
1250 MethodItem(m, Some(defaultness))
1251 }
1252 hir::ImplItemKind::Type(hir_ty) => {
1253 let type_ = clean_ty(hir_ty, cx);
1254 let generics = clean_generics(impl_.generics, cx);
1255 let item_type =
1256 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1257 AssocTypeItem(
1258 Box::new(TypeAlias {
1259 type_,
1260 generics,
1261 inner_type: None,
1262 item_type: Some(item_type),
1263 }),
1264 Vec::new(),
1265 )
1266 }
1267 };
1268
1269 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1270 })
1271}
1272
1273pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1274 let tcx = cx.tcx;
1275 let kind = match assoc_item.kind {
1276 ty::AssocKind::Const { .. } => {
1277 let ty = clean_middle_ty(
1278 ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()),
1279 cx,
1280 Some(assoc_item.def_id),
1281 None,
1282 );
1283
1284 let mut generics = clean_ty_generics(cx, assoc_item.def_id);
1285 simplify::move_bounds_to_generic_parameters(&mut generics);
1286
1287 match assoc_item.container {
1288 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1289 ImplAssocConstItem(Box::new(Constant {
1290 generics,
1291 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1292 type_: ty,
1293 }))
1294 }
1295 ty::AssocContainer::Trait => {
1296 if tcx.defaultness(assoc_item.def_id).has_value() {
1297 ProvidedAssocConstItem(Box::new(Constant {
1298 generics,
1299 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1300 type_: ty,
1301 }))
1302 } else {
1303 RequiredAssocConstItem(generics, Box::new(ty))
1304 }
1305 }
1306 }
1307 }
1308 ty::AssocKind::Fn { has_self, .. } => {
1309 let mut item = inline::build_function(cx, assoc_item.def_id);
1310
1311 if has_self {
1312 let self_ty = match assoc_item.container {
1313 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1314 tcx.type_of(assoc_item.container_id(tcx)).instantiate_identity()
1315 }
1316 ty::AssocContainer::Trait => tcx.types.self_param,
1317 };
1318 let self_param_ty =
1319 tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder();
1320 if self_param_ty == self_ty {
1321 item.decl.inputs[0].type_ = SelfTy;
1322 } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1323 && ty == self_ty
1324 {
1325 match item.decl.inputs[0].type_ {
1326 BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1327 _ => unreachable!(),
1328 }
1329 }
1330 }
1331
1332 let provided = match assoc_item.container {
1333 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1334 ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1335 };
1336 if provided {
1337 let defaultness = match assoc_item.container {
1338 ty::AssocContainer::TraitImpl(_) => Some(assoc_item.defaultness(tcx)),
1339 ty::AssocContainer::InherentImpl | ty::AssocContainer::Trait => None,
1340 };
1341 MethodItem(item, defaultness)
1342 } else {
1343 RequiredMethodItem(item)
1344 }
1345 }
1346 ty::AssocKind::Type { .. } => {
1347 let my_name = assoc_item.name();
1348
1349 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1350 match (¶m.kind, arg) {
1351 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1352 if *ty == param.name =>
1353 {
1354 true
1355 }
1356 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1357 if *lt == param.name =>
1358 {
1359 true
1360 }
1361 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1362 ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1363 _ => false,
1364 },
1365 _ => false,
1366 }
1367 }
1368
1369 let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1370 if let ty::AssocContainer::Trait = assoc_item.container {
1371 let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied();
1372 predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied()));
1373 }
1374 let mut generics = clean_ty_generics_inner(
1375 cx,
1376 tcx.generics_of(assoc_item.def_id),
1377 ty::GenericPredicates { parent: None, predicates },
1378 );
1379 simplify::move_bounds_to_generic_parameters(&mut generics);
1380
1381 if let ty::AssocContainer::Trait = assoc_item.container {
1382 let mut bounds: Vec<GenericBound> = Vec::new();
1387 generics.where_predicates.retain_mut(|pred| match *pred {
1388 WherePredicate::BoundPredicate {
1389 ty:
1390 QPath(box QPathData {
1391 ref assoc,
1392 ref self_type,
1393 trait_: Some(ref trait_),
1394 ..
1395 }),
1396 bounds: ref mut pred_bounds,
1397 ..
1398 } => {
1399 if assoc.name != my_name {
1400 return true;
1401 }
1402 if trait_.def_id() != assoc_item.container_id(tcx) {
1403 return true;
1404 }
1405 if *self_type != SelfTy {
1406 return true;
1407 }
1408 match &assoc.args {
1409 GenericArgs::AngleBracketed { args, constraints } => {
1410 if !constraints.is_empty()
1411 || generics
1412 .params
1413 .iter()
1414 .zip(args.iter())
1415 .any(|(param, arg)| !param_eq_arg(param, arg))
1416 {
1417 return true;
1418 }
1419 }
1420 GenericArgs::Parenthesized { .. } => {
1421 }
1424 GenericArgs::ReturnTypeNotation => {
1425 }
1427 }
1428 bounds.extend(mem::take(pred_bounds));
1429 false
1430 }
1431 _ => true,
1432 });
1433
1434 bounds.retain(|b| {
1435 !b.is_meta_sized_bound(cx)
1438 });
1439
1440 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1446 Some(i) => {
1447 bounds.remove(i);
1448 }
1449 None => bounds.push(GenericBound::maybe_sized(cx)),
1450 }
1451
1452 if tcx.defaultness(assoc_item.def_id).has_value() {
1453 AssocTypeItem(
1454 Box::new(TypeAlias {
1455 type_: clean_middle_ty(
1456 ty::Binder::dummy(
1457 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1458 ),
1459 cx,
1460 Some(assoc_item.def_id),
1461 None,
1462 ),
1463 generics,
1464 inner_type: None,
1465 item_type: None,
1466 }),
1467 bounds,
1468 )
1469 } else {
1470 RequiredAssocTypeItem(generics, bounds)
1471 }
1472 } else {
1473 AssocTypeItem(
1474 Box::new(TypeAlias {
1475 type_: clean_middle_ty(
1476 ty::Binder::dummy(
1477 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1478 ),
1479 cx,
1480 Some(assoc_item.def_id),
1481 None,
1482 ),
1483 generics,
1484 inner_type: None,
1485 item_type: None,
1486 }),
1487 Vec::new(),
1490 )
1491 }
1492 }
1493 };
1494
1495 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, cx)
1496}
1497
1498fn first_non_private_clean_path<'tcx>(
1499 cx: &mut DocContext<'tcx>,
1500 path: &hir::Path<'tcx>,
1501 new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1502 new_path_span: rustc_span::Span,
1503) -> Path {
1504 let new_hir_path =
1505 hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1506 let mut new_clean_path = clean_path(&new_hir_path, cx);
1507 if let Some(path_last) = path.segments.last().as_ref()
1512 && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1513 && let Some(path_last_args) = path_last.args.as_ref()
1514 && path_last.args.is_some()
1515 {
1516 assert!(new_path_last.args.is_empty());
1517 new_path_last.args = clean_generic_args(path_last_args, cx);
1518 }
1519 new_clean_path
1520}
1521
1522fn first_non_private<'tcx>(
1527 cx: &mut DocContext<'tcx>,
1528 hir_id: hir::HirId,
1529 path: &hir::Path<'tcx>,
1530) -> Option<Path> {
1531 let target_def_id = path.res.opt_def_id()?;
1532 let (parent_def_id, ident) = match &path.segments {
1533 [] => return None,
1534 [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1536 [parent, leaf] if parent.ident.name == kw::SelfLower => {
1538 (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1539 }
1540 [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1542 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1543 }
1544 [parent, leaf] if parent.ident.name == kw::Super => {
1545 let parent_mod = cx.tcx.parent_module(hir_id);
1546 if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1547 (super_parent, leaf.ident)
1548 } else {
1549 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1551 }
1552 }
1553 [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1555 };
1556 for child in
1558 cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1559 {
1560 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1561 continue;
1562 }
1563
1564 if let Some(def_id) = child.res.opt_def_id()
1565 && target_def_id == def_id
1566 {
1567 let mut last_path_res = None;
1568 'reexps: for reexp in child.reexport_chain.iter() {
1569 if let Some(use_def_id) = reexp.id()
1570 && let Some(local_use_def_id) = use_def_id.as_local()
1571 && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1572 && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1573 {
1574 for res in path.res.present_items() {
1575 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1576 continue;
1577 }
1578 if (cx.document_hidden() ||
1579 !cx.tcx.is_doc_hidden(use_def_id)) &&
1580 cx.tcx.local_visibility(local_use_def_id).is_public()
1584 {
1585 break 'reexps;
1586 }
1587 last_path_res = Some((path, res));
1588 continue 'reexps;
1589 }
1590 }
1591 }
1592 if !child.reexport_chain.is_empty() {
1593 if let Some((new_path, _)) = last_path_res {
1599 return Some(first_non_private_clean_path(
1600 cx,
1601 path,
1602 new_path.segments,
1603 new_path.span,
1604 ));
1605 }
1606 return None;
1611 }
1612 }
1613 }
1614 None
1615}
1616
1617fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1618 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1619 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1620
1621 match qpath {
1622 hir::QPath::Resolved(None, path) => {
1623 if let Res::Def(DefKind::TyParam, did) = path.res {
1624 if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1625 return new_ty;
1626 }
1627 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1628 return ImplTrait(bounds);
1629 }
1630 }
1631
1632 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1633 expanded
1634 } else {
1635 let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1637 path
1638 } else {
1639 clean_path(path, cx)
1640 };
1641 resolve_type(cx, path)
1642 }
1643 }
1644 hir::QPath::Resolved(Some(qself), p) => {
1645 let ty = lower_ty(cx.tcx, hir_ty);
1647 if !ty.has_escaping_bound_vars()
1649 && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1650 {
1651 return clean_middle_ty(normalized_value, cx, None, None);
1652 }
1653
1654 let trait_segments = &p.segments[..p.segments.len() - 1];
1655 let trait_def = cx.tcx.parent(p.res.def_id());
1656 let trait_ = self::Path {
1657 res: Res::Def(DefKind::Trait, trait_def),
1658 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1659 };
1660 register_res(cx, trait_.res);
1661 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1662 let self_type = clean_ty(qself, cx);
1663 let should_fully_qualify =
1664 should_fully_qualify_path(Some(self_def_id), &trait_, &self_type);
1665 Type::QPath(Box::new(QPathData {
1666 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1667 should_fully_qualify,
1668 self_type,
1669 trait_: Some(trait_),
1670 }))
1671 }
1672 hir::QPath::TypeRelative(qself, segment) => {
1673 let ty = lower_ty(cx.tcx, hir_ty);
1674 let self_type = clean_ty(qself, cx);
1675
1676 let (trait_, should_fully_qualify) = match ty.kind() {
1677 ty::Alias(ty::Projection, proj) => {
1678 let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1679 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1680 register_res(cx, trait_.res);
1681 let self_def_id = res.opt_def_id();
1682 let should_fully_qualify =
1683 should_fully_qualify_path(self_def_id, &trait_, &self_type);
1684
1685 (Some(trait_), should_fully_qualify)
1686 }
1687 ty::Alias(ty::Inherent, _) => (None, false),
1688 ty::Error(_) => return Type::Infer,
1690 _ => bug!("clean: expected associated type, found `{ty:?}`"),
1691 };
1692
1693 Type::QPath(Box::new(QPathData {
1694 assoc: clean_path_segment(segment, cx),
1695 should_fully_qualify,
1696 self_type,
1697 trait_,
1698 }))
1699 }
1700 }
1701}
1702
1703fn maybe_expand_private_type_alias<'tcx>(
1704 cx: &mut DocContext<'tcx>,
1705 path: &hir::Path<'tcx>,
1706) -> Option<Type> {
1707 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1708 let def_id = def_id.as_local()?;
1710 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1711 && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1712 {
1713 &cx.tcx.hir_expect_item(def_id).kind
1714 } else {
1715 return None;
1716 };
1717 let hir::ItemKind::TyAlias(_, generics, ty) = alias else { return None };
1718
1719 let final_seg = &path.segments.last().expect("segments were empty");
1720 let mut args = DefIdMap::default();
1721 let generic_args = final_seg.args();
1722
1723 let mut indices: hir::GenericParamCount = Default::default();
1724 for param in generics.params.iter() {
1725 match param.kind {
1726 hir::GenericParamKind::Lifetime { .. } => {
1727 let mut j = 0;
1728 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1729 hir::GenericArg::Lifetime(lt) => {
1730 if indices.lifetimes == j {
1731 return Some(lt);
1732 }
1733 j += 1;
1734 None
1735 }
1736 _ => None,
1737 });
1738 if let Some(lt) = lifetime {
1739 let lt = if !lt.is_anonymous() {
1740 clean_lifetime(lt, cx)
1741 } else {
1742 Lifetime::elided()
1743 };
1744 args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1745 }
1746 indices.lifetimes += 1;
1747 }
1748 hir::GenericParamKind::Type { ref default, .. } => {
1749 let mut j = 0;
1750 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1751 hir::GenericArg::Type(ty) => {
1752 if indices.types == j {
1753 return Some(ty.as_unambig_ty());
1754 }
1755 j += 1;
1756 None
1757 }
1758 _ => None,
1759 });
1760 if let Some(ty) = type_.or(*default) {
1761 args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1762 }
1763 indices.types += 1;
1764 }
1765 hir::GenericParamKind::Const { .. } => {}
1767 }
1768 }
1769
1770 Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1771 cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1772 }))
1773}
1774
1775pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1776 use rustc_hir::*;
1777
1778 match ty.kind {
1779 TyKind::Never => Primitive(PrimitiveType::Never),
1780 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1781 TyKind::Ref(l, ref m) => {
1782 let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1783 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1784 }
1785 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1786 TyKind::Pat(ty, pat) => Type::Pat(Box::new(clean_ty(ty, cx)), format!("{pat:?}").into()),
1787 TyKind::Array(ty, const_arg) => {
1788 let length = match const_arg.kind {
1796 hir::ConstArgKind::Infer(..) | hir::ConstArgKind::Error(..) => "_".to_string(),
1797 hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1798 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1799 let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1800 let ct = cx.tcx.normalize_erasing_regions(typing_env, ct);
1801 print_const(cx, ct)
1802 }
1803 hir::ConstArgKind::Path(..) => {
1804 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1805 print_const(cx, ct)
1806 }
1807 };
1808 Array(Box::new(clean_ty(ty, cx)), length.into())
1809 }
1810 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1811 TyKind::OpaqueDef(ty) => {
1812 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1813 }
1814 TyKind::Path(_) => clean_qpath(ty, cx),
1815 TyKind::TraitObject(bounds, lifetime) => {
1816 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1817 let lifetime = if !lifetime.is_elided() {
1818 Some(clean_lifetime(lifetime.pointer(), cx))
1819 } else {
1820 None
1821 };
1822 DynTrait(bounds, lifetime)
1823 }
1824 TyKind::FnPtr(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1825 TyKind::UnsafeBinder(unsafe_binder_ty) => {
1826 UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1827 }
1828 TyKind::Infer(())
1830 | TyKind::Err(_)
1831 | TyKind::InferDelegation(..)
1832 | TyKind::TraitAscription(_) => Infer,
1833 }
1834}
1835
1836fn normalize<'tcx>(
1838 cx: &DocContext<'tcx>,
1839 ty: ty::Binder<'tcx, Ty<'tcx>>,
1840) -> Option<ty::Binder<'tcx, Ty<'tcx>>> {
1841 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1843 return None;
1844 }
1845
1846 use rustc_middle::traits::ObligationCause;
1847 use rustc_trait_selection::infer::TyCtxtInferExt;
1848 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1849
1850 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1852 let normalized = infcx
1853 .at(&ObligationCause::dummy(), cx.param_env)
1854 .query_normalize(ty)
1855 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1856 match normalized {
1857 Ok(normalized_value) => {
1858 debug!("normalized {ty:?} to {normalized_value:?}");
1859 Some(normalized_value)
1860 }
1861 Err(err) => {
1862 debug!("failed to normalize {ty:?}: {err:?}");
1863 None
1864 }
1865 }
1866}
1867
1868fn clean_trait_object_lifetime_bound<'tcx>(
1869 region: ty::Region<'tcx>,
1870 container: Option<ContainerTy<'_, 'tcx>>,
1871 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1872 tcx: TyCtxt<'tcx>,
1873) -> Option<Lifetime> {
1874 if can_elide_trait_object_lifetime_bound(region, container, preds, tcx) {
1875 return None;
1876 }
1877
1878 match region.kind() {
1882 ty::ReStatic => Some(Lifetime::statik()),
1883 ty::ReEarlyParam(region) => Some(Lifetime(region.name)),
1884 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. }) => {
1885 Some(Lifetime(tcx.item_name(def_id)))
1886 }
1887 ty::ReBound(..)
1888 | ty::ReLateParam(_)
1889 | ty::ReVar(_)
1890 | ty::RePlaceholder(_)
1891 | ty::ReErased
1892 | ty::ReError(_) => None,
1893 }
1894}
1895
1896fn can_elide_trait_object_lifetime_bound<'tcx>(
1897 region: ty::Region<'tcx>,
1898 container: Option<ContainerTy<'_, 'tcx>>,
1899 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1900 tcx: TyCtxt<'tcx>,
1901) -> bool {
1902 let default = container
1907 .map_or(ObjectLifetimeDefault::Empty, |container| container.object_lifetime_default(tcx));
1908
1909 match default {
1912 ObjectLifetimeDefault::Static => return region.kind() == ty::ReStatic,
1913 ObjectLifetimeDefault::Arg(default) => {
1915 return region.get_name(tcx) == default.get_name(tcx);
1916 }
1917 ObjectLifetimeDefault::Ambiguous => return false,
1921 ObjectLifetimeDefault::Empty => {}
1923 }
1924
1925 match *object_region_bounds(tcx, preds) {
1927 [] => region.kind() == ty::ReStatic,
1935 [object_region] => object_region.get_name(tcx) == region.get_name(tcx),
1939 _ => false,
1943 }
1944}
1945
1946#[derive(Debug)]
1947pub(crate) enum ContainerTy<'a, 'tcx> {
1948 Ref(ty::Region<'tcx>),
1949 Regular {
1950 ty: DefId,
1951 args: ty::Binder<'tcx, &'a [ty::GenericArg<'tcx>]>,
1954 arg: usize,
1955 },
1956}
1957
1958impl<'tcx> ContainerTy<'_, 'tcx> {
1959 fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> {
1960 match self {
1961 Self::Ref(region) => ObjectLifetimeDefault::Arg(region),
1962 Self::Regular { ty: container, args, arg: index } => {
1963 let (DefKind::Struct
1964 | DefKind::Union
1965 | DefKind::Enum
1966 | DefKind::TyAlias
1967 | DefKind::Trait) = tcx.def_kind(container)
1968 else {
1969 return ObjectLifetimeDefault::Empty;
1970 };
1971
1972 let generics = tcx.generics_of(container);
1973 debug_assert_eq!(generics.parent_count, 0);
1974
1975 let param = generics.own_params[index].def_id;
1976 let default = tcx.object_lifetime_default(param);
1977 match default {
1978 rbv::ObjectLifetimeDefault::Param(lifetime) => {
1979 let index = generics.param_def_id_to_index[&lifetime];
1982 let arg = args.skip_binder()[index as usize].expect_region();
1983 ObjectLifetimeDefault::Arg(arg)
1984 }
1985 rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty,
1986 rbv::ObjectLifetimeDefault::Static => ObjectLifetimeDefault::Static,
1987 rbv::ObjectLifetimeDefault::Ambiguous => ObjectLifetimeDefault::Ambiguous,
1988 }
1989 }
1990 }
1991 }
1992}
1993
1994#[derive(Debug, Clone, Copy)]
1995pub(crate) enum ObjectLifetimeDefault<'tcx> {
1996 Empty,
1997 Static,
1998 Ambiguous,
1999 Arg(ty::Region<'tcx>),
2000}
2001
2002#[instrument(level = "trace", skip(cx), ret)]
2003pub(crate) fn clean_middle_ty<'tcx>(
2004 bound_ty: ty::Binder<'tcx, Ty<'tcx>>,
2005 cx: &mut DocContext<'tcx>,
2006 parent_def_id: Option<DefId>,
2007 container: Option<ContainerTy<'_, 'tcx>>,
2008) -> Type {
2009 let bound_ty = normalize(cx, bound_ty).unwrap_or(bound_ty);
2010 match *bound_ty.skip_binder().kind() {
2011 ty::Never => Primitive(PrimitiveType::Never),
2012 ty::Bool => Primitive(PrimitiveType::Bool),
2013 ty::Char => Primitive(PrimitiveType::Char),
2014 ty::Int(int_ty) => Primitive(int_ty.into()),
2015 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
2016 ty::Float(float_ty) => Primitive(float_ty.into()),
2017 ty::Str => Primitive(PrimitiveType::Str),
2018 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None))),
2019 ty::Pat(ty, pat) => Type::Pat(
2020 Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)),
2021 format!("{pat:?}").into_boxed_str(),
2022 ),
2023 ty::Array(ty, n) => {
2024 let n = cx.tcx.normalize_erasing_regions(cx.typing_env(), n);
2025 let n = print_const(cx, n);
2026 Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into())
2027 }
2028 ty::RawPtr(ty, mutbl) => {
2029 RawPointer(mutbl, Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)))
2030 }
2031 ty::Ref(r, ty, mutbl) => BorrowedRef {
2032 lifetime: clean_middle_region(r, cx),
2033 mutability: mutbl,
2034 type_: Box::new(clean_middle_ty(
2035 bound_ty.rebind(ty),
2036 cx,
2037 None,
2038 Some(ContainerTy::Ref(r)),
2039 )),
2040 },
2041 ty::FnDef(..) | ty::FnPtr(..) => {
2042 let sig = bound_ty.skip_binder().fn_sig(cx.tcx);
2044 let decl = clean_poly_fn_sig(cx, None, sig);
2045 let generic_params = clean_bound_vars(sig.bound_vars(), cx);
2046
2047 BareFunction(Box::new(BareFunctionDecl {
2048 safety: sig.safety(),
2049 generic_params,
2050 decl,
2051 abi: sig.abi(),
2052 }))
2053 }
2054 ty::UnsafeBinder(inner) => {
2055 let generic_params = clean_bound_vars(inner.bound_vars(), cx);
2056 let ty = clean_middle_ty(inner.into(), cx, None, None);
2057 UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, ty }))
2058 }
2059 ty::Adt(def, args) => {
2060 let did = def.did();
2061 let kind = match def.adt_kind() {
2062 AdtKind::Struct => ItemType::Struct,
2063 AdtKind::Union => ItemType::Union,
2064 AdtKind::Enum => ItemType::Enum,
2065 };
2066 inline::record_extern_fqn(cx, did, kind);
2067 let path = clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args));
2068 Type::Path { path }
2069 }
2070 ty::Foreign(did) => {
2071 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
2072 let path = clean_middle_path(
2073 cx,
2074 did,
2075 false,
2076 ThinVec::new(),
2077 ty::Binder::dummy(ty::GenericArgs::empty()),
2078 );
2079 Type::Path { path }
2080 }
2081 ty::Dynamic(obj, reg) => {
2082 let mut dids = obj.auto_traits();
2086 let did = obj
2087 .principal_def_id()
2088 .or_else(|| dids.next())
2089 .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?"));
2090 let args = match obj.principal() {
2091 Some(principal) => principal.map_bound(|p| p.args),
2092 _ => ty::Binder::dummy(ty::GenericArgs::empty()),
2094 };
2095
2096 inline::record_extern_fqn(cx, did, ItemType::Trait);
2097
2098 let lifetime = clean_trait_object_lifetime_bound(reg, container, obj, cx.tcx);
2099
2100 let mut bounds = dids
2101 .map(|did| {
2102 let empty = ty::Binder::dummy(ty::GenericArgs::empty());
2103 let path = clean_middle_path(cx, did, false, ThinVec::new(), empty);
2104 inline::record_extern_fqn(cx, did, ItemType::Trait);
2105 PolyTrait { trait_: path, generic_params: Vec::new() }
2106 })
2107 .collect::<Vec<_>>();
2108
2109 let constraints = obj
2110 .projection_bounds()
2111 .map(|pb| AssocItemConstraint {
2112 assoc: projection_to_path_segment(
2113 pb.map_bound(|pb| {
2114 pb.with_self_ty(cx.tcx, cx.tcx.types.trait_object_dummy_self)
2115 .projection_term
2116 }),
2117 cx,
2118 ),
2119 kind: AssocItemConstraintKind::Equality {
2120 term: clean_middle_term(pb.map_bound(|pb| pb.term), cx),
2121 },
2122 })
2123 .collect();
2124
2125 let late_bound_regions: FxIndexSet<_> = obj
2126 .iter()
2127 .flat_map(|pred| pred.bound_vars())
2128 .filter_map(|var| match var {
2129 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
2130 let name = cx.tcx.item_name(def_id);
2131 if name != kw::UnderscoreLifetime {
2132 Some(GenericParamDef::lifetime(def_id, name))
2133 } else {
2134 None
2135 }
2136 }
2137 _ => None,
2138 })
2139 .collect();
2140 let late_bound_regions = late_bound_regions.into_iter().collect();
2141
2142 let path = clean_middle_path(cx, did, false, constraints, args);
2143 bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
2144
2145 DynTrait(bounds, lifetime)
2146 }
2147 ty::Tuple(t) => {
2148 Tuple(t.iter().map(|t| clean_middle_ty(bound_ty.rebind(t), cx, None, None)).collect())
2149 }
2150
2151 ty::Alias(ty::Projection, alias_ty @ ty::AliasTy { def_id, args, .. }) => {
2152 if cx.tcx.is_impl_trait_in_trait(def_id) {
2153 clean_middle_opaque_bounds(cx, def_id, args)
2154 } else {
2155 Type::QPath(Box::new(clean_projection(
2156 bound_ty.rebind(alias_ty.into()),
2157 cx,
2158 parent_def_id,
2159 )))
2160 }
2161 }
2162
2163 ty::Alias(ty::Inherent, alias_ty @ ty::AliasTy { def_id, .. }) => {
2164 let alias_ty = bound_ty.rebind(alias_ty);
2165 let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None, None);
2166
2167 Type::QPath(Box::new(QPathData {
2168 assoc: PathSegment {
2169 name: cx.tcx.item_name(def_id),
2170 args: GenericArgs::AngleBracketed {
2171 args: clean_middle_generic_args(
2172 cx,
2173 alias_ty.map_bound(|ty| ty.args.as_slice()),
2174 true,
2175 def_id,
2176 ),
2177 constraints: Default::default(),
2178 },
2179 },
2180 should_fully_qualify: false,
2181 self_type,
2182 trait_: None,
2183 }))
2184 }
2185
2186 ty::Alias(ty::Free, ty::AliasTy { def_id, args, .. }) => {
2187 if cx.tcx.features().lazy_type_alias() {
2188 let path =
2191 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2192 Type::Path { path }
2193 } else {
2194 let ty = cx.tcx.type_of(def_id).instantiate(cx.tcx, args);
2195 clean_middle_ty(bound_ty.rebind(ty), cx, None, None)
2196 }
2197 }
2198
2199 ty::Param(ref p) => {
2200 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
2201 ImplTrait(bounds)
2202 } else if p.name == kw::SelfUpper {
2203 SelfTy
2204 } else {
2205 Generic(p.name)
2206 }
2207 }
2208
2209 ty::Bound(_, ref ty) => match ty.kind {
2210 ty::BoundTyKind::Param(def_id) => Generic(cx.tcx.item_name(def_id)),
2211 ty::BoundTyKind::Anon => panic!("unexpected anonymous bound type variable"),
2212 },
2213
2214 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2215 if cx.current_type_aliases.contains_key(&def_id) {
2217 let path =
2218 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2219 Type::Path { path }
2220 } else {
2221 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2222 let ty = clean_middle_opaque_bounds(cx, def_id, args);
2225 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2226 *count -= 1;
2227 if *count == 0 {
2228 cx.current_type_aliases.remove(&def_id);
2229 }
2230 }
2231 ty
2232 }
2233 }
2234
2235 ty::Closure(..) => panic!("Closure"),
2236 ty::CoroutineClosure(..) => panic!("CoroutineClosure"),
2237 ty::Coroutine(..) => panic!("Coroutine"),
2238 ty::Placeholder(..) => panic!("Placeholder"),
2239 ty::CoroutineWitness(..) => panic!("CoroutineWitness"),
2240 ty::Infer(..) => panic!("Infer"),
2241
2242 ty::Error(_) => FatalError.raise(),
2243 }
2244}
2245
2246fn clean_middle_opaque_bounds<'tcx>(
2247 cx: &mut DocContext<'tcx>,
2248 impl_trait_def_id: DefId,
2249 args: ty::GenericArgsRef<'tcx>,
2250) -> Type {
2251 let mut has_sized = false;
2252
2253 let bounds: Vec<_> = cx
2254 .tcx
2255 .explicit_item_bounds(impl_trait_def_id)
2256 .iter_instantiated_copied(cx.tcx, args)
2257 .collect();
2258
2259 let mut bounds = bounds
2260 .iter()
2261 .filter_map(|(bound, _)| {
2262 let bound_predicate = bound.kind();
2263 let trait_ref = match bound_predicate.skip_binder() {
2264 ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
2265 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
2266 return clean_middle_region(reg, cx).map(GenericBound::Outlives);
2267 }
2268 _ => return None,
2269 };
2270
2271 if cx.tcx.is_lang_item(trait_ref.def_id(), LangItem::MetaSized) {
2274 return None;
2275 }
2276
2277 if let Some(sized) = cx.tcx.lang_items().sized_trait()
2278 && trait_ref.def_id() == sized
2279 {
2280 has_sized = true;
2281 return None;
2282 }
2283
2284 let bindings: ThinVec<_> = bounds
2285 .iter()
2286 .filter_map(|(bound, _)| {
2287 let bound = bound.kind();
2288 if let ty::ClauseKind::Projection(proj_pred) = bound.skip_binder()
2289 && proj_pred.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
2290 {
2291 return Some(AssocItemConstraint {
2292 assoc: projection_to_path_segment(
2293 bound.rebind(proj_pred.projection_term),
2294 cx,
2295 ),
2296 kind: AssocItemConstraintKind::Equality {
2297 term: clean_middle_term(bound.rebind(proj_pred.term), cx),
2298 },
2299 });
2300 }
2301 None
2302 })
2303 .collect();
2304
2305 Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings))
2306 })
2307 .collect::<Vec<_>>();
2308
2309 if !has_sized {
2310 bounds.push(GenericBound::maybe_sized(cx));
2311 }
2312
2313 bounds.sort_by_key(|b| !b.is_trait_bound());
2315
2316 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
2319 bounds.insert(0, GenericBound::sized(cx));
2320 }
2321
2322 if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) {
2323 bounds.push(GenericBound::Use(
2324 args.iter()
2325 .map(|arg| match arg {
2326 hir::PreciseCapturingArgKind::Lifetime(lt) => {
2327 PreciseCapturingArg::Lifetime(Lifetime(*lt))
2328 }
2329 hir::PreciseCapturingArgKind::Param(param) => {
2330 PreciseCapturingArg::Param(*param)
2331 }
2332 })
2333 .collect(),
2334 ));
2335 }
2336
2337 ImplTrait(bounds)
2338}
2339
2340pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2341 clean_field_with_def_id(field.def_id.to_def_id(), field.ident.name, clean_ty(field.ty, cx), cx)
2342}
2343
2344pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item {
2345 clean_field_with_def_id(
2346 field.did,
2347 field.name,
2348 clean_middle_ty(
2349 ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity()),
2350 cx,
2351 Some(field.did),
2352 None,
2353 ),
2354 cx,
2355 )
2356}
2357
2358pub(crate) fn clean_field_with_def_id(
2359 def_id: DefId,
2360 name: Symbol,
2361 ty: Type,
2362 cx: &mut DocContext<'_>,
2363) -> Item {
2364 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
2365}
2366
2367pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item {
2368 let discriminant = match variant.discr {
2369 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2370 ty::VariantDiscr::Relative(_) => None,
2371 };
2372
2373 let kind = match variant.ctor_kind() {
2374 Some(CtorKind::Const) => VariantKind::CLike,
2375 Some(CtorKind::Fn) => VariantKind::Tuple(
2376 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2377 ),
2378 None => VariantKind::Struct(VariantStruct {
2379 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2380 }),
2381 };
2382
2383 Item::from_def_id_and_parts(
2384 variant.def_id,
2385 Some(variant.name),
2386 VariantItem(Variant { kind, discriminant }),
2387 cx,
2388 )
2389}
2390
2391pub(crate) fn clean_variant_def_with_args<'tcx>(
2392 variant: &ty::VariantDef,
2393 args: &GenericArgsRef<'tcx>,
2394 cx: &mut DocContext<'tcx>,
2395) -> Item {
2396 let discriminant = match variant.discr {
2397 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2398 ty::VariantDiscr::Relative(_) => None,
2399 };
2400
2401 use rustc_middle::traits::ObligationCause;
2402 use rustc_trait_selection::infer::TyCtxtInferExt;
2403 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
2404
2405 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2406 let kind = match variant.ctor_kind() {
2407 Some(CtorKind::Const) => VariantKind::CLike,
2408 Some(CtorKind::Fn) => VariantKind::Tuple(
2409 variant
2410 .fields
2411 .iter()
2412 .map(|field| {
2413 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2414
2415 let ty = infcx
2419 .at(&ObligationCause::dummy(), cx.param_env)
2420 .query_normalize(ty)
2421 .map(|normalized| normalized.value)
2422 .unwrap_or(ty);
2423
2424 clean_field_with_def_id(
2425 field.did,
2426 field.name,
2427 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2428 cx,
2429 )
2430 })
2431 .collect(),
2432 ),
2433 None => VariantKind::Struct(VariantStruct {
2434 fields: variant
2435 .fields
2436 .iter()
2437 .map(|field| {
2438 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2439
2440 let ty = infcx
2444 .at(&ObligationCause::dummy(), cx.param_env)
2445 .query_normalize(ty)
2446 .map(|normalized| normalized.value)
2447 .unwrap_or(ty);
2448
2449 clean_field_with_def_id(
2450 field.did,
2451 field.name,
2452 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2453 cx,
2454 )
2455 })
2456 .collect(),
2457 }),
2458 };
2459
2460 Item::from_def_id_and_parts(
2461 variant.def_id,
2462 Some(variant.name),
2463 VariantItem(Variant { kind, discriminant }),
2464 cx,
2465 )
2466}
2467
2468fn clean_variant_data<'tcx>(
2469 variant: &hir::VariantData<'tcx>,
2470 disr_expr: &Option<&hir::AnonConst>,
2471 cx: &mut DocContext<'tcx>,
2472) -> Variant {
2473 let discriminant = disr_expr
2474 .map(|disr| Discriminant { expr: Some(disr.body), value: disr.def_id.to_def_id() });
2475
2476 let kind = match variant {
2477 hir::VariantData::Struct { fields, .. } => VariantKind::Struct(VariantStruct {
2478 fields: fields.iter().map(|x| clean_field(x, cx)).collect(),
2479 }),
2480 hir::VariantData::Tuple(..) => {
2481 VariantKind::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
2482 }
2483 hir::VariantData::Unit(..) => VariantKind::CLike,
2484 };
2485
2486 Variant { discriminant, kind }
2487}
2488
2489fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
2490 Path {
2491 res: path.res,
2492 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
2493 }
2494}
2495
2496fn clean_generic_args<'tcx>(
2497 generic_args: &hir::GenericArgs<'tcx>,
2498 cx: &mut DocContext<'tcx>,
2499) -> GenericArgs {
2500 match generic_args.parenthesized {
2501 hir::GenericArgsParentheses::No => {
2502 let args = generic_args
2503 .args
2504 .iter()
2505 .map(|arg| match arg {
2506 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
2507 GenericArg::Lifetime(clean_lifetime(lt, cx))
2508 }
2509 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2510 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)),
2511 hir::GenericArg::Const(ct) => {
2512 GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct())))
2513 }
2514 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
2515 })
2516 .collect();
2517 let constraints = generic_args
2518 .constraints
2519 .iter()
2520 .map(|c| clean_assoc_item_constraint(c, cx))
2521 .collect::<ThinVec<_>>();
2522 GenericArgs::AngleBracketed { args, constraints }
2523 }
2524 hir::GenericArgsParentheses::ParenSugar => {
2525 let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else {
2526 bug!();
2527 };
2528 let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect();
2529 let output = match output.kind {
2530 hir::TyKind::Tup(&[]) => None,
2531 _ => Some(Box::new(clean_ty(output, cx))),
2532 };
2533 GenericArgs::Parenthesized { inputs, output }
2534 }
2535 hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
2536 }
2537}
2538
2539fn clean_path_segment<'tcx>(
2540 path: &hir::PathSegment<'tcx>,
2541 cx: &mut DocContext<'tcx>,
2542) -> PathSegment {
2543 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
2544}
2545
2546fn clean_bare_fn_ty<'tcx>(
2547 bare_fn: &hir::FnPtrTy<'tcx>,
2548 cx: &mut DocContext<'tcx>,
2549) -> BareFunctionDecl {
2550 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
2551 let generic_params = bare_fn
2553 .generic_params
2554 .iter()
2555 .filter(|p| !is_elided_lifetime(p))
2556 .map(|x| clean_generic_param(cx, None, x))
2557 .collect();
2558 let filter = |ident: Option<Ident>| {
2562 ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore)
2563 };
2564 let fallback =
2565 bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore);
2566 let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents, |ident| {
2567 filter(ident).or(fallback)
2568 });
2569 let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params);
2570 (generic_params, decl)
2571 });
2572 BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params }
2573}
2574
2575fn clean_unsafe_binder_ty<'tcx>(
2576 unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>,
2577 cx: &mut DocContext<'tcx>,
2578) -> UnsafeBinderTy {
2579 let generic_params = unsafe_binder_ty
2580 .generic_params
2581 .iter()
2582 .filter(|p| !is_elided_lifetime(p))
2583 .map(|x| clean_generic_param(cx, None, x))
2584 .collect();
2585 let ty = clean_ty(unsafe_binder_ty.inner_ty, cx);
2586 UnsafeBinderTy { generic_params, ty }
2587}
2588
2589pub(crate) fn reexport_chain(
2590 tcx: TyCtxt<'_>,
2591 import_def_id: LocalDefId,
2592 target_def_id: DefId,
2593) -> &[Reexport] {
2594 for child in tcx.module_children_local(tcx.local_parent(import_def_id)) {
2595 if child.res.opt_def_id() == Some(target_def_id)
2596 && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id())
2597 {
2598 return &child.reexport_chain;
2599 }
2600 }
2601 &[]
2602}
2603
2604fn get_all_import_attributes<'hir>(
2606 cx: &mut DocContext<'hir>,
2607 import_def_id: LocalDefId,
2608 target_def_id: DefId,
2609 is_inline: bool,
2610) -> Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)> {
2611 let mut attrs = Vec::new();
2612 let mut first = true;
2613 for def_id in reexport_chain(cx.tcx, import_def_id, target_def_id)
2614 .iter()
2615 .flat_map(|reexport| reexport.id())
2616 {
2617 let import_attrs = inline::load_attrs(cx, def_id);
2618 if first {
2619 attrs = import_attrs.iter().map(|attr| (Cow::Borrowed(attr), Some(def_id))).collect();
2621 first = false;
2622 } else if cx.document_hidden() || !cx.tcx.is_doc_hidden(def_id) {
2624 add_without_unwanted_attributes(&mut attrs, import_attrs, is_inline, Some(def_id));
2625 }
2626 }
2627 attrs
2628}
2629
2630fn add_without_unwanted_attributes<'hir>(
2651 attrs: &mut Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)>,
2652 new_attrs: &'hir [hir::Attribute],
2653 is_inline: bool,
2654 import_parent: Option<DefId>,
2655) {
2656 for attr in new_attrs {
2657 match attr {
2658 hir::Attribute::Parsed(AttributeKind::DocComment { .. }) => {
2659 attrs.push((Cow::Borrowed(attr), import_parent));
2660 }
2661 hir::Attribute::Parsed(AttributeKind::Doc(box d)) => {
2662 let DocAttribute { hidden, inline, cfg, .. } = d;
2664 let mut attr = DocAttribute::default();
2665 if is_inline {
2666 attr.cfg = cfg.clone();
2667 } else {
2668 attr.inline = inline.clone();
2669 attr.hidden = hidden.clone();
2670 }
2671 attrs.push((
2672 Cow::Owned(hir::Attribute::Parsed(AttributeKind::Doc(Box::new(attr)))),
2673 import_parent,
2674 ));
2675 }
2676 hir::Attribute::Unparsed(normal) if let [ident] = &*normal.path.segments => {
2677 if is_inline || ident.name != sym::cfg_trace {
2678 attrs.push((Cow::Borrowed(attr), import_parent));
2680 }
2681 }
2682 hir::Attribute::Parsed(..) => {
2684 attrs.push((Cow::Borrowed(attr), import_parent));
2685 }
2686 _ => {}
2687 }
2688 }
2689}
2690
2691fn clean_maybe_renamed_item<'tcx>(
2692 cx: &mut DocContext<'tcx>,
2693 item: &hir::Item<'tcx>,
2694 renamed: Option<Symbol>,
2695 import_ids: &[LocalDefId],
2696) -> Vec<Item> {
2697 use hir::ItemKind;
2698 fn get_name(
2699 cx: &DocContext<'_>,
2700 item: &hir::Item<'_>,
2701 renamed: Option<Symbol>,
2702 ) -> Option<Symbol> {
2703 renamed.or_else(|| cx.tcx.hir_opt_name(item.hir_id()))
2704 }
2705
2706 let def_id = item.owner_id.to_def_id();
2707 cx.with_param_env(def_id, |cx| {
2708 match item.kind {
2711 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.owner_id.def_id, cx),
2712 ItemKind::Use(path, kind) => {
2713 return clean_use_statement(
2714 item,
2715 get_name(cx, item, renamed),
2716 path,
2717 kind,
2718 cx,
2719 &mut FxHashSet::default(),
2720 );
2721 }
2722 _ => {}
2723 }
2724
2725 let mut name = get_name(cx, item, renamed).unwrap();
2726
2727 let kind = match item.kind {
2728 ItemKind::Static(mutability, _, ty, body_id) => StaticItem(Static {
2729 type_: Box::new(clean_ty(ty, cx)),
2730 mutability,
2731 expr: Some(body_id),
2732 }),
2733 ItemKind::Const(_, generics, ty, rhs) => ConstantItem(Box::new(Constant {
2734 generics: clean_generics(generics, cx),
2735 type_: clean_ty(ty, cx),
2736 kind: clean_const_item_rhs(rhs, def_id),
2737 })),
2738 ItemKind::TyAlias(_, generics, ty) => {
2739 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2740 let rustdoc_ty = clean_ty(ty, cx);
2741 let type_ =
2742 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, ty)), cx, None, None);
2743 let generics = clean_generics(generics, cx);
2744 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2745 *count -= 1;
2746 if *count == 0 {
2747 cx.current_type_aliases.remove(&def_id);
2748 }
2749 }
2750
2751 let ty = cx.tcx.type_of(def_id).instantiate_identity();
2752
2753 let mut ret = Vec::new();
2754 let inner_type = clean_ty_alias_inner_type(ty, cx, &mut ret);
2755
2756 ret.push(generate_item_with_correct_attrs(
2757 cx,
2758 TypeAliasItem(Box::new(TypeAlias {
2759 generics,
2760 inner_type,
2761 type_: rustdoc_ty,
2762 item_type: Some(type_),
2763 })),
2764 item.owner_id.def_id.to_def_id(),
2765 name,
2766 import_ids,
2767 renamed,
2768 ));
2769 return ret;
2770 }
2771 ItemKind::Enum(_, generics, def) => EnumItem(Enum {
2772 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2773 generics: clean_generics(generics, cx),
2774 }),
2775 ItemKind::TraitAlias(_, _, generics, bounds) => TraitAliasItem(TraitAlias {
2776 generics: clean_generics(generics, cx),
2777 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2778 }),
2779 ItemKind::Union(_, generics, variant_data) => UnionItem(Union {
2780 generics: clean_generics(generics, cx),
2781 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2782 }),
2783 ItemKind::Struct(_, generics, variant_data) => StructItem(Struct {
2784 ctor_kind: variant_data.ctor_kind(),
2785 generics: clean_generics(generics, cx),
2786 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2787 }),
2788 ItemKind::Macro(_, macro_def, MacroKinds::BANG) => MacroItem(Macro {
2791 source: display_macro_source(cx, name, macro_def),
2792 macro_rules: macro_def.macro_rules,
2793 }),
2794 ItemKind::Macro(_, _, MacroKinds::ATTR) => {
2795 clean_proc_macro(item, &mut name, MacroKind::Attr, cx)
2796 }
2797 ItemKind::Macro(_, _, MacroKinds::DERIVE) => {
2798 clean_proc_macro(item, &mut name, MacroKind::Derive, cx)
2799 }
2800 ItemKind::Macro(_, _, _) => todo!("Handle macros with multiple kinds"),
2801 ItemKind::Fn { ref sig, generics, body: body_id, .. } => {
2803 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2804 }
2805 ItemKind::Trait(_, _, _, _, generics, bounds, item_ids) => {
2806 let items = item_ids
2807 .iter()
2808 .map(|&ti| clean_trait_item(cx.tcx.hir_trait_item(ti), cx))
2809 .collect();
2810
2811 TraitItem(Box::new(Trait {
2812 def_id,
2813 items,
2814 generics: clean_generics(generics, cx),
2815 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2816 }))
2817 }
2818 ItemKind::ExternCrate(orig_name, _) => {
2819 return clean_extern_crate(item, name, orig_name, cx);
2820 }
2821 _ => span_bug!(item.span, "not yet converted"),
2822 };
2823
2824 vec![generate_item_with_correct_attrs(
2825 cx,
2826 kind,
2827 item.owner_id.def_id.to_def_id(),
2828 name,
2829 import_ids,
2830 renamed,
2831 )]
2832 })
2833}
2834
2835fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2836 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2837 Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx)
2838}
2839
2840fn clean_impl<'tcx>(
2841 impl_: &hir::Impl<'tcx>,
2842 def_id: LocalDefId,
2843 cx: &mut DocContext<'tcx>,
2844) -> Vec<Item> {
2845 let tcx = cx.tcx;
2846 let mut ret = Vec::new();
2847 let trait_ = impl_.of_trait.map(|t| clean_trait_ref(&t.trait_ref, cx));
2848 let items = impl_
2849 .items
2850 .iter()
2851 .map(|&ii| clean_impl_item(tcx.hir_impl_item(ii), cx))
2852 .collect::<Vec<_>>();
2853
2854 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2857 build_deref_target_impls(cx, &items, &mut ret);
2858 }
2859
2860 let for_ = clean_ty(impl_.self_ty, cx);
2861 let type_alias =
2862 for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) {
2863 DefKind::TyAlias => Some(clean_middle_ty(
2864 ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()),
2865 cx,
2866 Some(def_id.to_def_id()),
2867 None,
2868 )),
2869 _ => None,
2870 });
2871 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2872 let kind = ImplItem(Box::new(Impl {
2873 safety: match impl_.of_trait {
2874 Some(of_trait) => of_trait.safety,
2875 None => hir::Safety::Safe,
2876 },
2877 generics: clean_generics(impl_.generics, cx),
2878 trait_,
2879 for_,
2880 items,
2881 polarity: if impl_.of_trait.is_some() {
2882 tcx.impl_polarity(def_id)
2883 } else {
2884 ty::ImplPolarity::Positive
2885 },
2886 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), |d| d.fake_variadic.is_some()) {
2887 ImplKind::FakeVariadic
2888 } else {
2889 ImplKind::Normal
2890 },
2891 }));
2892 Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, cx)
2893 };
2894 if let Some(type_alias) = type_alias {
2895 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2896 }
2897 ret.push(make_item(trait_, for_, items));
2898 ret
2899}
2900
2901fn clean_extern_crate<'tcx>(
2902 krate: &hir::Item<'tcx>,
2903 name: Symbol,
2904 orig_name: Option<Symbol>,
2905 cx: &mut DocContext<'tcx>,
2906) -> Vec<Item> {
2907 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2909 let crate_def_id = cnum.as_def_id();
2911 let attrs = cx.tcx.hir_attrs(krate.hir_id());
2912 let ty_vis = cx.tcx.visibility(krate.owner_id);
2913 let please_inline = ty_vis.is_public()
2914 && attrs.iter().any(|a| {
2915 matches!(
2916 a,
2917 hir::Attribute::Parsed(AttributeKind::Doc(d))
2918 if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline))
2919 })
2920 && !cx.is_json_output();
2921
2922 let krate_owner_def_id = krate.owner_id.def_id;
2923
2924 if please_inline
2925 && let Some(items) = inline::try_inline(
2926 cx,
2927 Res::Def(DefKind::Mod, crate_def_id),
2928 name,
2929 Some((attrs, Some(krate_owner_def_id))),
2930 &mut Default::default(),
2931 )
2932 {
2933 return items;
2934 }
2935
2936 vec![Item::from_def_id_and_parts(
2937 krate_owner_def_id.to_def_id(),
2938 Some(name),
2939 ExternCrateItem { src: orig_name },
2940 cx,
2941 )]
2942}
2943
2944fn clean_use_statement<'tcx>(
2945 import: &hir::Item<'tcx>,
2946 name: Option<Symbol>,
2947 path: &hir::UsePath<'tcx>,
2948 kind: hir::UseKind,
2949 cx: &mut DocContext<'tcx>,
2950 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2951) -> Vec<Item> {
2952 let mut items = Vec::new();
2953 let hir::UsePath { segments, ref res, span } = *path;
2954 for res in res.present_items() {
2955 let path = hir::Path { segments, res, span };
2956 items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
2957 }
2958 items
2959}
2960
2961fn clean_use_statement_inner<'tcx>(
2962 import: &hir::Item<'tcx>,
2963 name: Option<Symbol>,
2964 path: &hir::Path<'tcx>,
2965 kind: hir::UseKind,
2966 cx: &mut DocContext<'tcx>,
2967 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2968) -> Vec<Item> {
2969 if should_ignore_res(path.res) {
2970 return Vec::new();
2971 }
2972 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2976 return Vec::new();
2977 }
2978
2979 let visibility = cx.tcx.visibility(import.owner_id);
2980 let attrs = cx.tcx.hir_attrs(import.hir_id());
2981 let inline_attr = find_attr!(
2982 attrs,
2983 AttributeKind::Doc(d) if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline) => d
2984 )
2985 .and_then(|d| d.inline.first());
2986 let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
2987 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
2988 let import_def_id = import.owner_id.def_id;
2989
2990 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
2994
2995 let is_visible_from_parent_mod =
3001 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3002
3003 if pub_underscore && let Some((_, inline_span)) = inline_attr {
3004 struct_span_code_err!(
3005 cx.tcx.dcx(),
3006 *inline_span,
3007 E0780,
3008 "anonymous imports cannot be inlined"
3009 )
3010 .with_span_label(import.span, "anonymous import")
3011 .emit();
3012 }
3013
3014 let mut denied = cx.is_json_output()
3019 || !(visibility.is_public() || (cx.document_private() && is_visible_from_parent_mod))
3020 || pub_underscore
3021 || attrs.iter().any(|a| matches!(
3022 a,
3023 hir::Attribute::Parsed(AttributeKind::Doc(d))
3024 if d.hidden.is_some() || d.inline.first().is_some_and(|(i, _)| *i == DocInline::NoInline)
3025 ));
3026
3027 let path = clean_path(path, cx);
3030 let inner = if kind == hir::UseKind::Glob {
3031 if !denied {
3032 let mut visited = DefIdSet::default();
3033 if let Some(items) = inline::try_inline_glob(
3034 cx,
3035 path.res,
3036 current_mod,
3037 &mut visited,
3038 inlined_names,
3039 import,
3040 ) {
3041 return items;
3042 }
3043 }
3044 Import::new_glob(resolve_use_source(cx, path), true)
3045 } else {
3046 let name = name.unwrap();
3047 if inline_attr.is_none()
3048 && let Res::Def(DefKind::Mod, did) = path.res
3049 && !did.is_local()
3050 && did.is_crate_root()
3051 {
3052 denied = true;
3055 }
3056 if !denied
3057 && let Some(mut items) = inline::try_inline(
3058 cx,
3059 path.res,
3060 name,
3061 Some((attrs, Some(import_def_id))),
3062 &mut Default::default(),
3063 )
3064 {
3065 items.push(Item::from_def_id_and_parts(
3066 import_def_id.to_def_id(),
3067 None,
3068 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3069 cx,
3070 ));
3071 return items;
3072 }
3073 Import::new_simple(name, resolve_use_source(cx, path), true)
3074 };
3075
3076 vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx)]
3077}
3078
3079fn clean_maybe_renamed_foreign_item<'tcx>(
3080 cx: &mut DocContext<'tcx>,
3081 item: &hir::ForeignItem<'tcx>,
3082 renamed: Option<Symbol>,
3083 import_id: Option<LocalDefId>,
3084) -> Item {
3085 let def_id = item.owner_id.to_def_id();
3086 cx.with_param_env(def_id, |cx| {
3087 let kind = match item.kind {
3088 hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3089 clean_function(cx, &sig, generics, ParamsSrc::Idents(idents)),
3090 sig.header.safety(),
3091 ),
3092 hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3093 Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3094 safety,
3095 ),
3096 hir::ForeignItemKind::Type => ForeignTypeItem,
3097 };
3098
3099 generate_item_with_correct_attrs(
3100 cx,
3101 kind,
3102 item.owner_id.def_id.to_def_id(),
3103 item.ident.name,
3104 import_id.as_slice(),
3105 renamed,
3106 )
3107 })
3108}
3109
3110fn clean_assoc_item_constraint<'tcx>(
3111 constraint: &hir::AssocItemConstraint<'tcx>,
3112 cx: &mut DocContext<'tcx>,
3113) -> AssocItemConstraint {
3114 AssocItemConstraint {
3115 assoc: PathSegment {
3116 name: constraint.ident.name,
3117 args: clean_generic_args(constraint.gen_args, cx),
3118 },
3119 kind: match constraint.kind {
3120 hir::AssocItemConstraintKind::Equality { ref term } => {
3121 AssocItemConstraintKind::Equality { term: clean_hir_term(term, cx) }
3122 }
3123 hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3124 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3125 },
3126 },
3127 }
3128}
3129
3130fn clean_bound_vars<'tcx>(
3131 bound_vars: &ty::List<ty::BoundVariableKind>,
3132 cx: &mut DocContext<'tcx>,
3133) -> Vec<GenericParamDef> {
3134 bound_vars
3135 .into_iter()
3136 .filter_map(|var| match var {
3137 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
3138 let name = cx.tcx.item_name(def_id);
3139 if name != kw::UnderscoreLifetime {
3140 Some(GenericParamDef::lifetime(def_id, name))
3141 } else {
3142 None
3143 }
3144 }
3145 ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
3146 let name = cx.tcx.item_name(def_id);
3147 Some(GenericParamDef {
3148 name,
3149 def_id,
3150 kind: GenericParamDefKind::Type {
3151 bounds: ThinVec::new(),
3152 default: None,
3153 synthetic: false,
3154 },
3155 })
3156 }
3157 ty::BoundVariableKind::Const => None,
3159 _ => None,
3160 })
3161 .collect()
3162}