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