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