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