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