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_clause<'tcx>(
429 clause: ty::Clause<'tcx>,
430 cx: &mut DocContext<'tcx>,
431) -> Option<WherePredicate> {
432 let bound_clause = clause.kind();
433 match bound_clause.skip_binder() {
434 ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_clause.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_clause.rebind(pred), cx))
438 }
439 ty::ClauseKind::Projection(pred) => {
440 Some(clean_projection_predicate(bound_clause.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_clauses_of(def_id))
859}
860
861fn clean_ty_generics_inner<'tcx>(
862 cx: &mut DocContext<'tcx>,
863 gens: &ty::Generics,
864 gen_clauses: ty::GenericClauses<'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_clauses = gen_clauses
896 .clauses
897 .iter()
898 .flat_map(|(clause, _)| {
899 let mut proj_pred = None;
900 let param_idx = {
901 let bound_c = clause.kind();
902 match bound_c.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_c.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 clause = clean_clause(*clause, cx)?;
925
926 bounds.extend(clause.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(clause)
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 = where_clauses.into_iter().flat_map(|c| clean_clause(*c, cx)).collect();
984
985 let mut generics = Generics { params, where_predicates };
986 simplify::sizedness_bounds(cx, &mut generics);
987 generics.where_predicates = simplify::where_clauses(cx.tcx, generics.where_predicates);
988 generics
989}
990
991fn clean_ty_alias_inner_type<'tcx>(
992 ty: Ty<'tcx>,
993 cx: &mut DocContext<'tcx>,
994 ret: &mut Vec<Item>,
995) -> Option<TypeAliasInnerType> {
996 let ty::Adt(adt_def, args) = ty.kind() else {
997 return None;
998 };
999
1000 if !adt_def.did().is_local() {
1001 cx.with_param_env(adt_def.did(), |cx| {
1002 inline::build_impls(cx, adt_def.did(), None, ret);
1003 });
1004 }
1005
1006 Some(if adt_def.is_enum() {
1007 let variants: rustc_index::IndexVec<_, _> = adt_def
1008 .variants()
1009 .iter()
1010 .map(|variant| clean_variant_def_with_args(variant, args, cx))
1011 .collect();
1012
1013 if !adt_def.did().is_local() {
1014 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Enum);
1015 }
1016
1017 TypeAliasInnerType::Enum {
1018 variants,
1019 is_non_exhaustive: adt_def.is_variant_list_non_exhaustive(),
1020 }
1021 } else {
1022 let variant = adt_def
1023 .variants()
1024 .iter()
1025 .next()
1026 .unwrap_or_else(|| bug!("a struct or union should always have one variant def"));
1027
1028 let fields: Vec<_> =
1029 clean_variant_def_with_args(variant, args, cx).kind.inner_items().cloned().collect();
1030
1031 if adt_def.is_struct() {
1032 if !adt_def.did().is_local() {
1033 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Struct);
1034 }
1035 TypeAliasInnerType::Struct { ctor_kind: variant.ctor_kind(), fields }
1036 } else {
1037 if !adt_def.did().is_local() {
1038 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Union);
1039 }
1040 TypeAliasInnerType::Union { fields }
1041 }
1042 })
1043}
1044
1045fn clean_proc_macro<'tcx>(
1046 item: &hir::Item<'tcx>,
1047 name: &mut Symbol,
1048 kind: MacroKind,
1049 tcx: TyCtxt<'tcx>,
1050) -> ItemKind {
1051 if kind != MacroKind::Derive {
1052 return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
1053 }
1054 let attrs = tcx.hir_attrs(item.hir_id());
1055 let Some((trait_name, helper_attrs)) = find_attr!(attrs, ProcMacroDerive { trait_name, helper_attrs, ..} => (*trait_name, helper_attrs))
1056 else {
1057 return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
1058 };
1059 *name = trait_name;
1060 let helpers = helper_attrs.iter().copied().collect();
1061
1062 ProcMacroItem(ProcMacro { kind, helpers })
1063}
1064
1065fn clean_fn_or_proc_macro<'tcx>(
1066 item: &hir::Item<'tcx>,
1067 sig: &hir::FnSig<'tcx>,
1068 generics: &hir::Generics<'tcx>,
1069 body_id: hir::BodyId,
1070 name: &mut Symbol,
1071 cx: &mut DocContext<'tcx>,
1072) -> ItemKind {
1073 let attrs = cx.tcx.hir_attrs(item.hir_id());
1074 let macro_kind = if find_attr!(attrs, ProcMacro) {
1075 Some(MacroKind::Bang)
1076 } else if find_attr!(attrs, ProcMacroDerive { .. }) {
1077 Some(MacroKind::Derive)
1078 } else if find_attr!(attrs, ProcMacroAttribute) {
1079 Some(MacroKind::Attr)
1080 } else {
1081 None
1082 };
1083
1084 match macro_kind {
1085 Some(kind) => clean_proc_macro(item, name, kind, cx.tcx),
1086 None => {
1087 let mut func = clean_function(
1088 cx,
1089 sig,
1090 generics,
1091 ParamsSrc::Body(body_id),
1092 item.owner_id.to_def_id(),
1093 );
1094 clean_fn_decl_legacy_const_generics(&mut func, attrs);
1095 FunctionItem(func)
1096 }
1097 }
1098}
1099
1100fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) {
1104 let Some(indexes) = find_attr!(attrs, RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes)
1105 else {
1106 return;
1107 };
1108
1109 for (pos, (index, _)) in indexes.iter().enumerate() {
1110 let GenericParamDef { name, kind, .. } = func.generics.params.remove(0);
1111 if let GenericParamDefKind::Const { ty, .. } = kind {
1112 func.decl
1113 .inputs
1114 .insert(*index, Parameter { name: Some(name), type_: *ty, is_const: true });
1115 } else {
1116 panic!("unexpected non const in position {pos}");
1117 }
1118 }
1119}
1120
1121enum ParamsSrc<'tcx> {
1122 Body(hir::BodyId),
1123 Idents(&'tcx [Option<Ident>]),
1124}
1125
1126fn clean_function<'tcx>(
1127 cx: &mut DocContext<'tcx>,
1128 sig: &hir::FnSig<'tcx>,
1129 generics: &hir::Generics<'tcx>,
1130 params: ParamsSrc<'tcx>,
1131 def_id: DefId,
1132) -> Box<Function> {
1133 let (generics, decl) = enter_impl_trait(cx, |cx| {
1134 let generics = clean_generics(generics, cx);
1136 let decl = if sig.decl.opt_delegation_sig_id().is_some() {
1137 let sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1144 clean_poly_fn_sig(cx, Some(def_id), sig)
1145 } else {
1146 let params = match params {
1147 ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl.inputs, body_id),
1148 ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents, |ident| {
1150 Some(ident.map_or(kw::Underscore, |ident| ident.name))
1151 }),
1152 };
1153 clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params)
1154 };
1155 (generics, decl)
1156 });
1157 Box::new(Function { decl, generics })
1158}
1159
1160fn clean_params<'tcx>(
1161 cx: &mut DocContext<'tcx>,
1162 types: &[hir::Ty<'tcx>],
1163 idents: &[Option<Ident>],
1164 postprocess: impl Fn(Option<Ident>) -> Option<Symbol>,
1165) -> Vec<Parameter> {
1166 types
1167 .iter()
1168 .enumerate()
1169 .map(|(i, ty)| Parameter {
1170 name: postprocess(idents[i]),
1171 type_: clean_ty(ty, cx),
1172 is_const: false,
1173 })
1174 .collect()
1175}
1176
1177fn clean_params_via_body<'tcx>(
1178 cx: &mut DocContext<'tcx>,
1179 types: &[hir::Ty<'tcx>],
1180 body_id: hir::BodyId,
1181) -> Vec<Parameter> {
1182 types
1183 .iter()
1184 .zip(cx.tcx.hir_body(body_id).params)
1185 .map(|(ty, param)| Parameter {
1186 name: Some(name_from_pat(param.pat)),
1187 type_: clean_ty(ty, cx),
1188 is_const: false,
1189 })
1190 .collect()
1191}
1192
1193fn clean_fn_decl_with_params<'tcx>(
1194 cx: &mut DocContext<'tcx>,
1195 decl: &hir::FnDecl<'tcx>,
1196 header: Option<&hir::FnHeader>,
1197 params: Vec<Parameter>,
1198) -> FnDecl {
1199 let mut output = match decl.output {
1200 hir::FnRetTy::Return(typ) => clean_ty(typ, cx),
1201 hir::FnRetTy::DefaultReturn(..) => Type::Tuple(Vec::new()),
1202 };
1203 if let Some(header) = header
1204 && header.is_async()
1205 {
1206 output = output.sugared_async_return_type();
1207 }
1208 FnDecl { inputs: params, output, c_variadic: decl.c_variadic() }
1209}
1210
1211fn clean_poly_fn_sig<'tcx>(
1212 cx: &mut DocContext<'tcx>,
1213 did: Option<DefId>,
1214 sig: ty::PolyFnSig<'tcx>,
1215) -> FnDecl {
1216 let mut output = clean_middle_ty(sig.output(), cx, None, None);
1217
1218 if let Some(did) = did
1222 && let Type::ImplTrait(_) = output
1223 && cx.tcx.asyncness(did).is_async()
1224 {
1225 output = output.sugared_async_return_type();
1226 }
1227
1228 let mut idents = did.map(|did| cx.tcx.fn_arg_idents(did)).unwrap_or_default().iter().copied();
1229
1230 let fallback = did.map(|_| kw::Underscore);
1235
1236 let params = sig
1237 .inputs()
1238 .iter()
1239 .map(|ty| Parameter {
1240 name: idents.next().flatten().map(|ident| ident.name).or(fallback),
1241 type_: clean_middle_ty(ty.map_bound(|ty| *ty), cx, None, None),
1242 is_const: false,
1243 })
1244 .collect();
1245
1246 FnDecl { inputs: params, output, c_variadic: sig.skip_binder().c_variadic() }
1247}
1248
1249fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1250 let path = clean_path(trait_ref.path, cx);
1251 register_res(cx, path.res);
1252 path
1253}
1254
1255fn clean_poly_trait_ref<'tcx>(
1256 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1257 cx: &mut DocContext<'tcx>,
1258) -> PolyTrait {
1259 PolyTrait {
1260 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1261 generic_params: poly_trait_ref
1262 .bound_generic_params
1263 .iter()
1264 .filter(|p| !is_elided_lifetime(p))
1265 .map(|x| clean_generic_param(cx, None, x))
1266 .collect(),
1267 }
1268}
1269
1270fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1271 let local_did = trait_item.owner_id.to_def_id();
1272 cx.with_param_env(local_did, |cx| {
1273 let inner = match trait_item.kind {
1274 hir::TraitItemKind::Const(ty, Some(default)) => {
1275 ProvidedAssocConstItem(Box::new(Constant {
1276 generics: enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)),
1277 kind: clean_const_item_rhs(default, local_did),
1278 type_: clean_ty(ty, cx),
1279 }))
1280 }
1281 hir::TraitItemKind::Const(ty, None) => {
1282 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1283 RequiredAssocConstItem(generics, Box::new(clean_ty(ty, cx)))
1284 }
1285 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1286 let m =
1287 clean_function(cx, sig, trait_item.generics, ParamsSrc::Body(body), local_did);
1288 MethodItem(m, Defaultness::from_trait_item(trait_item.defaultness))
1289 }
1290 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(idents)) => {
1291 let m = clean_function(
1292 cx,
1293 sig,
1294 trait_item.generics,
1295 ParamsSrc::Idents(idents),
1296 local_did,
1297 );
1298 RequiredMethodItem(m, Defaultness::from_trait_item(trait_item.defaultness))
1299 }
1300 hir::TraitItemKind::Type(bounds, Some(default)) => {
1301 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1302 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1303 let item_type =
1304 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, default)), cx, None, None);
1305 AssocTypeItem(
1306 Box::new(TypeAlias {
1307 type_: clean_ty(default, cx),
1308 generics,
1309 inner_type: None,
1310 item_type: Some(item_type),
1311 }),
1312 bounds,
1313 )
1314 }
1315 hir::TraitItemKind::Type(bounds, None) => {
1316 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1317 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1318 RequiredAssocTypeItem(generics, bounds)
1319 }
1320 };
1321 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx.tcx)
1322 })
1323}
1324
1325pub(crate) fn clean_impl_item<'tcx>(
1326 impl_: &hir::ImplItem<'tcx>,
1327 cx: &mut DocContext<'tcx>,
1328) -> Item {
1329 let local_did = impl_.owner_id.to_def_id();
1330 cx.with_param_env(local_did, |cx| {
1331 let inner = match impl_.kind {
1332 hir::ImplItemKind::Const(ty, expr) => ImplAssocConstItem(Box::new(Constant {
1333 generics: clean_generics(impl_.generics, cx),
1334 kind: clean_const_item_rhs(expr, local_did),
1335 type_: clean_ty(ty, cx),
1336 })),
1337 hir::ImplItemKind::Fn(ref sig, body) => {
1338 let m = clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body), local_did);
1339 let defaultness = match impl_.impl_kind {
1340 hir::ImplItemImplKind::Inherent { .. } => hir::Defaultness::Final,
1341 hir::ImplItemImplKind::Trait { defaultness, .. } => defaultness,
1342 };
1343 MethodItem(m, Defaultness::from_impl_item(defaultness))
1344 }
1345 hir::ImplItemKind::Type(hir_ty) => {
1346 let type_ = clean_ty(hir_ty, cx);
1347 let generics = clean_generics(impl_.generics, cx);
1348 let item_type =
1349 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1350 AssocTypeItem(
1351 Box::new(TypeAlias {
1352 type_,
1353 generics,
1354 inner_type: None,
1355 item_type: Some(item_type),
1356 }),
1357 Vec::new(),
1358 )
1359 }
1360 };
1361
1362 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx.tcx)
1363 })
1364}
1365
1366pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1367 let tcx = cx.tcx;
1368 let kind = match assoc_item.kind {
1369 ty::AssocKind::Const { .. } => {
1370 let ty = clean_middle_ty(
1371 ty::Binder::dummy(
1372 tcx.type_of(assoc_item.def_id).instantiate_identity().skip_norm_wip(),
1373 ),
1374 cx,
1375 Some(assoc_item.def_id),
1376 None,
1377 );
1378
1379 let mut generics = clean_ty_generics(cx, assoc_item.def_id);
1380 simplify::move_bounds_to_generic_parameters(&mut generics);
1381
1382 match assoc_item.container {
1383 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1384 ImplAssocConstItem(Box::new(Constant {
1385 generics,
1386 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1387 type_: ty,
1388 }))
1389 }
1390 ty::AssocContainer::Trait => {
1391 if tcx.defaultness(assoc_item.def_id).has_value() {
1392 ProvidedAssocConstItem(Box::new(Constant {
1393 generics,
1394 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1395 type_: ty,
1396 }))
1397 } else {
1398 RequiredAssocConstItem(generics, Box::new(ty))
1399 }
1400 }
1401 }
1402 }
1403 ty::AssocKind::Fn { has_self, .. } => {
1404 let mut item = inline::build_function(cx, assoc_item.def_id);
1405
1406 if has_self {
1407 let self_ty = match assoc_item.container {
1408 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => tcx
1409 .type_of(assoc_item.container_id(tcx))
1410 .instantiate_identity()
1411 .skip_norm_wip(),
1412 ty::AssocContainer::Trait => tcx.types.self_param,
1413 };
1414 let self_param_ty = tcx
1415 .fn_sig(assoc_item.def_id)
1416 .instantiate_identity()
1417 .skip_norm_wip()
1418 .input(0)
1419 .skip_binder();
1420 if self_param_ty == self_ty {
1421 item.decl.inputs[0].type_ = SelfTy;
1422 } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1423 && ty == self_ty
1424 {
1425 match item.decl.inputs[0].type_ {
1426 BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1427 _ => unreachable!(),
1428 }
1429 }
1430 }
1431
1432 let defaultness = assoc_item.defaultness(tcx);
1433 let (provided, defaultness) = match assoc_item.container {
1434 ty::AssocContainer::Trait => {
1435 (defaultness.has_value(), Defaultness::from_trait_item(defaultness))
1436 }
1437 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1438 (true, Defaultness::from_impl_item(defaultness))
1439 }
1440 };
1441
1442 if provided {
1443 MethodItem(item, defaultness)
1444 } else {
1445 RequiredMethodItem(item, defaultness)
1446 }
1447 }
1448 ty::AssocKind::Type { .. } => {
1449 let my_name = assoc_item.name();
1450
1451 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1452 match (¶m.kind, arg) {
1453 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1454 if *ty == param.name =>
1455 {
1456 true
1457 }
1458 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1459 if *lt == param.name =>
1460 {
1461 true
1462 }
1463 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1464 ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1465 _ => false,
1466 },
1467 _ => false,
1468 }
1469 }
1470
1471 let mut clauses = tcx.explicit_clauses_of(assoc_item.def_id).clauses;
1472 if let ty::AssocContainer::Trait = assoc_item.container {
1473 let bounds = tcx
1474 .explicit_item_bounds(assoc_item.def_id)
1475 .iter_identity_copied()
1476 .map(Unnormalized::skip_norm_wip);
1477 clauses = tcx.arena.alloc_from_iter(bounds.chain(clauses.iter().copied()));
1478 }
1479 let mut generics = clean_ty_generics_inner(
1480 cx,
1481 tcx.generics_of(assoc_item.def_id),
1482 ty::GenericClauses { parent: None, clauses },
1483 );
1484 simplify::move_bounds_to_generic_parameters(&mut generics);
1485
1486 if let ty::AssocContainer::Trait = assoc_item.container {
1487 let mut bounds: Vec<GenericBound> = Vec::new();
1492 generics.where_predicates.retain_mut(|pred| match *pred {
1493 WherePredicate::BoundPredicate {
1494 ty:
1495 QPath(QPathData {
1496 ref assoc, ref self_type, trait_: Some(ref trait_), ..
1497 }),
1498 bounds: ref mut pred_bounds,
1499 ..
1500 } => {
1501 if assoc.name != my_name {
1502 return true;
1503 }
1504 if trait_.def_id() != assoc_item.container_id(tcx) {
1505 return true;
1506 }
1507 if *self_type != SelfTy {
1508 return true;
1509 }
1510 match &assoc.args {
1511 GenericArgs::AngleBracketed { args, constraints } => {
1512 if !constraints.is_empty()
1513 || generics
1514 .params
1515 .iter()
1516 .zip(args.iter())
1517 .any(|(param, arg)| !param_eq_arg(param, arg))
1518 {
1519 return true;
1520 }
1521 }
1522 GenericArgs::Parenthesized { .. } => {
1523 }
1526 GenericArgs::ReturnTypeNotation => {
1527 }
1529 }
1530 bounds.extend(mem::take(pred_bounds));
1531 false
1532 }
1533 _ => true,
1534 });
1535
1536 bounds.retain(|b| {
1537 !b.is_meta_sized_bound(tcx)
1540 });
1541
1542 match bounds.iter().position(|b| b.is_sized_bound(tcx)) {
1548 Some(i) => {
1549 bounds.remove(i);
1550 }
1551 None => bounds.push(GenericBound::maybe_sized(cx)),
1552 }
1553
1554 if tcx.defaultness(assoc_item.def_id).has_value() {
1555 AssocTypeItem(
1556 Box::new(TypeAlias {
1557 type_: clean_middle_ty(
1558 ty::Binder::dummy(
1559 tcx.type_of(assoc_item.def_id)
1560 .instantiate_identity()
1561 .skip_norm_wip(),
1562 ),
1563 cx,
1564 Some(assoc_item.def_id),
1565 None,
1566 ),
1567 generics,
1568 inner_type: None,
1569 item_type: None,
1570 }),
1571 bounds,
1572 )
1573 } else {
1574 RequiredAssocTypeItem(generics, bounds)
1575 }
1576 } else {
1577 AssocTypeItem(
1578 Box::new(TypeAlias {
1579 type_: clean_middle_ty(
1580 ty::Binder::dummy(
1581 tcx.type_of(assoc_item.def_id)
1582 .instantiate_identity()
1583 .skip_norm_wip(),
1584 ),
1585 cx,
1586 Some(assoc_item.def_id),
1587 None,
1588 ),
1589 generics,
1590 inner_type: None,
1591 item_type: None,
1592 }),
1593 Vec::new(),
1596 )
1597 }
1598 }
1599 };
1600
1601 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, tcx)
1602}
1603
1604fn first_non_private_clean_path<'tcx>(
1605 cx: &mut DocContext<'tcx>,
1606 path: &hir::Path<'tcx>,
1607 new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1608 new_path_span: rustc_span::Span,
1609) -> Path {
1610 let new_hir_path =
1611 hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1612 let mut new_clean_path = clean_path(&new_hir_path, cx);
1613 if let Some(path_last) = path.segments.last().as_ref()
1618 && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1619 && let Some(path_last_args) = path_last.args.as_ref()
1620 && path_last.args.is_some()
1621 {
1622 assert!(new_path_last.args.is_empty());
1623 new_path_last.args = clean_generic_args(None, path_last_args, cx);
1624 }
1625 new_clean_path
1626}
1627
1628fn first_non_private<'tcx>(
1633 cx: &mut DocContext<'tcx>,
1634 hir_id: hir::HirId,
1635 path: &hir::Path<'tcx>,
1636) -> Option<Path> {
1637 let target_def_id = path.res.opt_def_id()?;
1638 let (parent_def_id, ident) = match &path.segments {
1639 [] => return None,
1640 [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1642 [parent, leaf] if parent.ident.name == kw::SelfLower => {
1644 (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1645 }
1646 [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1648 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1649 }
1650 [parent, leaf] if parent.ident.name == kw::Super => {
1651 let parent_mod = cx.tcx.parent_module(hir_id);
1652 if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1653 (super_parent, leaf.ident)
1654 } else {
1655 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1657 }
1658 }
1659 [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1661 };
1662 for child in
1664 cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1665 {
1666 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1667 continue;
1668 }
1669
1670 if let Some(def_id) = child.res.opt_def_id()
1671 && target_def_id == def_id
1672 {
1673 let mut last_path_res = None;
1674 'reexps: for reexp in child.reexport_chain.iter() {
1675 if let Some(use_def_id) = reexp.id()
1676 && let Some(local_use_def_id) = use_def_id.as_local()
1677 && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1678 && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1679 {
1680 for res in path.res.present_items() {
1681 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1682 continue;
1683 }
1684 if (cx.document_hidden() ||
1685 !cx.tcx.is_doc_hidden(use_def_id)) &&
1686 cx.tcx.local_visibility(local_use_def_id).is_public()
1690 {
1691 break 'reexps;
1692 }
1693 last_path_res = Some((path, res));
1694 continue 'reexps;
1695 }
1696 }
1697 }
1698 if !child.reexport_chain.is_empty() {
1699 if let Some((new_path, _)) = last_path_res {
1705 return Some(first_non_private_clean_path(
1706 cx,
1707 path,
1708 new_path.segments,
1709 new_path.span,
1710 ));
1711 }
1712 return None;
1717 }
1718 }
1719 }
1720 None
1721}
1722
1723fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1724 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1725 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1726
1727 match qpath {
1728 hir::QPath::Resolved(None, path) => {
1729 if let Res::Def(DefKind::TyParam, did) = path.res {
1730 if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1731 return new_ty;
1732 }
1733 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1734 return ImplTrait(bounds);
1735 }
1736 }
1737
1738 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1739 expanded
1740 } else {
1741 let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1743 path
1744 } else {
1745 clean_path(path, cx)
1746 };
1747 resolve_type(cx, path)
1748 }
1749 }
1750 hir::QPath::Resolved(Some(qself), p) => {
1751 let ty = lower_ty(cx.tcx, hir_ty);
1753 if !ty.has_escaping_bound_vars()
1755 && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1756 {
1757 return clean_middle_ty(normalized_value, cx, None, None);
1758 }
1759
1760 let trait_segments = &p.segments[..p.segments.len() - 1];
1761 let trait_def = cx.tcx.parent(p.res.def_id());
1762 let trait_ = self::Path {
1763 res: Res::Def(DefKind::Trait, trait_def),
1764 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1765 };
1766 register_res(cx, trait_.res);
1767 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1768 let self_type = clean_ty(qself, cx);
1769 let should_fully_qualify =
1770 should_fully_qualify_path(Some(self_def_id), &trait_, &self_type);
1771 Type::QPath(Box::new(QPathData {
1772 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1773 should_fully_qualify,
1774 self_type,
1775 trait_: Some(trait_),
1776 }))
1777 }
1778 hir::QPath::TypeRelative(qself, segment) => {
1779 let ty = lower_ty(cx.tcx, hir_ty);
1780 let self_type = clean_ty(qself, cx);
1781
1782 let (trait_, should_fully_qualify) = match ty.kind() {
1783 ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
1784 let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1785 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1786 register_res(cx, trait_.res);
1787 let self_def_id = res.opt_def_id();
1788 let should_fully_qualify =
1789 should_fully_qualify_path(self_def_id, &trait_, &self_type);
1790
1791 (Some(trait_), should_fully_qualify)
1792 }
1793 ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => (None, false),
1794 ty::Error(_) => return Type::Infer,
1796 _ => bug!("clean: expected associated type, found `{ty:?}`"),
1797 };
1798
1799 Type::QPath(Box::new(QPathData {
1800 assoc: clean_path_segment(segment, cx),
1801 should_fully_qualify,
1802 self_type,
1803 trait_,
1804 }))
1805 }
1806 }
1807}
1808
1809fn maybe_expand_private_type_alias<'tcx>(
1810 cx: &mut DocContext<'tcx>,
1811 path: &hir::Path<'tcx>,
1812) -> Option<Type> {
1813 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1814 let def_id = def_id.as_local()?;
1816 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1817 && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1818 {
1819 &cx.tcx.hir_expect_item(def_id).kind
1820 } else {
1821 return None;
1822 };
1823 let hir::ItemKind::TyAlias(_, generics, ty) = alias else { return None };
1824
1825 let final_seg = &path.segments.last().expect("segments were empty");
1826 let mut args = DefIdMap::default();
1827 let generic_args = final_seg.args();
1828
1829 let mut indices: hir::GenericParamCount = Default::default();
1830 for param in generics.params.iter() {
1831 match param.kind {
1832 hir::GenericParamKind::Lifetime { .. } => {
1833 let mut j = 0;
1834 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1835 hir::GenericArg::Lifetime(lt) => {
1836 if indices.lifetimes == j {
1837 return Some(lt);
1838 }
1839 j += 1;
1840 None
1841 }
1842 _ => None,
1843 });
1844 if let Some(lt) = lifetime {
1845 let lt = if !lt.is_anonymous() {
1846 clean_lifetime(lt, cx)
1847 } else {
1848 Lifetime::elided()
1849 };
1850 args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1851 }
1852 indices.lifetimes += 1;
1853 }
1854 hir::GenericParamKind::Type { ref default, .. } => {
1855 let mut j = 0;
1856 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1857 hir::GenericArg::Type(ty) => {
1858 if indices.types == j {
1859 return Some(ty.as_unambig_ty());
1860 }
1861 j += 1;
1862 None
1863 }
1864 _ => None,
1865 });
1866 if let Some(ty) = type_.or(*default) {
1867 args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1868 }
1869 indices.types += 1;
1870 }
1871 hir::GenericParamKind::Const { .. } => {}
1873 }
1874 }
1875
1876 Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1877 cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1878 }))
1879}
1880
1881pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1882 use rustc_hir::*;
1883
1884 match ty.kind {
1885 TyKind::Never => Primitive(PrimitiveType::Never),
1886 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1887 TyKind::Ref(l, ref m) => {
1888 let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1889 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1890 }
1891 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1892 TyKind::Pat(inner_ty, pat) => {
1893 let pat = match lower_ty(cx.tcx, ty).kind() {
1896 ty::Pat(_, pat) => format!("{pat:?}").into_boxed_str(),
1897 _ => format!("{pat:?}").into(),
1898 };
1899 Type::Pat(Box::new(clean_ty(inner_ty, cx)), pat)
1900 }
1901 TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => {
1902 let field_str = if let Some(variant) = variant {
1903 format!("{variant}.{field}")
1904 } else {
1905 format!("{field}")
1906 };
1907 Type::FieldOf(Box::new(clean_ty(ty, cx)), field_str.into())
1908 }
1909 TyKind::Array(ty, const_arg) => {
1910 let length = match const_arg.kind {
1918 hir::ConstArgKind::Infer(..) | hir::ConstArgKind::Error(..) => "_".to_string(),
1919 hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1920 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, cx.tcx.types.usize);
1921 let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1922 let ct =
1923 cx.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ct));
1924 print_const(cx.tcx, ct)
1925 }
1926 hir::ConstArgKind::Struct(..)
1927 | hir::ConstArgKind::Path(..)
1928 | hir::ConstArgKind::TupleCall(..)
1929 | hir::ConstArgKind::Tup(..)
1930 | hir::ConstArgKind::Array(..)
1931 | hir::ConstArgKind::Literal { .. } => {
1932 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, cx.tcx.types.usize);
1933 print_const(cx.tcx, ct)
1934 }
1935 };
1936 Array(Box::new(clean_ty(ty, cx)), length.into())
1937 }
1938 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1939 TyKind::OpaqueDef(ty) => {
1940 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1941 }
1942 TyKind::Path(_) => clean_qpath(ty, cx),
1943 TyKind::TraitObject(bounds, lifetime) => {
1944 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1945 let lifetime = if !lifetime.is_elided() {
1946 Some(clean_lifetime(lifetime.pointer(), cx))
1947 } else {
1948 None
1949 };
1950 DynTrait(bounds, lifetime)
1951 }
1952 TyKind::FnPtr(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1953 TyKind::UnsafeBinder(unsafe_binder_ty) => {
1954 UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1955 }
1956 TyKind::View(ty, _) => {
1957 clean_ty(ty, cx)
1959 }
1960 TyKind::Infer(())
1962 | TyKind::Err(_)
1963 | TyKind::InferDelegation(..)
1964 | TyKind::TraitAscription(_) => Infer,
1965 }
1966}
1967
1968fn normalize<'tcx>(
1970 cx: &DocContext<'tcx>,
1971 ty: ty::Binder<'tcx, Ty<'tcx>>,
1972) -> Option<ty::Binder<'tcx, Ty<'tcx>>> {
1973 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1975 return None;
1976 }
1977
1978 use rustc_middle::traits::ObligationCause;
1979 use rustc_trait_selection::infer::TyCtxtInferExt;
1980 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1981
1982 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1984 let normalized = infcx
1985 .at(&ObligationCause::dummy(), cx.param_env)
1986 .query_normalize(ty)
1987 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1988 match normalized {
1989 Ok(normalized_value) => {
1990 debug!("normalized {ty:?} to {normalized_value:?}");
1991 Some(normalized_value)
1992 }
1993 Err(err) => {
1994 debug!("failed to normalize {ty:?}: {err:?}");
1995 None
1996 }
1997 }
1998}
1999
2000fn clean_trait_object_lifetime_bound<'tcx>(
2001 region: ty::Region<'tcx>,
2002 container: Option<ContainerTy<'_, 'tcx>>,
2003 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2004 tcx: TyCtxt<'tcx>,
2005) -> Option<Lifetime> {
2006 if can_elide_trait_object_lifetime_bound(region, container, preds, tcx) {
2007 return None;
2008 }
2009
2010 match region.kind() {
2014 ty::ReStatic => Some(Lifetime::statik()),
2015 ty::ReEarlyParam(region) => Some(Lifetime(region.name)),
2016 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. }) => {
2017 Some(Lifetime(tcx.item_name(def_id)))
2018 }
2019 ty::ReBound(..)
2020 | ty::ReLateParam(_)
2021 | ty::ReVar(_)
2022 | ty::RePlaceholder(_)
2023 | ty::ReErased
2024 | ty::ReError(_) => None,
2025 }
2026}
2027
2028fn can_elide_trait_object_lifetime_bound<'tcx>(
2029 region: ty::Region<'tcx>,
2030 container: Option<ContainerTy<'_, 'tcx>>,
2031 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2032 tcx: TyCtxt<'tcx>,
2033) -> bool {
2034 let default = container
2039 .map_or(ObjectLifetimeDefault::Empty, |container| container.object_lifetime_default(tcx));
2040
2041 match default {
2044 ObjectLifetimeDefault::Static => return region.kind() == ty::ReStatic,
2045 ObjectLifetimeDefault::Arg(default) => {
2047 return region.get_name(tcx) == default.get_name(tcx);
2048 }
2049 ObjectLifetimeDefault::Ambiguous => return false,
2053 ObjectLifetimeDefault::Empty => {}
2055 }
2056
2057 match *object_region_bounds(tcx, preds) {
2059 [] => region.kind() == ty::ReStatic,
2067 [object_region] => object_region.get_name(tcx) == region.get_name(tcx),
2071 _ => false,
2075 }
2076}
2077
2078#[derive(Debug)]
2079pub(crate) enum ContainerTy<'a, 'tcx> {
2080 Ref(ty::Region<'tcx>),
2081 Regular {
2082 ty: DefId,
2083 args: ty::Binder<'tcx, &'a [ty::GenericArg<'tcx>]>,
2086 arg: usize,
2087 },
2088}
2089
2090impl<'tcx> ContainerTy<'_, 'tcx> {
2091 fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> {
2092 match self {
2093 Self::Ref(region) => ObjectLifetimeDefault::Arg(region),
2094 Self::Regular { ty: container, args, arg: index } => {
2095 let (DefKind::Struct
2099 | DefKind::Union
2100 | DefKind::Enum
2101 | DefKind::TyAlias
2102 | DefKind::Trait) = tcx.def_kind(container)
2103 else {
2104 return ObjectLifetimeDefault::Empty;
2105 };
2106
2107 let generics = tcx.generics_of(container);
2108 debug_assert_eq!(generics.parent_count, 0);
2109
2110 let param = generics.own_params[index].def_id;
2111 let default = tcx.object_lifetime_default(param);
2112 match default {
2113 rbv::ObjectLifetimeDefault::Param(lifetime) => {
2114 let index = generics.param_def_id_to_index[&lifetime];
2117 let arg = args.skip_binder()[index as usize].expect_region();
2118 ObjectLifetimeDefault::Arg(arg)
2119 }
2120 rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty,
2121 rbv::ObjectLifetimeDefault::Static => ObjectLifetimeDefault::Static,
2122 rbv::ObjectLifetimeDefault::Ambiguous => ObjectLifetimeDefault::Ambiguous,
2123 }
2124 }
2125 }
2126 }
2127}
2128
2129#[derive(Debug, Clone, Copy)]
2130pub(crate) enum ObjectLifetimeDefault<'tcx> {
2131 Empty,
2132 Static,
2133 Ambiguous,
2134 Arg(ty::Region<'tcx>),
2135}
2136
2137#[instrument(level = "trace", skip(cx), ret)]
2138pub(crate) fn clean_middle_ty<'tcx>(
2139 bound_ty: ty::Binder<'tcx, Ty<'tcx>>,
2140 cx: &mut DocContext<'tcx>,
2141 parent_def_id: Option<DefId>,
2142 container: Option<ContainerTy<'_, 'tcx>>,
2143) -> Type {
2144 let bound_ty = normalize(cx, bound_ty).unwrap_or(bound_ty);
2145 match *bound_ty.skip_binder().kind() {
2146 ty::Never => Primitive(PrimitiveType::Never),
2147 ty::Bool => Primitive(PrimitiveType::Bool),
2148 ty::Char => Primitive(PrimitiveType::Char),
2149 ty::Int(int_ty) => Primitive(int_ty.into()),
2150 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
2151 ty::Float(float_ty) => Primitive(float_ty.into()),
2152 ty::Str => Primitive(PrimitiveType::Str),
2153 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None))),
2154 ty::Pat(ty, pat) => Type::Pat(
2155 Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)),
2156 format!("{pat:?}").into_boxed_str(),
2157 ),
2158 ty::Array(ty, n) => {
2159 let n = cx
2160 .tcx
2161 .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(n))
2162 .unwrap_or(n);
2163 let n = print_const(cx.tcx, n);
2164 Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into())
2165 }
2166 ty::RawPtr(ty, mutbl) => {
2167 RawPointer(mutbl, Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)))
2168 }
2169 ty::Ref(r, ty, mutbl) => BorrowedRef {
2170 lifetime: clean_middle_region(r, cx.tcx),
2171 mutability: mutbl,
2172 type_: Box::new(clean_middle_ty(
2173 bound_ty.rebind(ty),
2174 cx,
2175 None,
2176 Some(ContainerTy::Ref(r)),
2177 )),
2178 },
2179 ty::FnDef(..) | ty::FnPtr(..) => {
2180 let sig = bound_ty.skip_binder().fn_sig(cx.tcx);
2182 let decl = clean_poly_fn_sig(cx, None, sig);
2183 let generic_params = clean_bound_vars(sig.bound_vars(), cx.tcx);
2184
2185 BareFunction(Box::new(BareFunctionDecl {
2186 safety: sig.safety(),
2187 generic_params,
2188 decl,
2189 abi: sig.abi(),
2190 }))
2191 }
2192 ty::UnsafeBinder(inner) => {
2193 let generic_params = clean_bound_vars(inner.bound_vars(), cx.tcx);
2194 let ty = clean_middle_ty(inner.into(), cx, None, None);
2195 UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, ty }))
2196 }
2197 ty::Adt(def, args) => {
2198 let did = def.did();
2199 let kind = match def.adt_kind() {
2200 AdtKind::Struct => ItemType::Struct,
2201 AdtKind::Union => ItemType::Union,
2202 AdtKind::Enum => ItemType::Enum,
2203 };
2204 inline::record_extern_fqn(cx, did, kind);
2205 let path = clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args));
2206 Type::Path { path }
2207 }
2208 ty::Foreign(did) => {
2209 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
2210 let path = clean_middle_path(
2211 cx,
2212 did,
2213 false,
2214 ThinVec::new(),
2215 ty::Binder::dummy(ty::GenericArgs::empty()),
2216 );
2217 Type::Path { path }
2218 }
2219 ty::Dynamic(obj, reg) => {
2220 let mut dids = obj.auto_traits();
2224 let did = obj
2225 .principal_def_id()
2226 .or_else(|| dids.next())
2227 .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?"));
2228 let args = match obj.principal() {
2229 Some(principal) => principal.map_bound(|p| p.args),
2230 _ => ty::Binder::dummy(ty::GenericArgs::empty()),
2232 };
2233
2234 inline::record_extern_fqn(cx, did, ItemType::Trait);
2235
2236 let lifetime = clean_trait_object_lifetime_bound(reg, container, obj, cx.tcx);
2237
2238 let mut bounds = dids
2239 .map(|did| {
2240 let empty = ty::Binder::dummy(ty::GenericArgs::empty());
2241 let path = clean_middle_path(cx, did, false, ThinVec::new(), empty);
2242 inline::record_extern_fqn(cx, did, ItemType::Trait);
2243 PolyTrait { trait_: path, generic_params: Vec::new() }
2244 })
2245 .collect::<Vec<_>>();
2246
2247 let constraints = obj
2248 .projection_bounds()
2249 .map(|pb| AssocItemConstraint {
2250 assoc: projection_to_path_segment(
2251 pb.map_bound(|pb| {
2252 pb.with_self_ty(cx.tcx, cx.tcx.types.trait_object_dummy_self)
2253 .projection_term
2254 }),
2255 cx,
2256 ),
2257 kind: AssocItemConstraintKind::Equality {
2258 term: clean_middle_term(pb.map_bound(|pb| pb.term), cx),
2259 },
2260 })
2261 .collect();
2262
2263 let late_bound_regions: FxIndexSet<_> = obj
2264 .iter()
2265 .flat_map(|pred| pred.bound_vars())
2266 .filter_map(|var| match var {
2267 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
2268 let name = cx.tcx.item_name(def_id);
2269 if name != kw::UnderscoreLifetime {
2270 Some(GenericParamDef::lifetime(def_id, name))
2271 } else {
2272 None
2273 }
2274 }
2275 _ => None,
2276 })
2277 .collect();
2278 let late_bound_regions = late_bound_regions.into_iter().collect();
2279
2280 let path = clean_middle_path(cx, did, false, constraints, args);
2281 bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
2282
2283 DynTrait(bounds, lifetime)
2284 }
2285 ty::Tuple(t) => {
2286 Tuple(t.iter().map(|t| clean_middle_ty(bound_ty.rebind(t), cx, None, None)).collect())
2287 }
2288
2289 ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) => {
2290 if cx.tcx.is_impl_trait_in_trait(def_id) {
2291 clean_middle_opaque_bounds(cx, def_id, args)
2292 } else {
2293 Type::QPath(Box::new(clean_projection(
2294 bound_ty.rebind(alias_ty.into()),
2295 cx,
2296 parent_def_id,
2297 )))
2298 }
2299 }
2300
2301 ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Inherent { def_id }, .. }) => {
2302 let alias_ty = bound_ty.rebind(alias_ty);
2303 let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None, None);
2304
2305 Type::QPath(Box::new(QPathData {
2306 assoc: PathSegment {
2307 name: cx.tcx.item_name(def_id),
2308 args: GenericArgs::AngleBracketed {
2309 args: clean_middle_generic_args(
2310 cx,
2311 alias_ty.map_bound(|ty| ty.args.as_slice()),
2312 true,
2313 def_id,
2314 ),
2315 constraints: Default::default(),
2316 },
2317 },
2318 should_fully_qualify: false,
2319 self_type,
2320 trait_: None,
2321 }))
2322 }
2323
2324 ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) => {
2325 if cx.tcx.features().checked_type_aliases() {
2326 let path =
2329 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2330 Type::Path { path }
2331 } else {
2332 let ty = cx.tcx.type_of(def_id).instantiate(cx.tcx, args).skip_norm_wip();
2333 clean_middle_ty(bound_ty.rebind(ty), cx, None, None)
2334 }
2335 }
2336
2337 ty::Param(ref p) => {
2338 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
2339 ImplTrait(bounds)
2340 } else if p.name == kw::SelfUpper {
2341 SelfTy
2342 } else {
2343 Generic(p.name)
2344 }
2345 }
2346
2347 ty::Bound(_, ref ty) => match ty.kind {
2348 ty::BoundTyKind::Param(def_id) => Generic(cx.tcx.item_name(def_id)),
2349 ty::BoundTyKind::Anon => panic!("unexpected anonymous bound type variable"),
2350 },
2351
2352 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
2353 if cx.current_type_aliases.contains_key(&def_id) {
2355 let path =
2356 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2357 Type::Path { path }
2358 } else {
2359 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2360 let ty = clean_middle_opaque_bounds(cx, def_id, args);
2363 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2364 *count -= 1;
2365 if *count == 0 {
2366 cx.current_type_aliases.remove(&def_id);
2367 }
2368 }
2369 ty
2370 }
2371 }
2372
2373 ty::Closure(..) => panic!("Closure"),
2374 ty::CoroutineClosure(..) => panic!("CoroutineClosure"),
2375 ty::Coroutine(..) => panic!("Coroutine"),
2376 ty::Placeholder(..) => panic!("Placeholder"),
2377 ty::CoroutineWitness(..) => panic!("CoroutineWitness"),
2378 ty::Infer(..) => panic!("Infer"),
2379
2380 ty::Error(_) => FatalError.raise(),
2381 }
2382}
2383
2384fn clean_middle_opaque_bounds<'tcx>(
2385 cx: &mut DocContext<'tcx>,
2386 impl_trait_def_id: DefId,
2387 args: ty::GenericArgsRef<'tcx>,
2388) -> Type {
2389 let mut has_sized = false;
2390
2391 let bounds: Vec<_> = cx
2392 .tcx
2393 .explicit_item_bounds(impl_trait_def_id)
2394 .iter_instantiated_copied(cx.tcx, args)
2395 .map(Unnormalized::skip_norm_wip)
2396 .collect();
2397
2398 let mut bounds = bounds
2399 .iter()
2400 .filter_map(|(bound, _)| {
2401 let bound_predicate = bound.kind();
2402 let trait_ref = match bound_predicate.skip_binder() {
2403 ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
2404 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
2405 return clean_middle_region(reg, cx.tcx).map(GenericBound::Outlives);
2406 }
2407 _ => return None,
2408 };
2409
2410 if cx.tcx.is_lang_item(trait_ref.def_id(), LangItem::MetaSized) {
2413 return None;
2414 }
2415
2416 if let Some(sized) = cx.tcx.lang_items().sized_trait()
2417 && trait_ref.def_id() == sized
2418 {
2419 has_sized = true;
2420 return None;
2421 }
2422
2423 let bindings: ThinVec<_> = bounds
2424 .iter()
2425 .filter_map(|(bound, _)| {
2426 let bound = bound.kind();
2427 if let ty::ClauseKind::Projection(proj_pred) = bound.skip_binder()
2428 && proj_pred.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
2429 {
2430 return Some(AssocItemConstraint {
2431 assoc: projection_to_path_segment(
2432 bound.rebind(proj_pred.projection_term),
2433 cx,
2434 ),
2435 kind: AssocItemConstraintKind::Equality {
2436 term: clean_middle_term(bound.rebind(proj_pred.term), cx),
2437 },
2438 });
2439 }
2440 None
2441 })
2442 .collect();
2443
2444 Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings))
2445 })
2446 .collect::<Vec<_>>();
2447
2448 if !has_sized {
2449 bounds.push(GenericBound::maybe_sized(cx));
2450 }
2451
2452 bounds.sort_by_key(|b| !b.is_trait_bound());
2454
2455 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
2458 bounds.insert(0, GenericBound::sized(cx));
2459 }
2460
2461 if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) {
2462 bounds.push(GenericBound::Use(
2463 args.iter()
2464 .map(|arg| match arg {
2465 hir::PreciseCapturingArgKind::Lifetime(lt) => {
2466 PreciseCapturingArg::Lifetime(Lifetime(*lt))
2467 }
2468 hir::PreciseCapturingArgKind::Param(param) => {
2469 PreciseCapturingArg::Param(*param)
2470 }
2471 })
2472 .collect(),
2473 ));
2474 }
2475
2476 ImplTrait(bounds)
2477}
2478
2479pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2480 clean_field_with_def_id(
2481 field.def_id.to_def_id(),
2482 field.ident.name,
2483 clean_ty(field.ty, cx),
2484 cx.tcx,
2485 )
2486}
2487
2488pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item {
2489 clean_field_with_def_id(
2490 field.did,
2491 field.name,
2492 clean_middle_ty(
2493 ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity().skip_norm_wip()),
2494 cx,
2495 Some(field.did),
2496 None,
2497 ),
2498 cx.tcx,
2499 )
2500}
2501
2502pub(crate) fn clean_field_with_def_id(
2503 def_id: DefId,
2504 name: Symbol,
2505 ty: Type,
2506 tcx: TyCtxt<'_>,
2507) -> Item {
2508 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), tcx)
2509}
2510
2511pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item {
2512 let discriminant = match variant.discr {
2513 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2514 ty::VariantDiscr::Relative(_) => None,
2515 };
2516
2517 let kind = match variant.ctor_kind() {
2518 Some(CtorKind::Const) => VariantKind::CLike,
2519 Some(CtorKind::Fn) => VariantKind::Tuple(
2520 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2521 ),
2522 None => VariantKind::Struct(VariantStruct {
2523 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2524 }),
2525 };
2526
2527 Item::from_def_id_and_parts(
2528 variant.def_id,
2529 Some(variant.name),
2530 VariantItem(Variant { kind, discriminant }),
2531 cx.tcx,
2532 )
2533}
2534
2535pub(crate) fn clean_variant_def_with_args<'tcx>(
2536 variant: &ty::VariantDef,
2537 args: &GenericArgsRef<'tcx>,
2538 cx: &mut DocContext<'tcx>,
2539) -> Item {
2540 let discriminant = match variant.discr {
2541 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2542 ty::VariantDiscr::Relative(_) => None,
2543 };
2544
2545 use rustc_middle::traits::ObligationCause;
2546 use rustc_trait_selection::infer::TyCtxtInferExt;
2547 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
2548
2549 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2550 let kind = match variant.ctor_kind() {
2551 Some(CtorKind::Const) => VariantKind::CLike,
2552 Some(CtorKind::Fn) => VariantKind::Tuple(
2553 variant
2554 .fields
2555 .iter()
2556 .map(|field| {
2557 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args).skip_norm_wip();
2558
2559 let ty = infcx
2563 .at(&ObligationCause::dummy(), cx.param_env)
2564 .query_normalize(ty)
2565 .map(|normalized| normalized.value)
2566 .unwrap_or(ty);
2567
2568 clean_field_with_def_id(
2569 field.did,
2570 field.name,
2571 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2572 cx.tcx,
2573 )
2574 })
2575 .collect(),
2576 ),
2577 None => VariantKind::Struct(VariantStruct {
2578 fields: variant
2579 .fields
2580 .iter()
2581 .map(|field| {
2582 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args).skip_norm_wip();
2583
2584 let ty = infcx
2588 .at(&ObligationCause::dummy(), cx.param_env)
2589 .query_normalize(ty)
2590 .map(|normalized| normalized.value)
2591 .unwrap_or(ty);
2592
2593 clean_field_with_def_id(
2594 field.did,
2595 field.name,
2596 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2597 cx.tcx,
2598 )
2599 })
2600 .collect(),
2601 }),
2602 };
2603
2604 Item::from_def_id_and_parts(
2605 variant.def_id,
2606 Some(variant.name),
2607 VariantItem(Variant { kind, discriminant }),
2608 cx.tcx,
2609 )
2610}
2611
2612fn clean_variant_data<'tcx>(
2613 variant: &hir::VariantData<'tcx>,
2614 disr_expr: &Option<&hir::AnonConst>,
2615 cx: &mut DocContext<'tcx>,
2616) -> Variant {
2617 let discriminant = disr_expr
2618 .map(|disr| Discriminant { expr: Some(disr.body), value: disr.def_id.to_def_id() });
2619
2620 let kind = match variant {
2621 hir::VariantData::Struct { fields, .. } => VariantKind::Struct(VariantStruct {
2622 fields: fields.iter().map(|x| clean_field(x, cx)).collect(),
2623 }),
2624 hir::VariantData::Tuple(..) => {
2625 VariantKind::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
2626 }
2627 hir::VariantData::Unit(..) => VariantKind::CLike,
2628 };
2629
2630 Variant { discriminant, kind }
2631}
2632
2633fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
2634 Path {
2635 res: path.res,
2636 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
2637 }
2638}
2639
2640fn clean_generic_args<'tcx>(
2641 trait_did: Option<DefId>,
2642 generic_args: &hir::GenericArgs<'tcx>,
2643 cx: &mut DocContext<'tcx>,
2644) -> GenericArgs {
2645 match generic_args.parenthesized {
2646 hir::GenericArgsParentheses::No => {
2647 let args = generic_args
2648 .args
2649 .iter()
2650 .map(|arg| match arg {
2651 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
2652 GenericArg::Lifetime(clean_lifetime(lt, cx))
2653 }
2654 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2655 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)),
2656 hir::GenericArg::Const(ct) => {
2657 GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct())))
2658 }
2659 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
2660 })
2661 .collect();
2662 let constraints = generic_args
2663 .constraints
2664 .iter()
2665 .map(|c| {
2666 clean_assoc_item_constraint(
2667 trait_did.expect("only trait ref has constraints"),
2668 c,
2669 cx,
2670 )
2671 })
2672 .collect::<ThinVec<_>>();
2673 GenericArgs::AngleBracketed { args, constraints }
2674 }
2675 hir::GenericArgsParentheses::ParenSugar => {
2676 let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else {
2677 bug!();
2678 };
2679 let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect();
2680 let output = match output.kind {
2681 hir::TyKind::Tup(&[]) => None,
2682 _ => Some(Box::new(clean_ty(output, cx))),
2683 };
2684 GenericArgs::Parenthesized { inputs, output }
2685 }
2686 hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
2687 }
2688}
2689
2690fn clean_path_segment<'tcx>(
2691 path: &hir::PathSegment<'tcx>,
2692 cx: &mut DocContext<'tcx>,
2693) -> PathSegment {
2694 let trait_did = match path.res {
2695 hir::def::Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2696 _ => None,
2697 };
2698 PathSegment { name: path.ident.name, args: clean_generic_args(trait_did, path.args(), cx) }
2699}
2700
2701fn clean_bare_fn_ty<'tcx>(
2702 bare_fn: &hir::FnPtrTy<'tcx>,
2703 cx: &mut DocContext<'tcx>,
2704) -> BareFunctionDecl {
2705 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
2706 let generic_params = bare_fn
2708 .generic_params
2709 .iter()
2710 .filter(|p| !is_elided_lifetime(p))
2711 .map(|x| clean_generic_param(cx, None, x))
2712 .collect();
2713 let filter = |ident: Option<Ident>| {
2717 ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore)
2718 };
2719 let fallback =
2720 bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore);
2721 let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents, |ident| {
2722 filter(ident).or(fallback)
2723 });
2724 let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params);
2725 (generic_params, decl)
2726 });
2727 BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params }
2728}
2729
2730fn clean_unsafe_binder_ty<'tcx>(
2731 unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>,
2732 cx: &mut DocContext<'tcx>,
2733) -> UnsafeBinderTy {
2734 let generic_params = unsafe_binder_ty
2735 .generic_params
2736 .iter()
2737 .filter(|p| !is_elided_lifetime(p))
2738 .map(|x| clean_generic_param(cx, None, x))
2739 .collect();
2740 let ty = clean_ty(unsafe_binder_ty.inner_ty, cx);
2741 UnsafeBinderTy { generic_params, ty }
2742}
2743
2744pub(crate) fn reexport_chain(
2745 tcx: TyCtxt<'_>,
2746 import_def_id: LocalDefId,
2747 target_def_id: DefId,
2748) -> &[Reexport] {
2749 for child in tcx.module_children_local(tcx.local_parent(import_def_id)) {
2750 if child.res.opt_def_id() == Some(target_def_id)
2751 && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id())
2752 {
2753 return &child.reexport_chain;
2754 }
2755 }
2756 &[]
2757}
2758
2759fn get_all_import_attributes<'hir>(
2761 cx: &mut DocContext<'hir>,
2762 import_def_id: LocalDefId,
2763 target_def_id: DefId,
2764 is_inline: bool,
2765) -> Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)> {
2766 let mut attrs = Vec::new();
2767 let mut first = true;
2768 for def_id in reexport_chain(cx.tcx, import_def_id, target_def_id)
2769 .iter()
2770 .flat_map(|reexport| reexport.id())
2771 {
2772 let import_attrs = inline::load_attrs(cx.tcx, def_id);
2773 if first {
2774 attrs = import_attrs.iter().map(|attr| (Cow::Borrowed(attr), Some(def_id))).collect();
2776 first = false;
2777 } else if cx.document_hidden() || !cx.tcx.is_doc_hidden(def_id) {
2779 add_without_unwanted_attributes(&mut attrs, import_attrs, is_inline, Some(def_id));
2780 }
2781 }
2782 attrs
2783}
2784
2785fn add_without_unwanted_attributes<'hir>(
2806 attrs: &mut Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)>,
2807 new_attrs: &'hir [hir::Attribute],
2808 is_inline: bool,
2809 import_parent: Option<DefId>,
2810) {
2811 for attr in new_attrs {
2812 match attr {
2813 hir::Attribute::Parsed(AttributeKind::DocComment { .. }) => {
2814 attrs.push((Cow::Borrowed(attr), import_parent));
2815 }
2816 hir::Attribute::Parsed(AttributeKind::Doc(d)) => {
2817 let DocAttribute {
2819 first_span: _,
2820 aliases,
2821 hidden,
2822 inline,
2823 cfg,
2824 auto_cfg: _,
2825 auto_cfg_change: _,
2826 fake_variadic: _,
2827 keyword: _,
2828 attribute: _,
2829 masked: _,
2830 notable_trait: _,
2831 search_unbox: _,
2832 html_favicon_url: _,
2833 html_logo_url: _,
2834 html_playground_url: _,
2835 html_root_url: _,
2836 html_no_source: _,
2837 issue_tracker_base_url: _,
2838 rust_logo: _,
2839 test_attrs: _,
2840 no_crate_inject: _,
2841 } = d;
2842 let mut attr = DocAttribute::default();
2843 if is_inline {
2844 attr.cfg = cfg.clone();
2845 } else {
2846 attr.inline = inline.clone();
2847 attr.hidden = hidden.clone();
2848 }
2849 attr.aliases = aliases.clone();
2850 attrs.push((
2851 Cow::Owned(hir::Attribute::Parsed(AttributeKind::Doc(Box::new(attr)))),
2852 import_parent,
2853 ));
2854 }
2855
2856 hir::Attribute::Parsed(AttributeKind::CfgTrace(..)) if !is_inline => {}
2858 _ => {
2860 attrs.push((Cow::Borrowed(attr), import_parent));
2861 }
2862 }
2863 }
2864}
2865
2866fn clean_maybe_renamed_item<'tcx>(
2867 cx: &mut DocContext<'tcx>,
2868 item: &hir::Item<'tcx>,
2869 renamed: Option<Symbol>,
2870 import_ids: &[LocalDefId],
2871) -> Vec<Item> {
2872 use hir::ItemKind;
2873 fn get_name(tcx: TyCtxt<'_>, item: &hir::Item<'_>, renamed: Option<Symbol>) -> Option<Symbol> {
2874 renamed.or_else(|| tcx.hir_opt_name(item.hir_id()))
2875 }
2876
2877 let def_id = item.owner_id.to_def_id();
2878 cx.with_param_env(def_id, |cx| {
2879 match item.kind {
2882 ItemKind::Impl(ref impl_) => {
2883 return clean_impl(impl_, item.owner_id.def_id, cx, renamed.is_some());
2887 }
2888 ItemKind::Use(path, kind) => {
2889 return clean_use_statement(
2890 item,
2891 get_name(cx.tcx, item, renamed),
2892 path,
2893 kind,
2894 cx,
2895 &mut FxHashSet::default(),
2896 );
2897 }
2898 _ => {}
2899 }
2900
2901 let mut name = get_name(cx.tcx, item, renamed).unwrap();
2902
2903 let kind = match item.kind {
2904 ItemKind::Static(mutability, _, ty, body_id) => StaticItem(Static {
2905 type_: Box::new(clean_ty(ty, cx)),
2906 mutability,
2907 expr: Some(body_id),
2908 }),
2909 ItemKind::Const(_, generics, ty, rhs) => ConstantItem(Box::new(Constant {
2910 generics: clean_generics(generics, cx),
2911 type_: clean_ty(ty, cx),
2912 kind: clean_const_item_rhs(rhs, def_id),
2913 })),
2914 ItemKind::TyAlias(_, generics, ty) => {
2915 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2916 let rustdoc_ty = clean_ty(ty, cx);
2917 let type_ =
2918 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, ty)), cx, None, None);
2919 let generics = clean_generics(generics, cx);
2920 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2921 *count -= 1;
2922 if *count == 0 {
2923 cx.current_type_aliases.remove(&def_id);
2924 }
2925 }
2926
2927 let ty = cx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
2928
2929 let mut ret = Vec::new();
2930 let inner_type = clean_ty_alias_inner_type(ty, cx, &mut ret);
2931
2932 ret.push(generate_item_with_correct_attrs(
2933 cx,
2934 TypeAliasItem(Box::new(TypeAlias {
2935 generics,
2936 inner_type,
2937 type_: rustdoc_ty,
2938 item_type: Some(type_),
2939 })),
2940 item.owner_id.def_id.to_def_id(),
2941 name,
2942 import_ids,
2943 renamed,
2944 ));
2945 return ret;
2946 }
2947 ItemKind::Enum(_, generics, def) => EnumItem(Enum {
2948 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2949 generics: clean_generics(generics, cx),
2950 }),
2951 ItemKind::TraitAlias(_, _, generics, bounds) => TraitAliasItem(TraitAlias {
2952 generics: clean_generics(generics, cx),
2953 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2954 }),
2955 ItemKind::Union(_, generics, variant_data) => UnionItem(Union {
2956 generics: clean_generics(generics, cx),
2957 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2958 }),
2959 ItemKind::Struct(_, generics, variant_data) => StructItem(Struct {
2960 ctor_kind: variant_data.ctor_kind(),
2961 generics: clean_generics(generics, cx),
2962 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2963 }),
2964 ItemKind::Macro(_, macro_def, kinds) => match kinds {
2965 MacroKinds::ATTR => clean_proc_macro(item, &mut name, MacroKind::Attr, cx.tcx),
2966 MacroKinds::DERIVE => clean_proc_macro(item, &mut name, MacroKind::Derive, cx.tcx),
2967 _ => MacroItem(
2968 Macro {
2969 source: display_macro_source(cx.tcx, name, macro_def),
2970 macro_rules: macro_def.macro_rules,
2971 },
2972 kinds,
2973 ),
2974 },
2975 ItemKind::Fn { ref sig, generics, body: body_id, .. } => {
2977 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2978 }
2979 ItemKind::Trait { generics, bounds, items: item_ids, .. } => {
2981 let items = item_ids
2982 .iter()
2983 .map(|&ti| clean_trait_item(cx.tcx.hir_trait_item(ti), cx))
2984 .collect();
2985
2986 TraitItem(Box::new(Trait {
2987 def_id,
2988 items,
2989 generics: clean_generics(generics, cx),
2990 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2991 }))
2992 }
2993 ItemKind::ExternCrate(orig_name, _) => {
2994 return clean_extern_crate(item, name, orig_name, cx);
2995 }
2996 _ => span_bug!(item.span, "not yet converted"),
2997 };
2998
2999 vec![generate_item_with_correct_attrs(
3000 cx,
3001 kind,
3002 item.owner_id.def_id.to_def_id(),
3003 name,
3004 import_ids,
3005 renamed,
3006 )]
3007 })
3008}
3009
3010fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
3011 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
3012 Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx.tcx)
3013}
3014
3015fn clean_impl<'tcx>(
3016 impl_: &hir::Impl<'tcx>,
3017 def_id: LocalDefId,
3018 cx: &mut DocContext<'tcx>,
3019 is_inlined: bool,
3023) -> Vec<Item> {
3024 let tcx = cx.tcx;
3025 let mut ret = Vec::new();
3026 let trait_ = match impl_.of_trait {
3027 Some(t) => {
3028 if is_inlined {
3029 return vec![Item::from_def_id_and_parts(
3030 def_id.to_def_id(),
3031 None,
3032 PlaceholderImplItem,
3033 tcx,
3034 )];
3035 }
3036 Some(clean_trait_ref(&t.trait_ref, cx))
3037 }
3038 None => None,
3039 };
3040 let items = impl_
3041 .items
3042 .iter()
3043 .map(|&ii| clean_impl_item(tcx.hir_impl_item(ii), cx))
3044 .collect::<Vec<_>>();
3045
3046 if trait_.as_ref().is_some_and(|t| tcx.lang_items().deref_trait() == Some(t.def_id()))
3049 && tcx.impl_polarity(def_id) != ty::ImplPolarity::Negative
3050 {
3051 build_deref_target_impls(cx, &items, &mut ret);
3052 }
3053
3054 let for_ = clean_ty(impl_.self_ty, cx);
3055 let type_alias =
3056 for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) {
3057 DefKind::TyAlias => Some(clean_middle_ty(
3058 ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity().skip_norm_wip()),
3059 cx,
3060 Some(def_id.to_def_id()),
3061 None,
3062 )),
3063 _ => None,
3064 });
3065 let is_deprecated = tcx
3066 .lookup_deprecation(def_id.to_def_id())
3067 .is_some_and(|deprecation| deprecation.is_in_effect());
3068 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
3069 let kind = ImplItem(Box::new(Impl {
3070 safety: match impl_.of_trait {
3071 Some(of_trait) => of_trait.safety,
3072 None => hir::Safety::Safe,
3073 },
3074 generics: clean_generics(impl_.generics, cx),
3075 trait_,
3076 for_,
3077 items,
3078 polarity: if impl_.of_trait.is_some() {
3079 tcx.impl_polarity(def_id)
3080 } else {
3081 ty::ImplPolarity::Positive
3082 },
3083 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), |d| d.fake_variadic.is_some()) {
3084 ImplKind::FakeVariadic
3085 } else {
3086 ImplKind::Normal
3087 },
3088 is_deprecated,
3089 }));
3090 Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, tcx)
3091 };
3092 if let Some(type_alias) = type_alias {
3093 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
3094 }
3095 ret.push(make_item(trait_, for_, items));
3096 ret
3097}
3098
3099fn clean_extern_crate<'tcx>(
3100 krate: &hir::Item<'tcx>,
3101 name: Symbol,
3102 orig_name: Option<Symbol>,
3103 cx: &mut DocContext<'tcx>,
3104) -> Vec<Item> {
3105 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
3107 let crate_def_id = cnum.as_def_id();
3109 let attrs = cx.tcx.hir_attrs(krate.hir_id());
3110 let ty_vis = cx.tcx.visibility(krate.owner_id);
3111 let please_inline = ty_vis.is_public()
3112 && attrs.iter().any(|a| {
3113 matches!(
3114 a,
3115 hir::Attribute::Parsed(AttributeKind::Doc(d))
3116 if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline))
3117 })
3118 && !cx.is_json_output();
3119
3120 let krate_owner_def_id = krate.owner_id.def_id;
3121
3122 if please_inline
3123 && let Some(items) = inline::try_inline(
3124 cx,
3125 Res::Def(DefKind::Mod, crate_def_id),
3126 name,
3127 Some((attrs, Some(krate_owner_def_id))),
3128 &mut Default::default(),
3129 )
3130 {
3131 return items;
3132 }
3133
3134 vec![Item::from_def_id_and_parts(
3135 krate_owner_def_id.to_def_id(),
3136 Some(name),
3137 ExternCrateItem { src: orig_name },
3138 cx.tcx,
3139 )]
3140}
3141
3142fn clean_use_statement<'tcx>(
3143 import: &hir::Item<'tcx>,
3144 name: Option<Symbol>,
3145 path: &hir::UsePath<'tcx>,
3146 kind: hir::UseKind,
3147 cx: &mut DocContext<'tcx>,
3148 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3149) -> Vec<Item> {
3150 let mut items = Vec::new();
3151 let hir::UsePath { segments, ref res, span } = *path;
3152 for res in res.present_items() {
3153 let path = hir::Path { segments, res, span };
3154 items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
3155 }
3156 items
3157}
3158
3159fn clean_use_statement_inner<'tcx>(
3160 import: &hir::Item<'tcx>,
3161 name: Option<Symbol>,
3162 path: &hir::Path<'tcx>,
3163 kind: hir::UseKind,
3164 cx: &mut DocContext<'tcx>,
3165 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3166) -> Vec<Item> {
3167 if should_ignore_res(path.res) {
3168 return Vec::new();
3169 }
3170 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
3174 return Vec::new();
3175 }
3176
3177 let visibility = cx.tcx.visibility(import.owner_id);
3178 let attrs = cx.tcx.hir_attrs(import.hir_id());
3179 let inline_attr = find_attr!(
3180 attrs,
3181 Doc(d) if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline) => d
3182 )
3183 .and_then(|d| d.inline.first());
3184 let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
3185 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
3186 let import_def_id = import.owner_id.def_id;
3187
3188 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
3192
3193 let is_visible_from_parent_mod =
3199 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3200
3201 if pub_underscore && let Some((_, inline_span)) = inline_attr {
3202 struct_span_code_err!(
3203 cx.tcx.dcx(),
3204 *inline_span,
3205 E0780,
3206 "anonymous imports cannot be inlined"
3207 )
3208 .with_span_label(import.span, "anonymous import")
3209 .emit();
3210 }
3211
3212 let mut denied = cx.is_json_output()
3217 || !(visibility.is_public() || (cx.document_private() && is_visible_from_parent_mod))
3218 || pub_underscore
3219 || attrs.iter().any(|a| matches!(
3220 a,
3221 hir::Attribute::Parsed(AttributeKind::Doc(d))
3222 if d.hidden.is_some() || d.inline.first().is_some_and(|(i, _)| *i == DocInline::NoInline)
3223 ));
3224
3225 let path = clean_path(path, cx);
3228 let inner = if kind == hir::UseKind::Glob {
3229 if !denied {
3230 let mut visited = DefIdSet::default();
3231 if let Some(items) = inline::try_inline_glob(
3232 cx,
3233 path.res,
3234 current_mod,
3235 &mut visited,
3236 inlined_names,
3237 import,
3238 ) {
3239 return items;
3240 }
3241 }
3242 Import::new_glob(resolve_use_source(cx, path), true)
3243 } else {
3244 let name = name.unwrap();
3245 if inline_attr.is_none()
3246 && let Res::Def(DefKind::Mod, did) = path.res
3247 && !did.is_local()
3248 && did.is_crate_root()
3249 {
3250 denied = true;
3253 }
3254 if !denied
3255 && let Some(mut items) = inline::try_inline(
3256 cx,
3257 path.res,
3258 name,
3259 Some((attrs, Some(import_def_id))),
3260 &mut Default::default(),
3261 )
3262 {
3263 items.push(Item::from_def_id_and_parts(
3264 import_def_id.to_def_id(),
3265 None,
3266 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3267 cx.tcx,
3268 ));
3269 return items;
3270 }
3271 Import::new_simple(name, resolve_use_source(cx, path), true)
3272 };
3273
3274 vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx.tcx)]
3275}
3276
3277fn clean_maybe_renamed_foreign_item<'tcx>(
3278 cx: &mut DocContext<'tcx>,
3279 item: &hir::ForeignItem<'tcx>,
3280 renamed: Option<Symbol>,
3281 import_id: Option<LocalDefId>,
3282) -> Item {
3283 let def_id = item.owner_id.to_def_id();
3284 cx.with_param_env(def_id, |cx| {
3285 let kind = match item.kind {
3286 hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3287 clean_function(cx, &sig, generics, ParamsSrc::Idents(idents), def_id),
3288 sig.header.safety(),
3289 ),
3290 hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3291 Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3292 safety,
3293 ),
3294 hir::ForeignItemKind::Type => ForeignTypeItem,
3295 };
3296
3297 let mut clean_item = generate_item_with_correct_attrs(
3298 cx,
3299 kind,
3300 item.owner_id.def_id.to_def_id(),
3301 item.ident.name,
3302 import_id.as_slice(),
3303 renamed,
3304 );
3305 let mut attrs = Attributes::from_hir(inline::load_attrs(
3307 cx.tcx,
3308 cx.tcx.hir_owner_parent(item.owner_id).owner.to_def_id(),
3309 ));
3310 attrs.merge_with(std::mem::take(&mut clean_item.inner.attrs));
3311 clean_item.inner.attrs = attrs;
3312 clean_item
3313 })
3314}
3315
3316fn clean_assoc_item_constraint<'tcx>(
3317 trait_did: DefId,
3318 constraint: &hir::AssocItemConstraint<'tcx>,
3319 cx: &mut DocContext<'tcx>,
3320) -> AssocItemConstraint {
3321 AssocItemConstraint {
3322 assoc: PathSegment {
3323 name: constraint.ident.name,
3324 args: clean_generic_args(None, constraint.gen_args, cx),
3325 },
3326 kind: match constraint.kind {
3327 hir::AssocItemConstraintKind::Equality { ref term } => {
3328 let assoc_tag = match term {
3329 hir::Term::Ty(_) => ty::AssocTag::Type,
3330 hir::Term::Const(_) => ty::AssocTag::Const,
3331 };
3332 let assoc_item = cx
3333 .tcx
3334 .associated_items(trait_did)
3335 .find_by_ident_and_kind(cx.tcx, constraint.ident, assoc_tag, trait_did)
3336 .map(|item| item.def_id);
3337 AssocItemConstraintKind::Equality { term: clean_hir_term(assoc_item, term, cx) }
3338 }
3339 hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3340 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3341 },
3342 },
3343 }
3344}
3345
3346fn clean_bound_vars<'tcx>(
3347 bound_vars: &ty::List<ty::BoundVariableKind<'tcx>>,
3348 tcx: TyCtxt<'tcx>,
3349) -> Vec<GenericParamDef> {
3350 bound_vars
3351 .into_iter()
3352 .filter_map(|var| match var {
3353 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
3354 let name = tcx.item_name(def_id);
3355 if name != kw::UnderscoreLifetime {
3356 Some(GenericParamDef::lifetime(def_id, name))
3357 } else {
3358 None
3359 }
3360 }
3361 ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
3362 let name = tcx.item_name(def_id);
3363 Some(GenericParamDef {
3364 name,
3365 def_id,
3366 kind: GenericParamDefKind::Type {
3367 bounds: ThinVec::new(),
3368 default: None,
3369 synthetic: false,
3370 },
3371 })
3372 }
3373 ty::BoundVariableKind::Const => None,
3375 _ => None,
3376 })
3377 .collect()
3378}