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_ast::token::{Token, TokenKind};
38use rustc_ast::tokenstream::{TokenStream, TokenTree};
39use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry};
40use rustc_errors::codes::*;
41use rustc_errors::{FatalError, struct_span_code_err};
42use rustc_hir::PredicateOrigin;
43use rustc_hir::def::{CtorKind, DefKind, Res};
44use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE, LocalDefId};
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 thin_vec::ThinVec;
56use tracing::{debug, instrument};
57use utils::*;
58use {rustc_ast as ast, rustc_hir as hir};
59
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)| {
70 let item = clean_maybe_renamed_foreign_item(cx, item, *renamed);
71 if let Some(name) = item.name
72 && (cx.render_options.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.render_options.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_id)| {
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_id);
103 for item in &v {
104 if let Some(name) = item.name
105 && (cx.render_options.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,
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_id: Option<LocalDefId>,
186 renamed: Option<Symbol>,
187) -> Item {
188 let target_attrs = inline::load_attrs(cx, def_id);
189 let attrs = if let Some(import_id) = import_id {
190 let is_inline = hir_attr_lists(inline::load_attrs(cx, import_id.to_def_id()), sym::doc)
196 .get_word_attr(sym::inline)
197 .is_some()
198 || (is_glob_import(cx.tcx, import_id)
199 && (cx.render_options.document_hidden || !cx.tcx.is_doc_hidden(def_id)));
200 let mut attrs = get_all_import_attributes(cx, import_id, def_id, is_inline);
201 add_without_unwanted_attributes(&mut attrs, target_attrs, is_inline, None);
202 attrs
203 } else {
204 target_attrs.iter().map(|attr| (Cow::Borrowed(attr), None)).collect()
206 };
207 let cfg = extract_cfg_from_attrs(
208 attrs.iter().map(move |(attr, _)| match attr {
209 Cow::Borrowed(attr) => *attr,
210 Cow::Owned(attr) => attr,
211 }),
212 cx.tcx,
213 &cx.cache.hidden_cfg,
214 );
215 let attrs = Attributes::from_hir_iter(attrs.iter().map(|(attr, did)| (&**attr, *did)), false);
216
217 let name = renamed.or(Some(name));
218 let mut item = Item::from_def_id_and_attrs_and_parts(def_id, name, kind, attrs, cfg);
219 item.inner.inline_stmt_id = import_id;
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 = cx.tcx.def_kind(trait_ref.def_id()).into();
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()),
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<'tcx>(
308 constant: &hir::ConstArg<'tcx>,
309 _cx: &mut DocContext<'tcx>,
310) -> ConstantKind {
311 match &constant.kind {
312 hir::ConstArgKind::Path(qpath) => {
313 ConstantKind::Path { path: qpath_to_string(qpath).into() }
314 }
315 hir::ConstArgKind::Anon(anon) => ConstantKind::Anonymous { body: anon.body },
316 hir::ConstArgKind::Infer(..) => ConstantKind::Infer,
317 }
318}
319
320pub(crate) fn clean_middle_const<'tcx>(
321 constant: ty::Binder<'tcx, ty::Const<'tcx>>,
322 _cx: &mut DocContext<'tcx>,
323) -> ConstantKind {
324 ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() }
326}
327
328pub(crate) fn clean_middle_region(region: ty::Region<'_>) -> Option<Lifetime> {
329 match region.kind() {
330 ty::ReStatic => Some(Lifetime::statik()),
331 _ if !region.has_name() => None,
332 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(_, name), .. }) => {
333 Some(Lifetime(name))
334 }
335 ty::ReEarlyParam(ref data) => Some(Lifetime(data.name)),
336 ty::ReBound(..)
337 | ty::ReLateParam(..)
338 | ty::ReVar(..)
339 | ty::ReError(_)
340 | ty::RePlaceholder(..)
341 | ty::ReErased => {
342 debug!("cannot clean region {region:?}");
343 None
344 }
345 }
346}
347
348fn clean_where_predicate<'tcx>(
349 predicate: &hir::WherePredicate<'tcx>,
350 cx: &mut DocContext<'tcx>,
351) -> Option<WherePredicate> {
352 if !predicate.kind.in_where_clause() {
353 return None;
354 }
355 Some(match predicate.kind {
356 hir::WherePredicateKind::BoundPredicate(wbp) => {
357 let bound_params = wbp
358 .bound_generic_params
359 .iter()
360 .map(|param| clean_generic_param(cx, None, param))
361 .collect();
362 WherePredicate::BoundPredicate {
363 ty: clean_ty(wbp.bounded_ty, cx),
364 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
365 bound_params,
366 }
367 }
368
369 hir::WherePredicateKind::RegionPredicate(wrp) => WherePredicate::RegionPredicate {
370 lifetime: clean_lifetime(wrp.lifetime, cx),
371 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
372 },
373
374 hir::WherePredicateKind::EqPredicate(_) => bug!("EqPredicate"),
377 })
378}
379
380pub(crate) fn clean_predicate<'tcx>(
381 predicate: ty::Clause<'tcx>,
382 cx: &mut DocContext<'tcx>,
383) -> Option<WherePredicate> {
384 let bound_predicate = predicate.kind();
385 match bound_predicate.skip_binder() {
386 ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_predicate.rebind(pred), cx),
387 ty::ClauseKind::RegionOutlives(pred) => Some(clean_region_outlives_predicate(pred)),
388 ty::ClauseKind::TypeOutlives(pred) => {
389 Some(clean_type_outlives_predicate(bound_predicate.rebind(pred), cx))
390 }
391 ty::ClauseKind::Projection(pred) => {
392 Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
393 }
394 ty::ClauseKind::ConstEvaluatable(..)
396 | ty::ClauseKind::WellFormed(..)
397 | ty::ClauseKind::ConstArgHasType(..)
398 | ty::ClauseKind::HostEffect(_) => None,
400 }
401}
402
403fn clean_poly_trait_predicate<'tcx>(
404 pred: ty::PolyTraitPredicate<'tcx>,
405 cx: &mut DocContext<'tcx>,
406) -> Option<WherePredicate> {
407 if Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait() {
410 return None;
411 }
412
413 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
414 Some(WherePredicate::BoundPredicate {
415 ty: clean_middle_ty(poly_trait_ref.self_ty(), cx, None, None),
416 bounds: vec![clean_poly_trait_ref_with_constraints(cx, poly_trait_ref, ThinVec::new())],
417 bound_params: Vec::new(),
418 })
419}
420
421fn clean_region_outlives_predicate(pred: ty::RegionOutlivesPredicate<'_>) -> WherePredicate {
422 let ty::OutlivesPredicate(a, b) = pred;
423
424 WherePredicate::RegionPredicate {
425 lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
426 bounds: vec![GenericBound::Outlives(
427 clean_middle_region(b).expect("failed to clean bounds"),
428 )],
429 }
430}
431
432fn clean_type_outlives_predicate<'tcx>(
433 pred: ty::Binder<'tcx, ty::TypeOutlivesPredicate<'tcx>>,
434 cx: &mut DocContext<'tcx>,
435) -> WherePredicate {
436 let ty::OutlivesPredicate(ty, lt) = pred.skip_binder();
437
438 WherePredicate::BoundPredicate {
439 ty: clean_middle_ty(pred.rebind(ty), cx, None, None),
440 bounds: vec![GenericBound::Outlives(
441 clean_middle_region(lt).expect("failed to clean lifetimes"),
442 )],
443 bound_params: Vec::new(),
444 }
445}
446
447fn clean_middle_term<'tcx>(
448 term: ty::Binder<'tcx, ty::Term<'tcx>>,
449 cx: &mut DocContext<'tcx>,
450) -> Term {
451 match term.skip_binder().kind() {
452 ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(term.rebind(ty), cx, None, None)),
453 ty::TermKind::Const(c) => Term::Constant(clean_middle_const(term.rebind(c), cx)),
454 }
455}
456
457fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
458 match term {
459 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
460 hir::Term::Const(c) => {
461 let ct = lower_const_arg_for_rustdoc(cx.tcx, c, FeedConstTy::No);
462 Term::Constant(clean_middle_const(ty::Binder::dummy(ct), cx))
463 }
464 }
465}
466
467fn clean_projection_predicate<'tcx>(
468 pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
469 cx: &mut DocContext<'tcx>,
470) -> WherePredicate {
471 WherePredicate::EqPredicate {
472 lhs: clean_projection(pred.map_bound(|p| p.projection_term), cx, None),
473 rhs: clean_middle_term(pred.map_bound(|p| p.term), cx),
474 }
475}
476
477fn clean_projection<'tcx>(
478 proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
479 cx: &mut DocContext<'tcx>,
480 parent_def_id: Option<DefId>,
481) -> QPathData {
482 let trait_ = clean_trait_ref_with_constraints(
483 cx,
484 proj.map_bound(|proj| proj.trait_ref(cx.tcx)),
485 ThinVec::new(),
486 );
487 let self_type = clean_middle_ty(proj.map_bound(|proj| proj.self_ty()), cx, None, None);
488 let self_def_id = match parent_def_id {
489 Some(parent_def_id) => cx.tcx.opt_parent(parent_def_id).or(Some(parent_def_id)),
490 None => self_type.def_id(&cx.cache),
491 };
492 let should_fully_qualify = should_fully_qualify_path(self_def_id, &trait_, &self_type);
493
494 QPathData {
495 assoc: projection_to_path_segment(proj, cx),
496 self_type,
497 should_fully_qualify,
498 trait_: Some(trait_),
499 }
500}
501
502fn should_fully_qualify_path(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
503 !trait_.segments.is_empty()
504 && self_def_id
505 .zip(Some(trait_.def_id()))
506 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
507}
508
509fn projection_to_path_segment<'tcx>(
510 proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
511 cx: &mut DocContext<'tcx>,
512) -> PathSegment {
513 let def_id = proj.skip_binder().def_id;
514 let generics = cx.tcx.generics_of(def_id);
515 PathSegment {
516 name: cx.tcx.item_name(def_id),
517 args: GenericArgs::AngleBracketed {
518 args: clean_middle_generic_args(
519 cx,
520 proj.map_bound(|ty| &ty.args[generics.parent_count..]),
521 false,
522 def_id,
523 ),
524 constraints: Default::default(),
525 },
526 }
527}
528
529fn clean_generic_param_def(
530 def: &ty::GenericParamDef,
531 defaults: ParamDefaults,
532 cx: &mut DocContext<'_>,
533) -> GenericParamDef {
534 let (name, kind) = match def.kind {
535 ty::GenericParamDefKind::Lifetime => {
536 (def.name, GenericParamDefKind::Lifetime { outlives: ThinVec::new() })
537 }
538 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
539 let default = if let ParamDefaults::Yes = defaults
540 && has_default
541 {
542 Some(clean_middle_ty(
543 ty::Binder::dummy(cx.tcx.type_of(def.def_id).instantiate_identity()),
544 cx,
545 Some(def.def_id),
546 None,
547 ))
548 } else {
549 None
550 };
551 (
552 def.name,
553 GenericParamDefKind::Type {
554 bounds: ThinVec::new(), default: default.map(Box::new),
556 synthetic,
557 },
558 )
559 }
560 ty::GenericParamDefKind::Const { has_default, synthetic } => (
561 def.name,
562 GenericParamDefKind::Const {
563 ty: Box::new(clean_middle_ty(
564 ty::Binder::dummy(
565 cx.tcx
566 .type_of(def.def_id)
567 .no_bound_vars()
568 .expect("const parameter types cannot be generic"),
569 ),
570 cx,
571 Some(def.def_id),
572 None,
573 )),
574 default: if let ParamDefaults::Yes = defaults
575 && has_default
576 {
577 Some(Box::new(
578 cx.tcx.const_param_default(def.def_id).instantiate_identity().to_string(),
579 ))
580 } else {
581 None
582 },
583 synthetic,
584 },
585 ),
586 };
587
588 GenericParamDef { name, def_id: def.def_id, kind }
589}
590
591enum ParamDefaults {
593 Yes,
594 No,
595}
596
597fn clean_generic_param<'tcx>(
598 cx: &mut DocContext<'tcx>,
599 generics: Option<&hir::Generics<'tcx>>,
600 param: &hir::GenericParam<'tcx>,
601) -> GenericParamDef {
602 let (name, kind) = match param.kind {
603 hir::GenericParamKind::Lifetime { .. } => {
604 let outlives = if let Some(generics) = generics {
605 generics
606 .outlives_for_param(param.def_id)
607 .filter(|bp| !bp.in_where_clause)
608 .flat_map(|bp| bp.bounds)
609 .map(|bound| match bound {
610 hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
611 _ => panic!(),
612 })
613 .collect()
614 } else {
615 ThinVec::new()
616 };
617 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
618 }
619 hir::GenericParamKind::Type { ref default, synthetic } => {
620 let bounds = if let Some(generics) = generics {
621 generics
622 .bounds_for_param(param.def_id)
623 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
624 .flat_map(|bp| bp.bounds)
625 .filter_map(|x| clean_generic_bound(x, cx))
626 .collect()
627 } else {
628 ThinVec::new()
629 };
630 (
631 param.name.ident().name,
632 GenericParamDefKind::Type {
633 bounds,
634 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
635 synthetic,
636 },
637 )
638 }
639 hir::GenericParamKind::Const { ty, default, synthetic } => (
640 param.name.ident().name,
641 GenericParamDefKind::Const {
642 ty: Box::new(clean_ty(ty, cx)),
643 default: default.map(|ct| {
644 Box::new(lower_const_arg_for_rustdoc(cx.tcx, ct, FeedConstTy::No).to_string())
645 }),
646 synthetic,
647 },
648 ),
649 };
650
651 GenericParamDef { name, def_id: param.def_id.to_def_id(), kind }
652}
653
654fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
658 match param.kind {
659 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
660 _ => false,
661 }
662}
663
664fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
668 matches!(
669 param.kind,
670 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) }
671 )
672}
673
674pub(crate) fn clean_generics<'tcx>(
675 gens: &hir::Generics<'tcx>,
676 cx: &mut DocContext<'tcx>,
677) -> Generics {
678 let impl_trait_params = gens
679 .params
680 .iter()
681 .filter(|param| is_impl_trait(param))
682 .map(|param| {
683 let param = clean_generic_param(cx, Some(gens), param);
684 match param.kind {
685 GenericParamDefKind::Lifetime { .. } => unreachable!(),
686 GenericParamDefKind::Type { ref bounds, .. } => {
687 cx.impl_trait_bounds.insert(param.def_id.into(), bounds.to_vec());
688 }
689 GenericParamDefKind::Const { .. } => unreachable!(),
690 }
691 param
692 })
693 .collect::<Vec<_>>();
694
695 let mut bound_predicates = FxIndexMap::default();
696 let mut region_predicates = FxIndexMap::default();
697 let mut eq_predicates = ThinVec::default();
698 for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
699 match pred {
700 WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
701 match bound_predicates.entry(ty) {
702 IndexEntry::Vacant(v) => {
703 v.insert((bounds, bound_params));
704 }
705 IndexEntry::Occupied(mut o) => {
706 for bound in bounds {
708 if !o.get().0.contains(&bound) {
709 o.get_mut().0.push(bound);
710 }
711 }
712 for bound_param in bound_params {
713 if !o.get().1.contains(&bound_param) {
714 o.get_mut().1.push(bound_param);
715 }
716 }
717 }
718 }
719 }
720 WherePredicate::RegionPredicate { lifetime, bounds } => {
721 match region_predicates.entry(lifetime) {
722 IndexEntry::Vacant(v) => {
723 v.insert(bounds);
724 }
725 IndexEntry::Occupied(mut o) => {
726 for bound in bounds {
728 if !o.get().contains(&bound) {
729 o.get_mut().push(bound);
730 }
731 }
732 }
733 }
734 }
735 WherePredicate::EqPredicate { lhs, rhs } => {
736 eq_predicates.push(WherePredicate::EqPredicate { lhs, rhs });
737 }
738 }
739 }
740
741 let mut params = ThinVec::with_capacity(gens.params.len());
742 for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
746 let mut p = clean_generic_param(cx, Some(gens), p);
747 match &mut p.kind {
748 GenericParamDefKind::Lifetime { outlives } => {
749 if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
750 for outlive in outlives.drain(..) {
752 let outlive = GenericBound::Outlives(outlive);
753 if !region_pred.contains(&outlive) {
754 region_pred.push(outlive);
755 }
756 }
757 }
758 }
759 GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
760 if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
761 for bound in bounds.drain(..) {
763 if !bound_pred.0.contains(&bound) {
764 bound_pred.0.push(bound);
765 }
766 }
767 }
768 }
769 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
770 }
772 }
773 params.push(p);
774 }
775 params.extend(impl_trait_params);
776
777 Generics {
778 params,
779 where_predicates: bound_predicates
780 .into_iter()
781 .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
782 ty,
783 bounds,
784 bound_params,
785 })
786 .chain(
787 region_predicates
788 .into_iter()
789 .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
790 )
791 .chain(eq_predicates)
792 .collect(),
793 }
794}
795
796fn clean_ty_generics<'tcx>(cx: &mut DocContext<'tcx>, def_id: DefId) -> Generics {
797 clean_ty_generics_inner(cx, cx.tcx.generics_of(def_id), cx.tcx.explicit_predicates_of(def_id))
798}
799
800fn clean_ty_generics_inner<'tcx>(
801 cx: &mut DocContext<'tcx>,
802 gens: &ty::Generics,
803 preds: ty::GenericPredicates<'tcx>,
804) -> Generics {
805 let mut impl_trait = BTreeMap::<u32, Vec<GenericBound>>::default();
808
809 let params: ThinVec<_> = gens
810 .own_params
811 .iter()
812 .filter(|param| match param.kind {
813 ty::GenericParamDefKind::Lifetime => !param.is_anonymous_lifetime(),
814 ty::GenericParamDefKind::Type { synthetic, .. } => {
815 if param.name == kw::SelfUpper {
816 debug_assert_eq!(param.index, 0);
817 return false;
818 }
819 if synthetic {
820 impl_trait.insert(param.index, vec![]);
821 return false;
822 }
823 true
824 }
825 ty::GenericParamDefKind::Const { .. } => true,
826 })
827 .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx))
828 .collect();
829
830 let mut impl_trait_proj =
832 FxHashMap::<u32, Vec<(DefId, PathSegment, ty::Binder<'_, ty::Term<'_>>)>>::default();
833
834 let where_predicates = preds
835 .predicates
836 .iter()
837 .flat_map(|(pred, _)| {
838 let mut proj_pred = None;
839 let param_idx = {
840 let bound_p = pred.kind();
841 match bound_p.skip_binder() {
842 ty::ClauseKind::Trait(pred) if let ty::Param(param) = pred.self_ty().kind() => {
843 Some(param.index)
844 }
845 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg))
846 if let ty::Param(param) = ty.kind() =>
847 {
848 Some(param.index)
849 }
850 ty::ClauseKind::Projection(p)
851 if let ty::Param(param) = p.projection_term.self_ty().kind() =>
852 {
853 proj_pred = Some(bound_p.rebind(p));
854 Some(param.index)
855 }
856 _ => None,
857 }
858 };
859
860 if let Some(param_idx) = param_idx
861 && let Some(bounds) = impl_trait.get_mut(¶m_idx)
862 {
863 let pred = clean_predicate(*pred, cx)?;
864
865 bounds.extend(pred.get_bounds().into_iter().flatten().cloned());
866
867 if let Some(pred) = proj_pred {
868 let lhs = clean_projection(pred.map_bound(|p| p.projection_term), cx, None);
869 impl_trait_proj.entry(param_idx).or_default().push((
870 lhs.trait_.unwrap().def_id(),
871 lhs.assoc,
872 pred.map_bound(|p| p.term),
873 ));
874 }
875
876 return None;
877 }
878
879 Some(pred)
880 })
881 .collect::<Vec<_>>();
882
883 for (idx, mut bounds) in impl_trait {
884 let mut has_sized = false;
885 bounds.retain(|b| {
886 if b.is_sized_bound(cx) {
887 has_sized = true;
888 false
889 } else {
890 true
891 }
892 });
893 if !has_sized {
894 bounds.push(GenericBound::maybe_sized(cx));
895 }
896
897 bounds.sort_by_key(|b| !b.is_trait_bound());
899
900 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
903 bounds.insert(0, GenericBound::sized(cx));
904 }
905
906 if let Some(proj) = impl_trait_proj.remove(&idx) {
907 for (trait_did, name, rhs) in proj {
908 let rhs = clean_middle_term(rhs, cx);
909 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
910 }
911 }
912
913 cx.impl_trait_bounds.insert(idx.into(), bounds);
914 }
915
916 let where_predicates =
919 where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect();
920
921 let mut generics = Generics { params, where_predicates };
922 simplify::sized_bounds(cx, &mut generics);
923 generics.where_predicates = simplify::where_clauses(cx, generics.where_predicates);
924 generics
925}
926
927fn clean_ty_alias_inner_type<'tcx>(
928 ty: Ty<'tcx>,
929 cx: &mut DocContext<'tcx>,
930 ret: &mut Vec<Item>,
931) -> Option<TypeAliasInnerType> {
932 let ty::Adt(adt_def, args) = ty.kind() else {
933 return None;
934 };
935
936 if !adt_def.did().is_local() {
937 cx.with_param_env(adt_def.did(), |cx| {
938 inline::build_impls(cx, adt_def.did(), None, ret);
939 });
940 }
941
942 Some(if adt_def.is_enum() {
943 let variants: rustc_index::IndexVec<_, _> = adt_def
944 .variants()
945 .iter()
946 .map(|variant| clean_variant_def_with_args(variant, args, cx))
947 .collect();
948
949 if !adt_def.did().is_local() {
950 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Enum);
951 }
952
953 TypeAliasInnerType::Enum {
954 variants,
955 is_non_exhaustive: adt_def.is_variant_list_non_exhaustive(),
956 }
957 } else {
958 let variant = adt_def
959 .variants()
960 .iter()
961 .next()
962 .unwrap_or_else(|| bug!("a struct or union should always have one variant def"));
963
964 let fields: Vec<_> =
965 clean_variant_def_with_args(variant, args, cx).kind.inner_items().cloned().collect();
966
967 if adt_def.is_struct() {
968 if !adt_def.did().is_local() {
969 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Struct);
970 }
971 TypeAliasInnerType::Struct { ctor_kind: variant.ctor_kind(), fields }
972 } else {
973 if !adt_def.did().is_local() {
974 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Union);
975 }
976 TypeAliasInnerType::Union { fields }
977 }
978 })
979}
980
981fn clean_proc_macro<'tcx>(
982 item: &hir::Item<'tcx>,
983 name: &mut Symbol,
984 kind: MacroKind,
985 cx: &mut DocContext<'tcx>,
986) -> ItemKind {
987 let attrs = cx.tcx.hir_attrs(item.hir_id());
988 if kind == MacroKind::Derive
989 && let Some(derive_name) =
990 hir_attr_lists(attrs, sym::proc_macro_derive).find_map(|mi| mi.ident())
991 {
992 *name = derive_name.name;
993 }
994
995 let mut helpers = Vec::new();
996 for mi in hir_attr_lists(attrs, sym::proc_macro_derive) {
997 if !mi.has_name(sym::attributes) {
998 continue;
999 }
1000
1001 if let Some(list) = mi.meta_item_list() {
1002 for inner_mi in list {
1003 if let Some(ident) = inner_mi.ident() {
1004 helpers.push(ident.name);
1005 }
1006 }
1007 }
1008 }
1009 ProcMacroItem(ProcMacro { kind, helpers })
1010}
1011
1012fn clean_fn_or_proc_macro<'tcx>(
1013 item: &hir::Item<'tcx>,
1014 sig: &hir::FnSig<'tcx>,
1015 generics: &hir::Generics<'tcx>,
1016 body_id: hir::BodyId,
1017 name: &mut Symbol,
1018 cx: &mut DocContext<'tcx>,
1019) -> ItemKind {
1020 let attrs = cx.tcx.hir_attrs(item.hir_id());
1021 let macro_kind = attrs.iter().find_map(|a| {
1022 if a.has_name(sym::proc_macro) {
1023 Some(MacroKind::Bang)
1024 } else if a.has_name(sym::proc_macro_derive) {
1025 Some(MacroKind::Derive)
1026 } else if a.has_name(sym::proc_macro_attribute) {
1027 Some(MacroKind::Attr)
1028 } else {
1029 None
1030 }
1031 });
1032 match macro_kind {
1033 Some(kind) => clean_proc_macro(item, name, kind, cx),
1034 None => {
1035 let mut func = clean_function(cx, sig, generics, ParamsSrc::Body(body_id));
1036 clean_fn_decl_legacy_const_generics(&mut func, attrs);
1037 FunctionItem(func)
1038 }
1039 }
1040}
1041
1042fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) {
1046 for meta_item_list in attrs
1047 .iter()
1048 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
1049 .filter_map(|a| a.meta_item_list())
1050 {
1051 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.lit()).enumerate() {
1052 match literal.kind {
1053 ast::LitKind::Int(a, _) => {
1054 let GenericParamDef { name, kind, .. } = func.generics.params.remove(0);
1055 if let GenericParamDefKind::Const { ty, .. } = kind {
1056 func.decl.inputs.insert(
1057 a.get() as _,
1058 Parameter { name: Some(name), type_: *ty, is_const: true },
1059 );
1060 } else {
1061 panic!("unexpected non const in position {pos}");
1062 }
1063 }
1064 _ => panic!("invalid arg index"),
1065 }
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: ConstantKind::Local { def_id: local_did, body: default },
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, None)
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)
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: ConstantKind::Local { def_id: local_did, body: expr },
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 = cx.tcx.defaultness(impl_.owner_id);
1270 MethodItem(m, Some(defaultness))
1271 }
1272 hir::ImplItemKind::Type(hir_ty) => {
1273 let type_ = clean_ty(hir_ty, cx);
1274 let generics = clean_generics(impl_.generics, cx);
1275 let item_type =
1276 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1277 AssocTypeItem(
1278 Box::new(TypeAlias {
1279 type_,
1280 generics,
1281 inner_type: None,
1282 item_type: Some(item_type),
1283 }),
1284 Vec::new(),
1285 )
1286 }
1287 };
1288
1289 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1290 })
1291}
1292
1293pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1294 let tcx = cx.tcx;
1295 let kind = match assoc_item.kind {
1296 ty::AssocKind::Const { .. } => {
1297 let ty = clean_middle_ty(
1298 ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()),
1299 cx,
1300 Some(assoc_item.def_id),
1301 None,
1302 );
1303
1304 let mut generics = clean_ty_generics(cx, assoc_item.def_id);
1305 simplify::move_bounds_to_generic_parameters(&mut generics);
1306
1307 match assoc_item.container {
1308 ty::AssocItemContainer::Impl => ImplAssocConstItem(Box::new(Constant {
1309 generics,
1310 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1311 type_: ty,
1312 })),
1313 ty::AssocItemContainer::Trait => {
1314 if tcx.defaultness(assoc_item.def_id).has_value() {
1315 ProvidedAssocConstItem(Box::new(Constant {
1316 generics,
1317 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1318 type_: ty,
1319 }))
1320 } else {
1321 RequiredAssocConstItem(generics, Box::new(ty))
1322 }
1323 }
1324 }
1325 }
1326 ty::AssocKind::Fn { has_self, .. } => {
1327 let mut item = inline::build_function(cx, assoc_item.def_id);
1328
1329 if has_self {
1330 let self_ty = match assoc_item.container {
1331 ty::AssocItemContainer::Impl => {
1332 tcx.type_of(assoc_item.container_id(tcx)).instantiate_identity()
1333 }
1334 ty::AssocItemContainer::Trait => tcx.types.self_param,
1335 };
1336 let self_param_ty =
1337 tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder();
1338 if self_param_ty == self_ty {
1339 item.decl.inputs[0].type_ = SelfTy;
1340 } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1341 && ty == self_ty
1342 {
1343 match item.decl.inputs[0].type_ {
1344 BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1345 _ => unreachable!(),
1346 }
1347 }
1348 }
1349
1350 let provided = match assoc_item.container {
1351 ty::AssocItemContainer::Impl => true,
1352 ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1353 };
1354 if provided {
1355 let defaultness = match assoc_item.container {
1356 ty::AssocItemContainer::Impl => Some(assoc_item.defaultness(tcx)),
1357 ty::AssocItemContainer::Trait => None,
1358 };
1359 MethodItem(item, defaultness)
1360 } else {
1361 RequiredMethodItem(item)
1362 }
1363 }
1364 ty::AssocKind::Type { .. } => {
1365 let my_name = assoc_item.name();
1366
1367 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1368 match (¶m.kind, arg) {
1369 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1370 if *ty == param.name =>
1371 {
1372 true
1373 }
1374 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1375 if *lt == param.name =>
1376 {
1377 true
1378 }
1379 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1380 ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1381 _ => false,
1382 },
1383 _ => false,
1384 }
1385 }
1386
1387 let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1388 if let ty::AssocItemContainer::Trait = assoc_item.container {
1389 let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied();
1390 predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied()));
1391 }
1392 let mut generics = clean_ty_generics_inner(
1393 cx,
1394 tcx.generics_of(assoc_item.def_id),
1395 ty::GenericPredicates { parent: None, predicates },
1396 );
1397 simplify::move_bounds_to_generic_parameters(&mut generics);
1398
1399 if let ty::AssocItemContainer::Trait = assoc_item.container {
1400 let mut bounds: Vec<GenericBound> = Vec::new();
1405 generics.where_predicates.retain_mut(|pred| match *pred {
1406 WherePredicate::BoundPredicate {
1407 ty:
1408 QPath(box QPathData {
1409 ref assoc,
1410 ref self_type,
1411 trait_: Some(ref trait_),
1412 ..
1413 }),
1414 bounds: ref mut pred_bounds,
1415 ..
1416 } => {
1417 if assoc.name != my_name {
1418 return true;
1419 }
1420 if trait_.def_id() != assoc_item.container_id(tcx) {
1421 return true;
1422 }
1423 if *self_type != SelfTy {
1424 return true;
1425 }
1426 match &assoc.args {
1427 GenericArgs::AngleBracketed { args, constraints } => {
1428 if !constraints.is_empty()
1429 || generics
1430 .params
1431 .iter()
1432 .zip(args.iter())
1433 .any(|(param, arg)| !param_eq_arg(param, arg))
1434 {
1435 return true;
1436 }
1437 }
1438 GenericArgs::Parenthesized { .. } => {
1439 }
1442 GenericArgs::ReturnTypeNotation => {
1443 }
1445 }
1446 bounds.extend(mem::take(pred_bounds));
1447 false
1448 }
1449 _ => true,
1450 });
1451 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1457 Some(i) => {
1458 bounds.remove(i);
1459 }
1460 None => bounds.push(GenericBound::maybe_sized(cx)),
1461 }
1462
1463 if tcx.defaultness(assoc_item.def_id).has_value() {
1464 AssocTypeItem(
1465 Box::new(TypeAlias {
1466 type_: clean_middle_ty(
1467 ty::Binder::dummy(
1468 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1469 ),
1470 cx,
1471 Some(assoc_item.def_id),
1472 None,
1473 ),
1474 generics,
1475 inner_type: None,
1476 item_type: None,
1477 }),
1478 bounds,
1479 )
1480 } else {
1481 RequiredAssocTypeItem(generics, bounds)
1482 }
1483 } else {
1484 AssocTypeItem(
1485 Box::new(TypeAlias {
1486 type_: clean_middle_ty(
1487 ty::Binder::dummy(
1488 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1489 ),
1490 cx,
1491 Some(assoc_item.def_id),
1492 None,
1493 ),
1494 generics,
1495 inner_type: None,
1496 item_type: None,
1497 }),
1498 Vec::new(),
1501 )
1502 }
1503 }
1504 };
1505
1506 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, cx)
1507}
1508
1509fn first_non_private_clean_path<'tcx>(
1510 cx: &mut DocContext<'tcx>,
1511 path: &hir::Path<'tcx>,
1512 new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1513 new_path_span: rustc_span::Span,
1514) -> Path {
1515 let new_hir_path =
1516 hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1517 let mut new_clean_path = clean_path(&new_hir_path, cx);
1518 if let Some(path_last) = path.segments.last().as_ref()
1523 && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1524 && let Some(path_last_args) = path_last.args.as_ref()
1525 && path_last.args.is_some()
1526 {
1527 assert!(new_path_last.args.is_empty());
1528 new_path_last.args = clean_generic_args(path_last_args, cx);
1529 }
1530 new_clean_path
1531}
1532
1533fn first_non_private<'tcx>(
1538 cx: &mut DocContext<'tcx>,
1539 hir_id: hir::HirId,
1540 path: &hir::Path<'tcx>,
1541) -> Option<Path> {
1542 let target_def_id = path.res.opt_def_id()?;
1543 let (parent_def_id, ident) = match &path.segments {
1544 [] => return None,
1545 [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1547 [parent, leaf] if parent.ident.name == kw::SelfLower => {
1549 (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1550 }
1551 [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1553 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1554 }
1555 [parent, leaf] if parent.ident.name == kw::Super => {
1556 let parent_mod = cx.tcx.parent_module(hir_id);
1557 if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1558 (super_parent, leaf.ident)
1559 } else {
1560 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1562 }
1563 }
1564 [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1566 };
1567 for child in
1569 cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1570 {
1571 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1572 continue;
1573 }
1574
1575 if let Some(def_id) = child.res.opt_def_id()
1576 && target_def_id == def_id
1577 {
1578 let mut last_path_res = None;
1579 'reexps: for reexp in child.reexport_chain.iter() {
1580 if let Some(use_def_id) = reexp.id()
1581 && let Some(local_use_def_id) = use_def_id.as_local()
1582 && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1583 && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1584 {
1585 for res in path.res.present_items() {
1586 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1587 continue;
1588 }
1589 if (cx.render_options.document_hidden ||
1590 !cx.tcx.is_doc_hidden(use_def_id)) &&
1591 cx.tcx.local_visibility(local_use_def_id).is_public()
1595 {
1596 break 'reexps;
1597 }
1598 last_path_res = Some((path, res));
1599 continue 'reexps;
1600 }
1601 }
1602 }
1603 if !child.reexport_chain.is_empty() {
1604 if let Some((new_path, _)) = last_path_res {
1610 return Some(first_non_private_clean_path(
1611 cx,
1612 path,
1613 new_path.segments,
1614 new_path.span,
1615 ));
1616 }
1617 return None;
1622 }
1623 }
1624 }
1625 None
1626}
1627
1628fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1629 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1630 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1631
1632 match qpath {
1633 hir::QPath::Resolved(None, path) => {
1634 if let Res::Def(DefKind::TyParam, did) = path.res {
1635 if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1636 return new_ty;
1637 }
1638 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1639 return ImplTrait(bounds);
1640 }
1641 }
1642
1643 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1644 expanded
1645 } else {
1646 let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1648 path
1649 } else {
1650 clean_path(path, cx)
1651 };
1652 resolve_type(cx, path)
1653 }
1654 }
1655 hir::QPath::Resolved(Some(qself), p) => {
1656 let ty = lower_ty(cx.tcx, hir_ty);
1658 if !ty.has_escaping_bound_vars()
1660 && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1661 {
1662 return clean_middle_ty(normalized_value, cx, None, None);
1663 }
1664
1665 let trait_segments = &p.segments[..p.segments.len() - 1];
1666 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1667 let trait_ = self::Path {
1668 res: Res::Def(DefKind::Trait, trait_def),
1669 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1670 };
1671 register_res(cx, trait_.res);
1672 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1673 let self_type = clean_ty(qself, cx);
1674 let should_fully_qualify =
1675 should_fully_qualify_path(Some(self_def_id), &trait_, &self_type);
1676 Type::QPath(Box::new(QPathData {
1677 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1678 should_fully_qualify,
1679 self_type,
1680 trait_: Some(trait_),
1681 }))
1682 }
1683 hir::QPath::TypeRelative(qself, segment) => {
1684 let ty = lower_ty(cx.tcx, hir_ty);
1685 let self_type = clean_ty(qself, cx);
1686
1687 let (trait_, should_fully_qualify) = match ty.kind() {
1688 ty::Alias(ty::Projection, proj) => {
1689 let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1690 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1691 register_res(cx, trait_.res);
1692 let self_def_id = res.opt_def_id();
1693 let should_fully_qualify =
1694 should_fully_qualify_path(self_def_id, &trait_, &self_type);
1695
1696 (Some(trait_), should_fully_qualify)
1697 }
1698 ty::Alias(ty::Inherent, _) => (None, false),
1699 ty::Error(_) => return Type::Infer,
1701 _ => bug!("clean: expected associated type, found `{ty:?}`"),
1702 };
1703
1704 Type::QPath(Box::new(QPathData {
1705 assoc: clean_path_segment(segment, cx),
1706 should_fully_qualify,
1707 self_type,
1708 trait_,
1709 }))
1710 }
1711 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1712 }
1713}
1714
1715fn maybe_expand_private_type_alias<'tcx>(
1716 cx: &mut DocContext<'tcx>,
1717 path: &hir::Path<'tcx>,
1718) -> Option<Type> {
1719 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1720 let def_id = def_id.as_local()?;
1722 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1723 && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1724 {
1725 &cx.tcx.hir_expect_item(def_id).kind
1726 } else {
1727 return None;
1728 };
1729 let hir::ItemKind::TyAlias(_, generics, ty) = alias else { return None };
1730
1731 let final_seg = &path.segments.last().expect("segments were empty");
1732 let mut args = DefIdMap::default();
1733 let generic_args = final_seg.args();
1734
1735 let mut indices: hir::GenericParamCount = Default::default();
1736 for param in generics.params.iter() {
1737 match param.kind {
1738 hir::GenericParamKind::Lifetime { .. } => {
1739 let mut j = 0;
1740 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1741 hir::GenericArg::Lifetime(lt) => {
1742 if indices.lifetimes == j {
1743 return Some(lt);
1744 }
1745 j += 1;
1746 None
1747 }
1748 _ => None,
1749 });
1750 if let Some(lt) = lifetime {
1751 let lt = if !lt.is_anonymous() {
1752 clean_lifetime(lt, cx)
1753 } else {
1754 Lifetime::elided()
1755 };
1756 args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1757 }
1758 indices.lifetimes += 1;
1759 }
1760 hir::GenericParamKind::Type { ref default, .. } => {
1761 let mut j = 0;
1762 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1763 hir::GenericArg::Type(ty) => {
1764 if indices.types == j {
1765 return Some(ty.as_unambig_ty());
1766 }
1767 j += 1;
1768 None
1769 }
1770 _ => None,
1771 });
1772 if let Some(ty) = type_.or(*default) {
1773 args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1774 }
1775 indices.types += 1;
1776 }
1777 hir::GenericParamKind::Const { .. } => {}
1779 }
1780 }
1781
1782 Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1783 cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1784 }))
1785}
1786
1787pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1788 use rustc_hir::*;
1789
1790 match ty.kind {
1791 TyKind::Never => Primitive(PrimitiveType::Never),
1792 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1793 TyKind::Ref(l, ref m) => {
1794 let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1795 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1796 }
1797 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1798 TyKind::Pat(ty, pat) => Type::Pat(Box::new(clean_ty(ty, cx)), format!("{pat:?}").into()),
1799 TyKind::Array(ty, const_arg) => {
1800 let length = match const_arg.kind {
1808 hir::ConstArgKind::Infer(..) => "_".to_string(),
1809 hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1810 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1811 let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1812 let ct = cx.tcx.normalize_erasing_regions(typing_env, ct);
1813 print_const(cx, ct)
1814 }
1815 hir::ConstArgKind::Path(..) => {
1816 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1817 print_const(cx, ct)
1818 }
1819 };
1820 Array(Box::new(clean_ty(ty, cx)), length.into())
1821 }
1822 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1823 TyKind::OpaqueDef(ty) => {
1824 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1825 }
1826 TyKind::Path(_) => clean_qpath(ty, cx),
1827 TyKind::TraitObject(bounds, lifetime) => {
1828 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1829 let lifetime = if !lifetime.is_elided() {
1830 Some(clean_lifetime(lifetime.pointer(), cx))
1831 } else {
1832 None
1833 };
1834 DynTrait(bounds, lifetime)
1835 }
1836 TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1837 TyKind::UnsafeBinder(unsafe_binder_ty) => {
1838 UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1839 }
1840 TyKind::Infer(())
1842 | TyKind::Err(_)
1843 | TyKind::Typeof(..)
1844 | TyKind::InferDelegation(..)
1845 | TyKind::TraitAscription(_) => Infer,
1846 }
1847}
1848
1849fn normalize<'tcx>(
1851 cx: &DocContext<'tcx>,
1852 ty: ty::Binder<'tcx, Ty<'tcx>>,
1853) -> Option<ty::Binder<'tcx, Ty<'tcx>>> {
1854 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1856 return None;
1857 }
1858
1859 use rustc_middle::traits::ObligationCause;
1860 use rustc_trait_selection::infer::TyCtxtInferExt;
1861 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1862
1863 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1865 let normalized = infcx
1866 .at(&ObligationCause::dummy(), cx.param_env)
1867 .query_normalize(ty)
1868 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1869 match normalized {
1870 Ok(normalized_value) => {
1871 debug!("normalized {ty:?} to {normalized_value:?}");
1872 Some(normalized_value)
1873 }
1874 Err(err) => {
1875 debug!("failed to normalize {ty:?}: {err:?}");
1876 None
1877 }
1878 }
1879}
1880
1881fn clean_trait_object_lifetime_bound<'tcx>(
1882 region: ty::Region<'tcx>,
1883 container: Option<ContainerTy<'_, 'tcx>>,
1884 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1885 tcx: TyCtxt<'tcx>,
1886) -> Option<Lifetime> {
1887 if can_elide_trait_object_lifetime_bound(region, container, preds, tcx) {
1888 return None;
1889 }
1890
1891 match region.kind() {
1895 ty::ReStatic => Some(Lifetime::statik()),
1896 ty::ReEarlyParam(region) => Some(Lifetime(region.name)),
1897 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(_, name), .. }) => {
1898 Some(Lifetime(name))
1899 }
1900 ty::ReBound(..)
1901 | ty::ReLateParam(_)
1902 | ty::ReVar(_)
1903 | ty::RePlaceholder(_)
1904 | ty::ReErased
1905 | ty::ReError(_) => None,
1906 }
1907}
1908
1909fn can_elide_trait_object_lifetime_bound<'tcx>(
1910 region: ty::Region<'tcx>,
1911 container: Option<ContainerTy<'_, 'tcx>>,
1912 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1913 tcx: TyCtxt<'tcx>,
1914) -> bool {
1915 let default = container
1920 .map_or(ObjectLifetimeDefault::Empty, |container| container.object_lifetime_default(tcx));
1921
1922 match default {
1925 ObjectLifetimeDefault::Static => return region.kind() == ty::ReStatic,
1926 ObjectLifetimeDefault::Arg(default) => return region.get_name() == default.get_name(),
1928 ObjectLifetimeDefault::Ambiguous => return false,
1932 ObjectLifetimeDefault::Empty => {}
1934 }
1935
1936 match *object_region_bounds(tcx, preds) {
1938 [] => region.kind() == ty::ReStatic,
1946 [object_region] => object_region.get_name() == region.get_name(),
1950 _ => false,
1954 }
1955}
1956
1957#[derive(Debug)]
1958pub(crate) enum ContainerTy<'a, 'tcx> {
1959 Ref(ty::Region<'tcx>),
1960 Regular {
1961 ty: DefId,
1962 args: ty::Binder<'tcx, &'a [ty::GenericArg<'tcx>]>,
1965 arg: usize,
1966 },
1967}
1968
1969impl<'tcx> ContainerTy<'_, 'tcx> {
1970 fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> {
1971 match self {
1972 Self::Ref(region) => ObjectLifetimeDefault::Arg(region),
1973 Self::Regular { ty: container, args, arg: index } => {
1974 let (DefKind::Struct
1975 | DefKind::Union
1976 | DefKind::Enum
1977 | DefKind::TyAlias
1978 | DefKind::Trait) = tcx.def_kind(container)
1979 else {
1980 return ObjectLifetimeDefault::Empty;
1981 };
1982
1983 let generics = tcx.generics_of(container);
1984 debug_assert_eq!(generics.parent_count, 0);
1985
1986 let param = generics.own_params[index].def_id;
1987 let default = tcx.object_lifetime_default(param);
1988 match default {
1989 rbv::ObjectLifetimeDefault::Param(lifetime) => {
1990 let index = generics.param_def_id_to_index[&lifetime];
1993 let arg = args.skip_binder()[index as usize].expect_region();
1994 ObjectLifetimeDefault::Arg(arg)
1995 }
1996 rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty,
1997 rbv::ObjectLifetimeDefault::Static => ObjectLifetimeDefault::Static,
1998 rbv::ObjectLifetimeDefault::Ambiguous => ObjectLifetimeDefault::Ambiguous,
1999 }
2000 }
2001 }
2002 }
2003}
2004
2005#[derive(Debug, Clone, Copy)]
2006pub(crate) enum ObjectLifetimeDefault<'tcx> {
2007 Empty,
2008 Static,
2009 Ambiguous,
2010 Arg(ty::Region<'tcx>),
2011}
2012
2013#[instrument(level = "trace", skip(cx), ret)]
2014pub(crate) fn clean_middle_ty<'tcx>(
2015 bound_ty: ty::Binder<'tcx, Ty<'tcx>>,
2016 cx: &mut DocContext<'tcx>,
2017 parent_def_id: Option<DefId>,
2018 container: Option<ContainerTy<'_, 'tcx>>,
2019) -> Type {
2020 let bound_ty = normalize(cx, bound_ty).unwrap_or(bound_ty);
2021 match *bound_ty.skip_binder().kind() {
2022 ty::Never => Primitive(PrimitiveType::Never),
2023 ty::Bool => Primitive(PrimitiveType::Bool),
2024 ty::Char => Primitive(PrimitiveType::Char),
2025 ty::Int(int_ty) => Primitive(int_ty.into()),
2026 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
2027 ty::Float(float_ty) => Primitive(float_ty.into()),
2028 ty::Str => Primitive(PrimitiveType::Str),
2029 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None))),
2030 ty::Pat(ty, pat) => Type::Pat(
2031 Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)),
2032 format!("{pat:?}").into_boxed_str(),
2033 ),
2034 ty::Array(ty, n) => {
2035 let n = cx.tcx.normalize_erasing_regions(cx.typing_env(), n);
2036 let n = print_const(cx, n);
2037 Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into())
2038 }
2039 ty::RawPtr(ty, mutbl) => {
2040 RawPointer(mutbl, Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)))
2041 }
2042 ty::Ref(r, ty, mutbl) => BorrowedRef {
2043 lifetime: clean_middle_region(r),
2044 mutability: mutbl,
2045 type_: Box::new(clean_middle_ty(
2046 bound_ty.rebind(ty),
2047 cx,
2048 None,
2049 Some(ContainerTy::Ref(r)),
2050 )),
2051 },
2052 ty::FnDef(..) | ty::FnPtr(..) => {
2053 let sig = bound_ty.skip_binder().fn_sig(cx.tcx);
2055 let decl = clean_poly_fn_sig(cx, None, sig);
2056 let generic_params = clean_bound_vars(sig.bound_vars());
2057
2058 BareFunction(Box::new(BareFunctionDecl {
2059 safety: sig.safety(),
2060 generic_params,
2061 decl,
2062 abi: sig.abi(),
2063 }))
2064 }
2065 ty::UnsafeBinder(inner) => {
2066 let generic_params = clean_bound_vars(inner.bound_vars());
2067 let ty = clean_middle_ty(inner.into(), cx, None, None);
2068 UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, ty }))
2069 }
2070 ty::Adt(def, args) => {
2071 let did = def.did();
2072 let kind = match def.adt_kind() {
2073 AdtKind::Struct => ItemType::Struct,
2074 AdtKind::Union => ItemType::Union,
2075 AdtKind::Enum => ItemType::Enum,
2076 };
2077 inline::record_extern_fqn(cx, did, kind);
2078 let path = clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args));
2079 Type::Path { path }
2080 }
2081 ty::Foreign(did) => {
2082 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
2083 let path = clean_middle_path(
2084 cx,
2085 did,
2086 false,
2087 ThinVec::new(),
2088 ty::Binder::dummy(ty::GenericArgs::empty()),
2089 );
2090 Type::Path { path }
2091 }
2092 ty::Dynamic(obj, reg, _) => {
2093 let mut dids = obj.auto_traits();
2097 let did = obj
2098 .principal_def_id()
2099 .or_else(|| dids.next())
2100 .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?"));
2101 let args = match obj.principal() {
2102 Some(principal) => principal.map_bound(|p| p.args),
2103 _ => ty::Binder::dummy(ty::GenericArgs::empty()),
2105 };
2106
2107 inline::record_extern_fqn(cx, did, ItemType::Trait);
2108
2109 let lifetime = clean_trait_object_lifetime_bound(reg, container, obj, cx.tcx);
2110
2111 let mut bounds = dids
2112 .map(|did| {
2113 let empty = ty::Binder::dummy(ty::GenericArgs::empty());
2114 let path = clean_middle_path(cx, did, false, ThinVec::new(), empty);
2115 inline::record_extern_fqn(cx, did, ItemType::Trait);
2116 PolyTrait { trait_: path, generic_params: Vec::new() }
2117 })
2118 .collect::<Vec<_>>();
2119
2120 let constraints = obj
2121 .projection_bounds()
2122 .map(|pb| AssocItemConstraint {
2123 assoc: projection_to_path_segment(
2124 pb.map_bound(|pb| {
2125 pb.with_self_ty(cx.tcx, cx.tcx.types.trait_object_dummy_self)
2126 .projection_term
2127 }),
2128 cx,
2129 ),
2130 kind: AssocItemConstraintKind::Equality {
2131 term: clean_middle_term(pb.map_bound(|pb| pb.term), cx),
2132 },
2133 })
2134 .collect();
2135
2136 let late_bound_regions: FxIndexSet<_> = obj
2137 .iter()
2138 .flat_map(|pred| pred.bound_vars())
2139 .filter_map(|var| match var {
2140 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id, name))
2141 if name != kw::UnderscoreLifetime =>
2142 {
2143 Some(GenericParamDef::lifetime(def_id, name))
2144 }
2145 _ => None,
2146 })
2147 .collect();
2148 let late_bound_regions = late_bound_regions.into_iter().collect();
2149
2150 let path = clean_middle_path(cx, did, false, constraints, args);
2151 bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
2152
2153 DynTrait(bounds, lifetime)
2154 }
2155 ty::Tuple(t) => {
2156 Tuple(t.iter().map(|t| clean_middle_ty(bound_ty.rebind(t), cx, None, None)).collect())
2157 }
2158
2159 ty::Alias(ty::Projection, alias_ty @ ty::AliasTy { def_id, args, .. }) => {
2160 if cx.tcx.is_impl_trait_in_trait(def_id) {
2161 clean_middle_opaque_bounds(cx, def_id, args)
2162 } else {
2163 Type::QPath(Box::new(clean_projection(
2164 bound_ty.rebind(alias_ty.into()),
2165 cx,
2166 parent_def_id,
2167 )))
2168 }
2169 }
2170
2171 ty::Alias(ty::Inherent, alias_ty @ ty::AliasTy { def_id, .. }) => {
2172 let alias_ty = bound_ty.rebind(alias_ty);
2173 let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None, None);
2174
2175 Type::QPath(Box::new(QPathData {
2176 assoc: PathSegment {
2177 name: cx.tcx.item_name(def_id),
2178 args: GenericArgs::AngleBracketed {
2179 args: clean_middle_generic_args(
2180 cx,
2181 alias_ty.map_bound(|ty| ty.args.as_slice()),
2182 true,
2183 def_id,
2184 ),
2185 constraints: Default::default(),
2186 },
2187 },
2188 should_fully_qualify: false,
2189 self_type,
2190 trait_: None,
2191 }))
2192 }
2193
2194 ty::Alias(ty::Free, ty::AliasTy { def_id, args, .. }) => {
2195 if cx.tcx.features().lazy_type_alias() {
2196 let path =
2199 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2200 Type::Path { path }
2201 } else {
2202 let ty = cx.tcx.type_of(def_id).instantiate(cx.tcx, args);
2203 clean_middle_ty(bound_ty.rebind(ty), cx, None, None)
2204 }
2205 }
2206
2207 ty::Param(ref p) => {
2208 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
2209 ImplTrait(bounds)
2210 } else if p.name == kw::SelfUpper {
2211 SelfTy
2212 } else {
2213 Generic(p.name)
2214 }
2215 }
2216
2217 ty::Bound(_, ref ty) => match ty.kind {
2218 ty::BoundTyKind::Param(_, name) => Generic(name),
2219 ty::BoundTyKind::Anon => panic!("unexpected anonymous bound type variable"),
2220 },
2221
2222 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2223 if cx.current_type_aliases.contains_key(&def_id) {
2225 let path =
2226 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2227 Type::Path { path }
2228 } else {
2229 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2230 let ty = clean_middle_opaque_bounds(cx, def_id, args);
2233 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2234 *count -= 1;
2235 if *count == 0 {
2236 cx.current_type_aliases.remove(&def_id);
2237 }
2238 }
2239 ty
2240 }
2241 }
2242
2243 ty::Closure(..) => panic!("Closure"),
2244 ty::CoroutineClosure(..) => panic!("CoroutineClosure"),
2245 ty::Coroutine(..) => panic!("Coroutine"),
2246 ty::Placeholder(..) => panic!("Placeholder"),
2247 ty::CoroutineWitness(..) => panic!("CoroutineWitness"),
2248 ty::Infer(..) => panic!("Infer"),
2249
2250 ty::Error(_) => FatalError.raise(),
2251 }
2252}
2253
2254fn clean_middle_opaque_bounds<'tcx>(
2255 cx: &mut DocContext<'tcx>,
2256 impl_trait_def_id: DefId,
2257 args: ty::GenericArgsRef<'tcx>,
2258) -> Type {
2259 let mut has_sized = false;
2260
2261 let bounds: Vec<_> = cx
2262 .tcx
2263 .explicit_item_bounds(impl_trait_def_id)
2264 .iter_instantiated_copied(cx.tcx, args)
2265 .collect();
2266
2267 let mut bounds = bounds
2268 .iter()
2269 .filter_map(|(bound, _)| {
2270 let bound_predicate = bound.kind();
2271 let trait_ref = match bound_predicate.skip_binder() {
2272 ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
2273 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
2274 return clean_middle_region(reg).map(GenericBound::Outlives);
2275 }
2276 _ => return None,
2277 };
2278
2279 if let Some(sized) = cx.tcx.lang_items().sized_trait()
2280 && trait_ref.def_id() == sized
2281 {
2282 has_sized = true;
2283 return None;
2284 }
2285
2286 let bindings: ThinVec<_> = bounds
2287 .iter()
2288 .filter_map(|(bound, _)| {
2289 let bound = bound.kind();
2290 if let ty::ClauseKind::Projection(proj_pred) = bound.skip_binder()
2291 && proj_pred.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
2292 {
2293 return Some(AssocItemConstraint {
2294 assoc: projection_to_path_segment(
2295 bound.rebind(proj_pred.projection_term),
2296 cx,
2297 ),
2298 kind: AssocItemConstraintKind::Equality {
2299 term: clean_middle_term(bound.rebind(proj_pred.term), cx),
2300 },
2301 });
2302 }
2303 None
2304 })
2305 .collect();
2306
2307 Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings))
2308 })
2309 .collect::<Vec<_>>();
2310
2311 if !has_sized {
2312 bounds.push(GenericBound::maybe_sized(cx));
2313 }
2314
2315 bounds.sort_by_key(|b| !b.is_trait_bound());
2317
2318 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
2321 bounds.insert(0, GenericBound::sized(cx));
2322 }
2323
2324 if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) {
2325 bounds.push(GenericBound::Use(
2326 args.iter()
2327 .map(|arg| match arg {
2328 hir::PreciseCapturingArgKind::Lifetime(lt) => {
2329 PreciseCapturingArg::Lifetime(Lifetime(*lt))
2330 }
2331 hir::PreciseCapturingArgKind::Param(param) => {
2332 PreciseCapturingArg::Param(*param)
2333 }
2334 })
2335 .collect(),
2336 ));
2337 }
2338
2339 ImplTrait(bounds)
2340}
2341
2342pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2343 clean_field_with_def_id(field.def_id.to_def_id(), field.ident.name, clean_ty(field.ty, cx), cx)
2344}
2345
2346pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item {
2347 clean_field_with_def_id(
2348 field.did,
2349 field.name,
2350 clean_middle_ty(
2351 ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity()),
2352 cx,
2353 Some(field.did),
2354 None,
2355 ),
2356 cx,
2357 )
2358}
2359
2360pub(crate) fn clean_field_with_def_id(
2361 def_id: DefId,
2362 name: Symbol,
2363 ty: Type,
2364 cx: &mut DocContext<'_>,
2365) -> Item {
2366 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
2367}
2368
2369pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item {
2370 let discriminant = match variant.discr {
2371 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2372 ty::VariantDiscr::Relative(_) => None,
2373 };
2374
2375 let kind = match variant.ctor_kind() {
2376 Some(CtorKind::Const) => VariantKind::CLike,
2377 Some(CtorKind::Fn) => VariantKind::Tuple(
2378 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2379 ),
2380 None => VariantKind::Struct(VariantStruct {
2381 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2382 }),
2383 };
2384
2385 Item::from_def_id_and_parts(
2386 variant.def_id,
2387 Some(variant.name),
2388 VariantItem(Variant { kind, discriminant }),
2389 cx,
2390 )
2391}
2392
2393pub(crate) fn clean_variant_def_with_args<'tcx>(
2394 variant: &ty::VariantDef,
2395 args: &GenericArgsRef<'tcx>,
2396 cx: &mut DocContext<'tcx>,
2397) -> 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 use rustc_middle::traits::ObligationCause;
2404 use rustc_trait_selection::infer::TyCtxtInferExt;
2405 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
2406
2407 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2408 let kind = match variant.ctor_kind() {
2409 Some(CtorKind::Const) => VariantKind::CLike,
2410 Some(CtorKind::Fn) => VariantKind::Tuple(
2411 variant
2412 .fields
2413 .iter()
2414 .map(|field| {
2415 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2416
2417 let ty = infcx
2421 .at(&ObligationCause::dummy(), cx.param_env)
2422 .query_normalize(ty)
2423 .map(|normalized| normalized.value)
2424 .unwrap_or(ty);
2425
2426 clean_field_with_def_id(
2427 field.did,
2428 field.name,
2429 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2430 cx,
2431 )
2432 })
2433 .collect(),
2434 ),
2435 None => VariantKind::Struct(VariantStruct {
2436 fields: variant
2437 .fields
2438 .iter()
2439 .map(|field| {
2440 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2441
2442 let ty = infcx
2446 .at(&ObligationCause::dummy(), cx.param_env)
2447 .query_normalize(ty)
2448 .map(|normalized| normalized.value)
2449 .unwrap_or(ty);
2450
2451 clean_field_with_def_id(
2452 field.did,
2453 field.name,
2454 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2455 cx,
2456 )
2457 })
2458 .collect(),
2459 }),
2460 };
2461
2462 Item::from_def_id_and_parts(
2463 variant.def_id,
2464 Some(variant.name),
2465 VariantItem(Variant { kind, discriminant }),
2466 cx,
2467 )
2468}
2469
2470fn clean_variant_data<'tcx>(
2471 variant: &hir::VariantData<'tcx>,
2472 disr_expr: &Option<&hir::AnonConst>,
2473 cx: &mut DocContext<'tcx>,
2474) -> Variant {
2475 let discriminant = disr_expr
2476 .map(|disr| Discriminant { expr: Some(disr.body), value: disr.def_id.to_def_id() });
2477
2478 let kind = match variant {
2479 hir::VariantData::Struct { fields, .. } => VariantKind::Struct(VariantStruct {
2480 fields: fields.iter().map(|x| clean_field(x, cx)).collect(),
2481 }),
2482 hir::VariantData::Tuple(..) => {
2483 VariantKind::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
2484 }
2485 hir::VariantData::Unit(..) => VariantKind::CLike,
2486 };
2487
2488 Variant { discriminant, kind }
2489}
2490
2491fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
2492 Path {
2493 res: path.res,
2494 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
2495 }
2496}
2497
2498fn clean_generic_args<'tcx>(
2499 generic_args: &hir::GenericArgs<'tcx>,
2500 cx: &mut DocContext<'tcx>,
2501) -> GenericArgs {
2502 match generic_args.parenthesized {
2503 hir::GenericArgsParentheses::No => {
2504 let args = generic_args
2505 .args
2506 .iter()
2507 .map(|arg| match arg {
2508 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
2509 GenericArg::Lifetime(clean_lifetime(lt, cx))
2510 }
2511 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2512 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)),
2513 hir::GenericArg::Const(ct) => {
2514 GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct(), cx)))
2515 }
2516 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
2517 })
2518 .collect();
2519 let constraints = generic_args
2520 .constraints
2521 .iter()
2522 .map(|c| clean_assoc_item_constraint(c, cx))
2523 .collect::<ThinVec<_>>();
2524 GenericArgs::AngleBracketed { args, constraints }
2525 }
2526 hir::GenericArgsParentheses::ParenSugar => {
2527 let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else {
2528 bug!();
2529 };
2530 let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect();
2531 let output = match output.kind {
2532 hir::TyKind::Tup(&[]) => None,
2533 _ => Some(Box::new(clean_ty(output, cx))),
2534 };
2535 GenericArgs::Parenthesized { inputs, output }
2536 }
2537 hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
2538 }
2539}
2540
2541fn clean_path_segment<'tcx>(
2542 path: &hir::PathSegment<'tcx>,
2543 cx: &mut DocContext<'tcx>,
2544) -> PathSegment {
2545 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
2546}
2547
2548fn clean_bare_fn_ty<'tcx>(
2549 bare_fn: &hir::BareFnTy<'tcx>,
2550 cx: &mut DocContext<'tcx>,
2551) -> BareFunctionDecl {
2552 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
2553 let generic_params = bare_fn
2555 .generic_params
2556 .iter()
2557 .filter(|p| !is_elided_lifetime(p))
2558 .map(|x| clean_generic_param(cx, None, x))
2559 .collect();
2560 let filter = |ident: Option<Ident>| {
2564 ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore)
2565 };
2566 let fallback =
2567 bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore);
2568 let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents, |ident| {
2569 filter(ident).or(fallback)
2570 });
2571 let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params);
2572 (generic_params, decl)
2573 });
2574 BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params }
2575}
2576
2577fn clean_unsafe_binder_ty<'tcx>(
2578 unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>,
2579 cx: &mut DocContext<'tcx>,
2580) -> UnsafeBinderTy {
2581 let generic_params = unsafe_binder_ty
2582 .generic_params
2583 .iter()
2584 .filter(|p| !is_elided_lifetime(p))
2585 .map(|x| clean_generic_param(cx, None, x))
2586 .collect();
2587 let ty = clean_ty(unsafe_binder_ty.inner_ty, cx);
2588 UnsafeBinderTy { generic_params, ty }
2589}
2590
2591pub(crate) fn reexport_chain(
2592 tcx: TyCtxt<'_>,
2593 import_def_id: LocalDefId,
2594 target_def_id: DefId,
2595) -> &[Reexport] {
2596 for child in tcx.module_children_local(tcx.local_parent(import_def_id)) {
2597 if child.res.opt_def_id() == Some(target_def_id)
2598 && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id())
2599 {
2600 return &child.reexport_chain;
2601 }
2602 }
2603 &[]
2604}
2605
2606fn get_all_import_attributes<'hir>(
2608 cx: &mut DocContext<'hir>,
2609 import_def_id: LocalDefId,
2610 target_def_id: DefId,
2611 is_inline: bool,
2612) -> Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)> {
2613 let mut attrs = Vec::new();
2614 let mut first = true;
2615 for def_id in reexport_chain(cx.tcx, import_def_id, target_def_id)
2616 .iter()
2617 .flat_map(|reexport| reexport.id())
2618 {
2619 let import_attrs = inline::load_attrs(cx, def_id);
2620 if first {
2621 attrs = import_attrs.iter().map(|attr| (Cow::Borrowed(attr), Some(def_id))).collect();
2623 first = false;
2624 } else if cx.render_options.document_hidden || !cx.tcx.is_doc_hidden(def_id) {
2626 add_without_unwanted_attributes(&mut attrs, import_attrs, is_inline, Some(def_id));
2627 }
2628 }
2629 attrs
2630}
2631
2632fn filter_tokens_from_list(
2633 args_tokens: &TokenStream,
2634 should_retain: impl Fn(&TokenTree) -> bool,
2635) -> Vec<TokenTree> {
2636 let mut tokens = Vec::with_capacity(args_tokens.len());
2637 let mut skip_next_comma = false;
2638 for token in args_tokens.iter() {
2639 match token {
2640 TokenTree::Token(Token { kind: TokenKind::Comma, .. }, _) if skip_next_comma => {
2641 skip_next_comma = false;
2642 }
2643 token if should_retain(token) => {
2644 skip_next_comma = false;
2645 tokens.push(token.clone());
2646 }
2647 _ => {
2648 skip_next_comma = true;
2649 }
2650 }
2651 }
2652 tokens
2653}
2654
2655fn filter_doc_attr_ident(ident: Symbol, is_inline: bool) -> bool {
2656 if is_inline {
2657 ident == sym::hidden || ident == sym::inline || ident == sym::no_inline
2658 } else {
2659 ident == sym::cfg
2660 }
2661}
2662
2663fn filter_doc_attr(args: &mut hir::AttrArgs, is_inline: bool) {
2666 match args {
2667 hir::AttrArgs::Delimited(args) => {
2668 let tokens = filter_tokens_from_list(&args.tokens, |token| {
2669 !matches!(
2670 token,
2671 TokenTree::Token(
2672 Token {
2673 kind: TokenKind::Ident(
2674 ident,
2675 _,
2676 ),
2677 ..
2678 },
2679 _,
2680 ) if filter_doc_attr_ident(*ident, is_inline),
2681 )
2682 });
2683 args.tokens = TokenStream::new(tokens);
2684 }
2685 hir::AttrArgs::Empty | hir::AttrArgs::Eq { .. } => {}
2686 }
2687}
2688
2689fn add_without_unwanted_attributes<'hir>(
2710 attrs: &mut Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)>,
2711 new_attrs: &'hir [hir::Attribute],
2712 is_inline: bool,
2713 import_parent: Option<DefId>,
2714) {
2715 for attr in new_attrs {
2716 if attr.is_doc_comment() {
2717 attrs.push((Cow::Borrowed(attr), import_parent));
2718 continue;
2719 }
2720 let mut attr = attr.clone();
2721 match attr {
2722 hir::Attribute::Unparsed(ref mut normal) if let [ident] = &*normal.path.segments => {
2723 let ident = ident.name;
2724 if ident == sym::doc {
2725 filter_doc_attr(&mut normal.args, is_inline);
2726 attrs.push((Cow::Owned(attr), import_parent));
2727 } else if is_inline || ident != sym::cfg_trace {
2728 attrs.push((Cow::Owned(attr), import_parent));
2730 }
2731 }
2732 hir::Attribute::Parsed(..) if is_inline => {
2733 attrs.push((Cow::Owned(attr), import_parent));
2734 }
2735 _ => {}
2736 }
2737 }
2738}
2739
2740fn clean_maybe_renamed_item<'tcx>(
2741 cx: &mut DocContext<'tcx>,
2742 item: &hir::Item<'tcx>,
2743 renamed: Option<Symbol>,
2744 import_id: Option<LocalDefId>,
2745) -> Vec<Item> {
2746 use hir::ItemKind;
2747
2748 fn get_name(
2749 cx: &DocContext<'_>,
2750 item: &hir::Item<'_>,
2751 renamed: Option<Symbol>,
2752 ) -> Option<Symbol> {
2753 renamed.or_else(|| cx.tcx.hir_opt_name(item.hir_id()))
2754 }
2755
2756 let def_id = item.owner_id.to_def_id();
2757 cx.with_param_env(def_id, |cx| {
2758 match item.kind {
2761 ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx),
2762 ItemKind::Use(path, kind) => {
2763 return clean_use_statement(
2764 item,
2765 get_name(cx, item, renamed),
2766 path,
2767 kind,
2768 cx,
2769 &mut FxHashSet::default(),
2770 );
2771 }
2772 _ => {}
2773 }
2774
2775 let mut name = get_name(cx, item, renamed).unwrap();
2776
2777 let kind = match item.kind {
2778 ItemKind::Static(mutability, _, ty, body_id) => StaticItem(Static {
2779 type_: Box::new(clean_ty(ty, cx)),
2780 mutability,
2781 expr: Some(body_id),
2782 }),
2783 ItemKind::Const(_, generics, ty, body_id) => ConstantItem(Box::new(Constant {
2784 generics: clean_generics(generics, cx),
2785 type_: clean_ty(ty, cx),
2786 kind: ConstantKind::Local { body: body_id, def_id },
2787 })),
2788 ItemKind::TyAlias(_, generics, ty) => {
2789 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2790 let rustdoc_ty = clean_ty(ty, cx);
2791 let type_ =
2792 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, ty)), cx, None, None);
2793 let generics = clean_generics(generics, cx);
2794 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2795 *count -= 1;
2796 if *count == 0 {
2797 cx.current_type_aliases.remove(&def_id);
2798 }
2799 }
2800
2801 let ty = cx.tcx.type_of(def_id).instantiate_identity();
2802
2803 let mut ret = Vec::new();
2804 let inner_type = clean_ty_alias_inner_type(ty, cx, &mut ret);
2805
2806 ret.push(generate_item_with_correct_attrs(
2807 cx,
2808 TypeAliasItem(Box::new(TypeAlias {
2809 generics,
2810 inner_type,
2811 type_: rustdoc_ty,
2812 item_type: Some(type_),
2813 })),
2814 item.owner_id.def_id.to_def_id(),
2815 name,
2816 import_id,
2817 renamed,
2818 ));
2819 return ret;
2820 }
2821 ItemKind::Enum(_, generics, def) => EnumItem(Enum {
2822 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2823 generics: clean_generics(generics, cx),
2824 }),
2825 ItemKind::TraitAlias(_, generics, bounds) => TraitAliasItem(TraitAlias {
2826 generics: clean_generics(generics, cx),
2827 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2828 }),
2829 ItemKind::Union(_, generics, variant_data) => UnionItem(Union {
2830 generics: clean_generics(generics, cx),
2831 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2832 }),
2833 ItemKind::Struct(_, generics, variant_data) => StructItem(Struct {
2834 ctor_kind: variant_data.ctor_kind(),
2835 generics: clean_generics(generics, cx),
2836 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2837 }),
2838 ItemKind::Macro(_, macro_def, MacroKind::Bang) => MacroItem(Macro {
2839 source: display_macro_source(cx, name, macro_def),
2840 macro_rules: macro_def.macro_rules,
2841 }),
2842 ItemKind::Macro(_, _, macro_kind) => clean_proc_macro(item, &mut name, macro_kind, cx),
2843 ItemKind::Fn { ref sig, generics, body: body_id, .. } => {
2845 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2846 }
2847 ItemKind::Trait(_, _, _, generics, bounds, item_ids) => {
2848 let items = item_ids
2849 .iter()
2850 .map(|ti| clean_trait_item(cx.tcx.hir_trait_item(ti.id), cx))
2851 .collect();
2852
2853 TraitItem(Box::new(Trait {
2854 def_id,
2855 items,
2856 generics: clean_generics(generics, cx),
2857 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2858 }))
2859 }
2860 ItemKind::ExternCrate(orig_name, _) => {
2861 return clean_extern_crate(item, name, orig_name, cx);
2862 }
2863 _ => span_bug!(item.span, "not yet converted"),
2864 };
2865
2866 vec![generate_item_with_correct_attrs(
2867 cx,
2868 kind,
2869 item.owner_id.def_id.to_def_id(),
2870 name,
2871 import_id,
2872 renamed,
2873 )]
2874 })
2875}
2876
2877fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2878 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2879 Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx)
2880}
2881
2882fn clean_impl<'tcx>(
2883 impl_: &hir::Impl<'tcx>,
2884 def_id: LocalDefId,
2885 cx: &mut DocContext<'tcx>,
2886) -> Vec<Item> {
2887 let tcx = cx.tcx;
2888 let mut ret = Vec::new();
2889 let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
2890 let items = impl_
2891 .items
2892 .iter()
2893 .map(|ii| clean_impl_item(tcx.hir_impl_item(ii.id), cx))
2894 .collect::<Vec<_>>();
2895
2896 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2899 build_deref_target_impls(cx, &items, &mut ret);
2900 }
2901
2902 let for_ = clean_ty(impl_.self_ty, cx);
2903 let type_alias =
2904 for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) {
2905 DefKind::TyAlias => Some(clean_middle_ty(
2906 ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()),
2907 cx,
2908 Some(def_id.to_def_id()),
2909 None,
2910 )),
2911 _ => None,
2912 });
2913 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2914 let kind = ImplItem(Box::new(Impl {
2915 safety: impl_.safety,
2916 generics: clean_generics(impl_.generics, cx),
2917 trait_,
2918 for_,
2919 items,
2920 polarity: tcx.impl_polarity(def_id),
2921 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2922 ImplKind::FakeVariadic
2923 } else {
2924 ImplKind::Normal
2925 },
2926 }));
2927 Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, cx)
2928 };
2929 if let Some(type_alias) = type_alias {
2930 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2931 }
2932 ret.push(make_item(trait_, for_, items));
2933 ret
2934}
2935
2936fn clean_extern_crate<'tcx>(
2937 krate: &hir::Item<'tcx>,
2938 name: Symbol,
2939 orig_name: Option<Symbol>,
2940 cx: &mut DocContext<'tcx>,
2941) -> Vec<Item> {
2942 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2944 let crate_def_id = cnum.as_def_id();
2946 let attrs = cx.tcx.hir_attrs(krate.hir_id());
2947 let ty_vis = cx.tcx.visibility(krate.owner_id);
2948 let please_inline = ty_vis.is_public()
2949 && attrs.iter().any(|a| {
2950 a.has_name(sym::doc)
2951 && match a.meta_item_list() {
2952 Some(l) => ast::attr::list_contains_name(&l, sym::inline),
2953 None => false,
2954 }
2955 })
2956 && !cx.is_json_output();
2957
2958 let krate_owner_def_id = krate.owner_id.def_id;
2959 if please_inline
2960 && let Some(items) = inline::try_inline(
2961 cx,
2962 Res::Def(DefKind::Mod, crate_def_id),
2963 name,
2964 Some((attrs, Some(krate_owner_def_id))),
2965 &mut Default::default(),
2966 )
2967 {
2968 return items;
2969 }
2970
2971 vec![Item::from_def_id_and_parts(
2972 krate_owner_def_id.to_def_id(),
2973 Some(name),
2974 ExternCrateItem { src: orig_name },
2975 cx,
2976 )]
2977}
2978
2979fn clean_use_statement<'tcx>(
2980 import: &hir::Item<'tcx>,
2981 name: Option<Symbol>,
2982 path: &hir::UsePath<'tcx>,
2983 kind: hir::UseKind,
2984 cx: &mut DocContext<'tcx>,
2985 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2986) -> Vec<Item> {
2987 let mut items = Vec::new();
2988 let hir::UsePath { segments, ref res, span } = *path;
2989 for res in res.present_items() {
2990 let path = hir::Path { segments, res, span };
2991 items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
2992 }
2993 items
2994}
2995
2996fn clean_use_statement_inner<'tcx>(
2997 import: &hir::Item<'tcx>,
2998 name: Option<Symbol>,
2999 path: &hir::Path<'tcx>,
3000 kind: hir::UseKind,
3001 cx: &mut DocContext<'tcx>,
3002 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3003) -> Vec<Item> {
3004 if should_ignore_res(path.res) {
3005 return Vec::new();
3006 }
3007 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
3011 return Vec::new();
3012 }
3013
3014 let visibility = cx.tcx.visibility(import.owner_id);
3015 let attrs = cx.tcx.hir_attrs(import.hir_id());
3016 let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline);
3017 let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
3018 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
3019 let import_def_id = import.owner_id.def_id;
3020
3021 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
3025
3026 let is_visible_from_parent_mod =
3032 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3033
3034 if pub_underscore && let Some(ref inline) = inline_attr {
3035 struct_span_code_err!(
3036 cx.tcx.dcx(),
3037 inline.span(),
3038 E0780,
3039 "anonymous imports cannot be inlined"
3040 )
3041 .with_span_label(import.span, "anonymous import")
3042 .emit();
3043 }
3044
3045 let mut denied = cx.is_json_output()
3050 || !(visibility.is_public()
3051 || (cx.render_options.document_private && is_visible_from_parent_mod))
3052 || pub_underscore
3053 || attrs.iter().any(|a| {
3054 a.has_name(sym::doc)
3055 && match a.meta_item_list() {
3056 Some(l) => {
3057 ast::attr::list_contains_name(&l, sym::no_inline)
3058 || ast::attr::list_contains_name(&l, sym::hidden)
3059 }
3060 None => false,
3061 }
3062 });
3063
3064 let path = clean_path(path, cx);
3067 let inner = if kind == hir::UseKind::Glob {
3068 if !denied {
3069 let mut visited = DefIdSet::default();
3070 if let Some(items) = inline::try_inline_glob(
3071 cx,
3072 path.res,
3073 current_mod,
3074 &mut visited,
3075 inlined_names,
3076 import,
3077 ) {
3078 return items;
3079 }
3080 }
3081 Import::new_glob(resolve_use_source(cx, path), true)
3082 } else {
3083 let name = name.unwrap();
3084 if inline_attr.is_none()
3085 && let Res::Def(DefKind::Mod, did) = path.res
3086 && !did.is_local()
3087 && did.is_crate_root()
3088 {
3089 denied = true;
3092 }
3093 if !denied
3094 && let Some(mut items) = inline::try_inline(
3095 cx,
3096 path.res,
3097 name,
3098 Some((attrs, Some(import_def_id))),
3099 &mut Default::default(),
3100 )
3101 {
3102 items.push(Item::from_def_id_and_parts(
3103 import_def_id.to_def_id(),
3104 None,
3105 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3106 cx,
3107 ));
3108 return items;
3109 }
3110 Import::new_simple(name, resolve_use_source(cx, path), true)
3111 };
3112
3113 vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx)]
3114}
3115
3116fn clean_maybe_renamed_foreign_item<'tcx>(
3117 cx: &mut DocContext<'tcx>,
3118 item: &hir::ForeignItem<'tcx>,
3119 renamed: Option<Symbol>,
3120) -> Item {
3121 let def_id = item.owner_id.to_def_id();
3122 cx.with_param_env(def_id, |cx| {
3123 let kind = match item.kind {
3124 hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3125 clean_function(cx, &sig, generics, ParamsSrc::Idents(idents)),
3126 sig.header.safety(),
3127 ),
3128 hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3129 Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3130 safety,
3131 ),
3132 hir::ForeignItemKind::Type => ForeignTypeItem,
3133 };
3134
3135 Item::from_def_id_and_parts(
3136 item.owner_id.def_id.to_def_id(),
3137 Some(renamed.unwrap_or(item.ident.name)),
3138 kind,
3139 cx,
3140 )
3141 })
3142}
3143
3144fn clean_assoc_item_constraint<'tcx>(
3145 constraint: &hir::AssocItemConstraint<'tcx>,
3146 cx: &mut DocContext<'tcx>,
3147) -> AssocItemConstraint {
3148 AssocItemConstraint {
3149 assoc: PathSegment {
3150 name: constraint.ident.name,
3151 args: clean_generic_args(constraint.gen_args, cx),
3152 },
3153 kind: match constraint.kind {
3154 hir::AssocItemConstraintKind::Equality { ref term } => {
3155 AssocItemConstraintKind::Equality { term: clean_hir_term(term, cx) }
3156 }
3157 hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3158 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3159 },
3160 },
3161 }
3162}
3163
3164fn clean_bound_vars(bound_vars: &ty::List<ty::BoundVariableKind>) -> Vec<GenericParamDef> {
3165 bound_vars
3166 .into_iter()
3167 .filter_map(|var| match var {
3168 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id, name))
3169 if name != kw::UnderscoreLifetime =>
3170 {
3171 Some(GenericParamDef::lifetime(def_id, name))
3172 }
3173 ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id, name)) => {
3174 Some(GenericParamDef {
3175 name,
3176 def_id,
3177 kind: GenericParamDefKind::Type {
3178 bounds: ThinVec::new(),
3179 default: None,
3180 synthetic: false,
3181 },
3182 })
3183 }
3184 ty::BoundVariableKind::Const => None,
3186 _ => None,
3187 })
3188 .collect()
3189}