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