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