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