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 = cx.tcx.defaultness(impl_.owner_id);
1260 MethodItem(m, Some(defaultness))
1261 }
1262 hir::ImplItemKind::Type(hir_ty) => {
1263 let type_ = clean_ty(hir_ty, cx);
1264 let generics = clean_generics(impl_.generics, cx);
1265 let item_type =
1266 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1267 AssocTypeItem(
1268 Box::new(TypeAlias {
1269 type_,
1270 generics,
1271 inner_type: None,
1272 item_type: Some(item_type),
1273 }),
1274 Vec::new(),
1275 )
1276 }
1277 };
1278
1279 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1280 })
1281}
1282
1283pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1284 let tcx = cx.tcx;
1285 let kind = match assoc_item.kind {
1286 ty::AssocKind::Const { .. } => {
1287 let ty = clean_middle_ty(
1288 ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()),
1289 cx,
1290 Some(assoc_item.def_id),
1291 None,
1292 );
1293
1294 let mut generics = clean_ty_generics(cx, assoc_item.def_id);
1295 simplify::move_bounds_to_generic_parameters(&mut generics);
1296
1297 match assoc_item.container {
1298 ty::AssocItemContainer::Impl => ImplAssocConstItem(Box::new(Constant {
1299 generics,
1300 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1301 type_: ty,
1302 })),
1303 ty::AssocItemContainer::Trait => {
1304 if tcx.defaultness(assoc_item.def_id).has_value() {
1305 ProvidedAssocConstItem(Box::new(Constant {
1306 generics,
1307 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1308 type_: ty,
1309 }))
1310 } else {
1311 RequiredAssocConstItem(generics, Box::new(ty))
1312 }
1313 }
1314 }
1315 }
1316 ty::AssocKind::Fn { has_self, .. } => {
1317 let mut item = inline::build_function(cx, assoc_item.def_id);
1318
1319 if has_self {
1320 let self_ty = match assoc_item.container {
1321 ty::AssocItemContainer::Impl => {
1322 tcx.type_of(assoc_item.container_id(tcx)).instantiate_identity()
1323 }
1324 ty::AssocItemContainer::Trait => tcx.types.self_param,
1325 };
1326 let self_param_ty =
1327 tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder();
1328 if self_param_ty == self_ty {
1329 item.decl.inputs[0].type_ = SelfTy;
1330 } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1331 && ty == self_ty
1332 {
1333 match item.decl.inputs[0].type_ {
1334 BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1335 _ => unreachable!(),
1336 }
1337 }
1338 }
1339
1340 let provided = match assoc_item.container {
1341 ty::AssocItemContainer::Impl => true,
1342 ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1343 };
1344 if provided {
1345 let defaultness = match assoc_item.container {
1346 ty::AssocItemContainer::Impl => Some(assoc_item.defaultness(tcx)),
1347 ty::AssocItemContainer::Trait => None,
1348 };
1349 MethodItem(item, defaultness)
1350 } else {
1351 RequiredMethodItem(item)
1352 }
1353 }
1354 ty::AssocKind::Type { .. } => {
1355 let my_name = assoc_item.name();
1356
1357 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1358 match (¶m.kind, arg) {
1359 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1360 if *ty == param.name =>
1361 {
1362 true
1363 }
1364 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1365 if *lt == param.name =>
1366 {
1367 true
1368 }
1369 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1370 ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1371 _ => false,
1372 },
1373 _ => false,
1374 }
1375 }
1376
1377 let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1378 if let ty::AssocItemContainer::Trait = assoc_item.container {
1379 let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied();
1380 predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied()));
1381 }
1382 let mut generics = clean_ty_generics_inner(
1383 cx,
1384 tcx.generics_of(assoc_item.def_id),
1385 ty::GenericPredicates { parent: None, predicates },
1386 );
1387 simplify::move_bounds_to_generic_parameters(&mut generics);
1388
1389 if let ty::AssocItemContainer::Trait = assoc_item.container {
1390 let mut bounds: Vec<GenericBound> = Vec::new();
1395 generics.where_predicates.retain_mut(|pred| match *pred {
1396 WherePredicate::BoundPredicate {
1397 ty:
1398 QPath(box QPathData {
1399 ref assoc,
1400 ref self_type,
1401 trait_: Some(ref trait_),
1402 ..
1403 }),
1404 bounds: ref mut pred_bounds,
1405 ..
1406 } => {
1407 if assoc.name != my_name {
1408 return true;
1409 }
1410 if trait_.def_id() != assoc_item.container_id(tcx) {
1411 return true;
1412 }
1413 if *self_type != SelfTy {
1414 return true;
1415 }
1416 match &assoc.args {
1417 GenericArgs::AngleBracketed { args, constraints } => {
1418 if !constraints.is_empty()
1419 || generics
1420 .params
1421 .iter()
1422 .zip(args.iter())
1423 .any(|(param, arg)| !param_eq_arg(param, arg))
1424 {
1425 return true;
1426 }
1427 }
1428 GenericArgs::Parenthesized { .. } => {
1429 }
1432 GenericArgs::ReturnTypeNotation => {
1433 }
1435 }
1436 bounds.extend(mem::take(pred_bounds));
1437 false
1438 }
1439 _ => true,
1440 });
1441
1442 bounds.retain(|b| {
1443 !b.is_meta_sized_bound(cx)
1446 });
1447
1448 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1454 Some(i) => {
1455 bounds.remove(i);
1456 }
1457 None => bounds.push(GenericBound::maybe_sized(cx)),
1458 }
1459
1460 if tcx.defaultness(assoc_item.def_id).has_value() {
1461 AssocTypeItem(
1462 Box::new(TypeAlias {
1463 type_: clean_middle_ty(
1464 ty::Binder::dummy(
1465 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1466 ),
1467 cx,
1468 Some(assoc_item.def_id),
1469 None,
1470 ),
1471 generics,
1472 inner_type: None,
1473 item_type: None,
1474 }),
1475 bounds,
1476 )
1477 } else {
1478 RequiredAssocTypeItem(generics, bounds)
1479 }
1480 } else {
1481 AssocTypeItem(
1482 Box::new(TypeAlias {
1483 type_: clean_middle_ty(
1484 ty::Binder::dummy(
1485 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1486 ),
1487 cx,
1488 Some(assoc_item.def_id),
1489 None,
1490 ),
1491 generics,
1492 inner_type: None,
1493 item_type: None,
1494 }),
1495 Vec::new(),
1498 )
1499 }
1500 }
1501 };
1502
1503 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, cx)
1504}
1505
1506fn first_non_private_clean_path<'tcx>(
1507 cx: &mut DocContext<'tcx>,
1508 path: &hir::Path<'tcx>,
1509 new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1510 new_path_span: rustc_span::Span,
1511) -> Path {
1512 let new_hir_path =
1513 hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1514 let mut new_clean_path = clean_path(&new_hir_path, cx);
1515 if let Some(path_last) = path.segments.last().as_ref()
1520 && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1521 && let Some(path_last_args) = path_last.args.as_ref()
1522 && path_last.args.is_some()
1523 {
1524 assert!(new_path_last.args.is_empty());
1525 new_path_last.args = clean_generic_args(path_last_args, cx);
1526 }
1527 new_clean_path
1528}
1529
1530fn first_non_private<'tcx>(
1535 cx: &mut DocContext<'tcx>,
1536 hir_id: hir::HirId,
1537 path: &hir::Path<'tcx>,
1538) -> Option<Path> {
1539 let target_def_id = path.res.opt_def_id()?;
1540 let (parent_def_id, ident) = match &path.segments {
1541 [] => return None,
1542 [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1544 [parent, leaf] if parent.ident.name == kw::SelfLower => {
1546 (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1547 }
1548 [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1550 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1551 }
1552 [parent, leaf] if parent.ident.name == kw::Super => {
1553 let parent_mod = cx.tcx.parent_module(hir_id);
1554 if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1555 (super_parent, leaf.ident)
1556 } else {
1557 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1559 }
1560 }
1561 [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1563 };
1564 for child in
1566 cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1567 {
1568 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1569 continue;
1570 }
1571
1572 if let Some(def_id) = child.res.opt_def_id()
1573 && target_def_id == def_id
1574 {
1575 let mut last_path_res = None;
1576 'reexps: for reexp in child.reexport_chain.iter() {
1577 if let Some(use_def_id) = reexp.id()
1578 && let Some(local_use_def_id) = use_def_id.as_local()
1579 && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1580 && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1581 {
1582 for res in path.res.present_items() {
1583 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1584 continue;
1585 }
1586 if (cx.render_options.document_hidden ||
1587 !cx.tcx.is_doc_hidden(use_def_id)) &&
1588 cx.tcx.local_visibility(local_use_def_id).is_public()
1592 {
1593 break 'reexps;
1594 }
1595 last_path_res = Some((path, res));
1596 continue 'reexps;
1597 }
1598 }
1599 }
1600 if !child.reexport_chain.is_empty() {
1601 if let Some((new_path, _)) = last_path_res {
1607 return Some(first_non_private_clean_path(
1608 cx,
1609 path,
1610 new_path.segments,
1611 new_path.span,
1612 ));
1613 }
1614 return None;
1619 }
1620 }
1621 }
1622 None
1623}
1624
1625fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1626 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1627 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1628
1629 match qpath {
1630 hir::QPath::Resolved(None, path) => {
1631 if let Res::Def(DefKind::TyParam, did) = path.res {
1632 if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1633 return new_ty;
1634 }
1635 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1636 return ImplTrait(bounds);
1637 }
1638 }
1639
1640 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1641 expanded
1642 } else {
1643 let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1645 path
1646 } else {
1647 clean_path(path, cx)
1648 };
1649 resolve_type(cx, path)
1650 }
1651 }
1652 hir::QPath::Resolved(Some(qself), p) => {
1653 let ty = lower_ty(cx.tcx, hir_ty);
1655 if !ty.has_escaping_bound_vars()
1657 && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1658 {
1659 return clean_middle_ty(normalized_value, cx, None, None);
1660 }
1661
1662 let trait_segments = &p.segments[..p.segments.len() - 1];
1663 let trait_def = cx.tcx.parent(p.res.def_id());
1664 let trait_ = self::Path {
1665 res: Res::Def(DefKind::Trait, trait_def),
1666 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1667 };
1668 register_res(cx, trait_.res);
1669 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1670 let self_type = clean_ty(qself, cx);
1671 let should_fully_qualify =
1672 should_fully_qualify_path(Some(self_def_id), &trait_, &self_type);
1673 Type::QPath(Box::new(QPathData {
1674 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1675 should_fully_qualify,
1676 self_type,
1677 trait_: Some(trait_),
1678 }))
1679 }
1680 hir::QPath::TypeRelative(qself, segment) => {
1681 let ty = lower_ty(cx.tcx, hir_ty);
1682 let self_type = clean_ty(qself, cx);
1683
1684 let (trait_, should_fully_qualify) = match ty.kind() {
1685 ty::Alias(ty::Projection, proj) => {
1686 let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1687 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1688 register_res(cx, trait_.res);
1689 let self_def_id = res.opt_def_id();
1690 let should_fully_qualify =
1691 should_fully_qualify_path(self_def_id, &trait_, &self_type);
1692
1693 (Some(trait_), should_fully_qualify)
1694 }
1695 ty::Alias(ty::Inherent, _) => (None, false),
1696 ty::Error(_) => return Type::Infer,
1698 _ => bug!("clean: expected associated type, found `{ty:?}`"),
1699 };
1700
1701 Type::QPath(Box::new(QPathData {
1702 assoc: clean_path_segment(segment, cx),
1703 should_fully_qualify,
1704 self_type,
1705 trait_,
1706 }))
1707 }
1708 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1709 }
1710}
1711
1712fn maybe_expand_private_type_alias<'tcx>(
1713 cx: &mut DocContext<'tcx>,
1714 path: &hir::Path<'tcx>,
1715) -> Option<Type> {
1716 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1717 let def_id = def_id.as_local()?;
1719 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1720 && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1721 {
1722 &cx.tcx.hir_expect_item(def_id).kind
1723 } else {
1724 return None;
1725 };
1726 let hir::ItemKind::TyAlias(_, generics, ty) = alias else { return None };
1727
1728 let final_seg = &path.segments.last().expect("segments were empty");
1729 let mut args = DefIdMap::default();
1730 let generic_args = final_seg.args();
1731
1732 let mut indices: hir::GenericParamCount = Default::default();
1733 for param in generics.params.iter() {
1734 match param.kind {
1735 hir::GenericParamKind::Lifetime { .. } => {
1736 let mut j = 0;
1737 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1738 hir::GenericArg::Lifetime(lt) => {
1739 if indices.lifetimes == j {
1740 return Some(lt);
1741 }
1742 j += 1;
1743 None
1744 }
1745 _ => None,
1746 });
1747 if let Some(lt) = lifetime {
1748 let lt = if !lt.is_anonymous() {
1749 clean_lifetime(lt, cx)
1750 } else {
1751 Lifetime::elided()
1752 };
1753 args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1754 }
1755 indices.lifetimes += 1;
1756 }
1757 hir::GenericParamKind::Type { ref default, .. } => {
1758 let mut j = 0;
1759 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1760 hir::GenericArg::Type(ty) => {
1761 if indices.types == j {
1762 return Some(ty.as_unambig_ty());
1763 }
1764 j += 1;
1765 None
1766 }
1767 _ => None,
1768 });
1769 if let Some(ty) = type_.or(*default) {
1770 args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1771 }
1772 indices.types += 1;
1773 }
1774 hir::GenericParamKind::Const { .. } => {}
1776 }
1777 }
1778
1779 Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1780 cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1781 }))
1782}
1783
1784pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1785 use rustc_hir::*;
1786
1787 match ty.kind {
1788 TyKind::Never => Primitive(PrimitiveType::Never),
1789 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1790 TyKind::Ref(l, ref m) => {
1791 let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1792 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1793 }
1794 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1795 TyKind::Pat(ty, pat) => Type::Pat(Box::new(clean_ty(ty, cx)), format!("{pat:?}").into()),
1796 TyKind::Array(ty, const_arg) => {
1797 let length = match const_arg.kind {
1805 hir::ConstArgKind::Infer(..) => "_".to_string(),
1806 hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1807 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1808 let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1809 let ct = cx.tcx.normalize_erasing_regions(typing_env, ct);
1810 print_const(cx, ct)
1811 }
1812 hir::ConstArgKind::Path(..) => {
1813 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1814 print_const(cx, ct)
1815 }
1816 };
1817 Array(Box::new(clean_ty(ty, cx)), length.into())
1818 }
1819 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1820 TyKind::OpaqueDef(ty) => {
1821 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1822 }
1823 TyKind::Path(_) => clean_qpath(ty, cx),
1824 TyKind::TraitObject(bounds, lifetime) => {
1825 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1826 let lifetime = if !lifetime.is_elided() {
1827 Some(clean_lifetime(lifetime.pointer(), cx))
1828 } else {
1829 None
1830 };
1831 DynTrait(bounds, lifetime)
1832 }
1833 TyKind::FnPtr(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1834 TyKind::UnsafeBinder(unsafe_binder_ty) => {
1835 UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1836 }
1837 TyKind::Infer(())
1839 | TyKind::Err(_)
1840 | TyKind::Typeof(..)
1841 | TyKind::InferDelegation(..)
1842 | TyKind::TraitAscription(_) => Infer,
1843 }
1844}
1845
1846fn normalize<'tcx>(
1848 cx: &DocContext<'tcx>,
1849 ty: ty::Binder<'tcx, Ty<'tcx>>,
1850) -> Option<ty::Binder<'tcx, Ty<'tcx>>> {
1851 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1853 return None;
1854 }
1855
1856 use rustc_middle::traits::ObligationCause;
1857 use rustc_trait_selection::infer::TyCtxtInferExt;
1858 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1859
1860 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1862 let normalized = infcx
1863 .at(&ObligationCause::dummy(), cx.param_env)
1864 .query_normalize(ty)
1865 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1866 match normalized {
1867 Ok(normalized_value) => {
1868 debug!("normalized {ty:?} to {normalized_value:?}");
1869 Some(normalized_value)
1870 }
1871 Err(err) => {
1872 debug!("failed to normalize {ty:?}: {err:?}");
1873 None
1874 }
1875 }
1876}
1877
1878fn clean_trait_object_lifetime_bound<'tcx>(
1879 region: ty::Region<'tcx>,
1880 container: Option<ContainerTy<'_, 'tcx>>,
1881 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1882 tcx: TyCtxt<'tcx>,
1883) -> Option<Lifetime> {
1884 if can_elide_trait_object_lifetime_bound(region, container, preds, tcx) {
1885 return None;
1886 }
1887
1888 match region.kind() {
1892 ty::ReStatic => Some(Lifetime::statik()),
1893 ty::ReEarlyParam(region) => Some(Lifetime(region.name)),
1894 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. }) => {
1895 Some(Lifetime(tcx.item_name(def_id)))
1896 }
1897 ty::ReBound(..)
1898 | ty::ReLateParam(_)
1899 | ty::ReVar(_)
1900 | ty::RePlaceholder(_)
1901 | ty::ReErased
1902 | ty::ReError(_) => None,
1903 }
1904}
1905
1906fn can_elide_trait_object_lifetime_bound<'tcx>(
1907 region: ty::Region<'tcx>,
1908 container: Option<ContainerTy<'_, 'tcx>>,
1909 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1910 tcx: TyCtxt<'tcx>,
1911) -> bool {
1912 let default = container
1917 .map_or(ObjectLifetimeDefault::Empty, |container| container.object_lifetime_default(tcx));
1918
1919 match default {
1922 ObjectLifetimeDefault::Static => return region.kind() == ty::ReStatic,
1923 ObjectLifetimeDefault::Arg(default) => {
1925 return region.get_name(tcx) == default.get_name(tcx);
1926 }
1927 ObjectLifetimeDefault::Ambiguous => return false,
1931 ObjectLifetimeDefault::Empty => {}
1933 }
1934
1935 match *object_region_bounds(tcx, preds) {
1937 [] => region.kind() == ty::ReStatic,
1945 [object_region] => object_region.get_name(tcx) == region.get_name(tcx),
1949 _ => false,
1953 }
1954}
1955
1956#[derive(Debug)]
1957pub(crate) enum ContainerTy<'a, 'tcx> {
1958 Ref(ty::Region<'tcx>),
1959 Regular {
1960 ty: DefId,
1961 args: ty::Binder<'tcx, &'a [ty::GenericArg<'tcx>]>,
1964 arg: usize,
1965 },
1966}
1967
1968impl<'tcx> ContainerTy<'_, 'tcx> {
1969 fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> {
1970 match self {
1971 Self::Ref(region) => ObjectLifetimeDefault::Arg(region),
1972 Self::Regular { ty: container, args, arg: index } => {
1973 let (DefKind::Struct
1974 | DefKind::Union
1975 | DefKind::Enum
1976 | DefKind::TyAlias
1977 | DefKind::Trait) = tcx.def_kind(container)
1978 else {
1979 return ObjectLifetimeDefault::Empty;
1980 };
1981
1982 let generics = tcx.generics_of(container);
1983 debug_assert_eq!(generics.parent_count, 0);
1984
1985 let param = generics.own_params[index].def_id;
1986 let default = tcx.object_lifetime_default(param);
1987 match default {
1988 rbv::ObjectLifetimeDefault::Param(lifetime) => {
1989 let index = generics.param_def_id_to_index[&lifetime];
1992 let arg = args.skip_binder()[index as usize].expect_region();
1993 ObjectLifetimeDefault::Arg(arg)
1994 }
1995 rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty,
1996 rbv::ObjectLifetimeDefault::Static => ObjectLifetimeDefault::Static,
1997 rbv::ObjectLifetimeDefault::Ambiguous => ObjectLifetimeDefault::Ambiguous,
1998 }
1999 }
2000 }
2001 }
2002}
2003
2004#[derive(Debug, Clone, Copy)]
2005pub(crate) enum ObjectLifetimeDefault<'tcx> {
2006 Empty,
2007 Static,
2008 Ambiguous,
2009 Arg(ty::Region<'tcx>),
2010}
2011
2012#[instrument(level = "trace", skip(cx), ret)]
2013pub(crate) fn clean_middle_ty<'tcx>(
2014 bound_ty: ty::Binder<'tcx, Ty<'tcx>>,
2015 cx: &mut DocContext<'tcx>,
2016 parent_def_id: Option<DefId>,
2017 container: Option<ContainerTy<'_, 'tcx>>,
2018) -> Type {
2019 let bound_ty = normalize(cx, bound_ty).unwrap_or(bound_ty);
2020 match *bound_ty.skip_binder().kind() {
2021 ty::Never => Primitive(PrimitiveType::Never),
2022 ty::Bool => Primitive(PrimitiveType::Bool),
2023 ty::Char => Primitive(PrimitiveType::Char),
2024 ty::Int(int_ty) => Primitive(int_ty.into()),
2025 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
2026 ty::Float(float_ty) => Primitive(float_ty.into()),
2027 ty::Str => Primitive(PrimitiveType::Str),
2028 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None))),
2029 ty::Pat(ty, pat) => Type::Pat(
2030 Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)),
2031 format!("{pat:?}").into_boxed_str(),
2032 ),
2033 ty::Array(ty, n) => {
2034 let n = cx.tcx.normalize_erasing_regions(cx.typing_env(), n);
2035 let n = print_const(cx, n);
2036 Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into())
2037 }
2038 ty::RawPtr(ty, mutbl) => {
2039 RawPointer(mutbl, Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)))
2040 }
2041 ty::Ref(r, ty, mutbl) => BorrowedRef {
2042 lifetime: clean_middle_region(r, cx),
2043 mutability: mutbl,
2044 type_: Box::new(clean_middle_ty(
2045 bound_ty.rebind(ty),
2046 cx,
2047 None,
2048 Some(ContainerTy::Ref(r)),
2049 )),
2050 },
2051 ty::FnDef(..) | ty::FnPtr(..) => {
2052 let sig = bound_ty.skip_binder().fn_sig(cx.tcx);
2054 let decl = clean_poly_fn_sig(cx, None, sig);
2055 let generic_params = clean_bound_vars(sig.bound_vars(), cx);
2056
2057 BareFunction(Box::new(BareFunctionDecl {
2058 safety: sig.safety(),
2059 generic_params,
2060 decl,
2061 abi: sig.abi(),
2062 }))
2063 }
2064 ty::UnsafeBinder(inner) => {
2065 let generic_params = clean_bound_vars(inner.bound_vars(), cx);
2066 let ty = clean_middle_ty(inner.into(), cx, None, None);
2067 UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, ty }))
2068 }
2069 ty::Adt(def, args) => {
2070 let did = def.did();
2071 let kind = match def.adt_kind() {
2072 AdtKind::Struct => ItemType::Struct,
2073 AdtKind::Union => ItemType::Union,
2074 AdtKind::Enum => ItemType::Enum,
2075 };
2076 inline::record_extern_fqn(cx, did, kind);
2077 let path = clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args));
2078 Type::Path { path }
2079 }
2080 ty::Foreign(did) => {
2081 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
2082 let path = clean_middle_path(
2083 cx,
2084 did,
2085 false,
2086 ThinVec::new(),
2087 ty::Binder::dummy(ty::GenericArgs::empty()),
2088 );
2089 Type::Path { path }
2090 }
2091 ty::Dynamic(obj, reg, _) => {
2092 let mut dids = obj.auto_traits();
2096 let did = obj
2097 .principal_def_id()
2098 .or_else(|| dids.next())
2099 .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?"));
2100 let args = match obj.principal() {
2101 Some(principal) => principal.map_bound(|p| p.args),
2102 _ => ty::Binder::dummy(ty::GenericArgs::empty()),
2104 };
2105
2106 inline::record_extern_fqn(cx, did, ItemType::Trait);
2107
2108 let lifetime = clean_trait_object_lifetime_bound(reg, container, obj, cx.tcx);
2109
2110 let mut bounds = dids
2111 .map(|did| {
2112 let empty = ty::Binder::dummy(ty::GenericArgs::empty());
2113 let path = clean_middle_path(cx, did, false, ThinVec::new(), empty);
2114 inline::record_extern_fqn(cx, did, ItemType::Trait);
2115 PolyTrait { trait_: path, generic_params: Vec::new() }
2116 })
2117 .collect::<Vec<_>>();
2118
2119 let constraints = obj
2120 .projection_bounds()
2121 .map(|pb| AssocItemConstraint {
2122 assoc: projection_to_path_segment(
2123 pb.map_bound(|pb| {
2124 pb.with_self_ty(cx.tcx, cx.tcx.types.trait_object_dummy_self)
2125 .projection_term
2126 }),
2127 cx,
2128 ),
2129 kind: AssocItemConstraintKind::Equality {
2130 term: clean_middle_term(pb.map_bound(|pb| pb.term), cx),
2131 },
2132 })
2133 .collect();
2134
2135 let late_bound_regions: FxIndexSet<_> = obj
2136 .iter()
2137 .flat_map(|pred| pred.bound_vars())
2138 .filter_map(|var| match var {
2139 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
2140 let name = cx.tcx.item_name(def_id);
2141 if name != kw::UnderscoreLifetime {
2142 Some(GenericParamDef::lifetime(def_id, name))
2143 } else {
2144 None
2145 }
2146 }
2147 _ => None,
2148 })
2149 .collect();
2150 let late_bound_regions = late_bound_regions.into_iter().collect();
2151
2152 let path = clean_middle_path(cx, did, false, constraints, args);
2153 bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
2154
2155 DynTrait(bounds, lifetime)
2156 }
2157 ty::Tuple(t) => {
2158 Tuple(t.iter().map(|t| clean_middle_ty(bound_ty.rebind(t), cx, None, None)).collect())
2159 }
2160
2161 ty::Alias(ty::Projection, alias_ty @ ty::AliasTy { def_id, args, .. }) => {
2162 if cx.tcx.is_impl_trait_in_trait(def_id) {
2163 clean_middle_opaque_bounds(cx, def_id, args)
2164 } else {
2165 Type::QPath(Box::new(clean_projection(
2166 bound_ty.rebind(alias_ty.into()),
2167 cx,
2168 parent_def_id,
2169 )))
2170 }
2171 }
2172
2173 ty::Alias(ty::Inherent, alias_ty @ ty::AliasTy { def_id, .. }) => {
2174 let alias_ty = bound_ty.rebind(alias_ty);
2175 let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None, None);
2176
2177 Type::QPath(Box::new(QPathData {
2178 assoc: PathSegment {
2179 name: cx.tcx.item_name(def_id),
2180 args: GenericArgs::AngleBracketed {
2181 args: clean_middle_generic_args(
2182 cx,
2183 alias_ty.map_bound(|ty| ty.args.as_slice()),
2184 true,
2185 def_id,
2186 ),
2187 constraints: Default::default(),
2188 },
2189 },
2190 should_fully_qualify: false,
2191 self_type,
2192 trait_: None,
2193 }))
2194 }
2195
2196 ty::Alias(ty::Free, ty::AliasTy { def_id, args, .. }) => {
2197 if cx.tcx.features().lazy_type_alias() {
2198 let path =
2201 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2202 Type::Path { path }
2203 } else {
2204 let ty = cx.tcx.type_of(def_id).instantiate(cx.tcx, args);
2205 clean_middle_ty(bound_ty.rebind(ty), cx, None, None)
2206 }
2207 }
2208
2209 ty::Param(ref p) => {
2210 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
2211 ImplTrait(bounds)
2212 } else if p.name == kw::SelfUpper {
2213 SelfTy
2214 } else {
2215 Generic(p.name)
2216 }
2217 }
2218
2219 ty::Bound(_, ref ty) => match ty.kind {
2220 ty::BoundTyKind::Param(def_id) => Generic(cx.tcx.item_name(def_id)),
2221 ty::BoundTyKind::Anon => panic!("unexpected anonymous bound type variable"),
2222 },
2223
2224 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2225 if cx.current_type_aliases.contains_key(&def_id) {
2227 let path =
2228 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2229 Type::Path { path }
2230 } else {
2231 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2232 let ty = clean_middle_opaque_bounds(cx, def_id, args);
2235 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2236 *count -= 1;
2237 if *count == 0 {
2238 cx.current_type_aliases.remove(&def_id);
2239 }
2240 }
2241 ty
2242 }
2243 }
2244
2245 ty::Closure(..) => panic!("Closure"),
2246 ty::CoroutineClosure(..) => panic!("CoroutineClosure"),
2247 ty::Coroutine(..) => panic!("Coroutine"),
2248 ty::Placeholder(..) => panic!("Placeholder"),
2249 ty::CoroutineWitness(..) => panic!("CoroutineWitness"),
2250 ty::Infer(..) => panic!("Infer"),
2251
2252 ty::Error(_) => FatalError.raise(),
2253 }
2254}
2255
2256fn clean_middle_opaque_bounds<'tcx>(
2257 cx: &mut DocContext<'tcx>,
2258 impl_trait_def_id: DefId,
2259 args: ty::GenericArgsRef<'tcx>,
2260) -> Type {
2261 let mut has_sized = false;
2262
2263 let bounds: Vec<_> = cx
2264 .tcx
2265 .explicit_item_bounds(impl_trait_def_id)
2266 .iter_instantiated_copied(cx.tcx, args)
2267 .collect();
2268
2269 let mut bounds = bounds
2270 .iter()
2271 .filter_map(|(bound, _)| {
2272 let bound_predicate = bound.kind();
2273 let trait_ref = match bound_predicate.skip_binder() {
2274 ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
2275 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
2276 return clean_middle_region(reg, cx).map(GenericBound::Outlives);
2277 }
2278 _ => return None,
2279 };
2280
2281 if cx.tcx.is_lang_item(trait_ref.def_id(), LangItem::MetaSized) {
2284 return None;
2285 }
2286
2287 if let Some(sized) = cx.tcx.lang_items().sized_trait()
2288 && trait_ref.def_id() == sized
2289 {
2290 has_sized = true;
2291 return None;
2292 }
2293
2294 let bindings: ThinVec<_> = bounds
2295 .iter()
2296 .filter_map(|(bound, _)| {
2297 let bound = bound.kind();
2298 if let ty::ClauseKind::Projection(proj_pred) = bound.skip_binder()
2299 && proj_pred.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
2300 {
2301 return Some(AssocItemConstraint {
2302 assoc: projection_to_path_segment(
2303 bound.rebind(proj_pred.projection_term),
2304 cx,
2305 ),
2306 kind: AssocItemConstraintKind::Equality {
2307 term: clean_middle_term(bound.rebind(proj_pred.term), cx),
2308 },
2309 });
2310 }
2311 None
2312 })
2313 .collect();
2314
2315 Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings))
2316 })
2317 .collect::<Vec<_>>();
2318
2319 if !has_sized {
2320 bounds.push(GenericBound::maybe_sized(cx));
2321 }
2322
2323 bounds.sort_by_key(|b| !b.is_trait_bound());
2325
2326 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
2329 bounds.insert(0, GenericBound::sized(cx));
2330 }
2331
2332 if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) {
2333 bounds.push(GenericBound::Use(
2334 args.iter()
2335 .map(|arg| match arg {
2336 hir::PreciseCapturingArgKind::Lifetime(lt) => {
2337 PreciseCapturingArg::Lifetime(Lifetime(*lt))
2338 }
2339 hir::PreciseCapturingArgKind::Param(param) => {
2340 PreciseCapturingArg::Param(*param)
2341 }
2342 })
2343 .collect(),
2344 ));
2345 }
2346
2347 ImplTrait(bounds)
2348}
2349
2350pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2351 clean_field_with_def_id(field.def_id.to_def_id(), field.ident.name, clean_ty(field.ty, cx), cx)
2352}
2353
2354pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item {
2355 clean_field_with_def_id(
2356 field.did,
2357 field.name,
2358 clean_middle_ty(
2359 ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity()),
2360 cx,
2361 Some(field.did),
2362 None,
2363 ),
2364 cx,
2365 )
2366}
2367
2368pub(crate) fn clean_field_with_def_id(
2369 def_id: DefId,
2370 name: Symbol,
2371 ty: Type,
2372 cx: &mut DocContext<'_>,
2373) -> Item {
2374 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
2375}
2376
2377pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item {
2378 let discriminant = match variant.discr {
2379 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2380 ty::VariantDiscr::Relative(_) => None,
2381 };
2382
2383 let kind = match variant.ctor_kind() {
2384 Some(CtorKind::Const) => VariantKind::CLike,
2385 Some(CtorKind::Fn) => VariantKind::Tuple(
2386 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2387 ),
2388 None => VariantKind::Struct(VariantStruct {
2389 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2390 }),
2391 };
2392
2393 Item::from_def_id_and_parts(
2394 variant.def_id,
2395 Some(variant.name),
2396 VariantItem(Variant { kind, discriminant }),
2397 cx,
2398 )
2399}
2400
2401pub(crate) fn clean_variant_def_with_args<'tcx>(
2402 variant: &ty::VariantDef,
2403 args: &GenericArgsRef<'tcx>,
2404 cx: &mut DocContext<'tcx>,
2405) -> Item {
2406 let discriminant = match variant.discr {
2407 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2408 ty::VariantDiscr::Relative(_) => None,
2409 };
2410
2411 use rustc_middle::traits::ObligationCause;
2412 use rustc_trait_selection::infer::TyCtxtInferExt;
2413 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
2414
2415 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2416 let kind = match variant.ctor_kind() {
2417 Some(CtorKind::Const) => VariantKind::CLike,
2418 Some(CtorKind::Fn) => VariantKind::Tuple(
2419 variant
2420 .fields
2421 .iter()
2422 .map(|field| {
2423 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2424
2425 let ty = infcx
2429 .at(&ObligationCause::dummy(), cx.param_env)
2430 .query_normalize(ty)
2431 .map(|normalized| normalized.value)
2432 .unwrap_or(ty);
2433
2434 clean_field_with_def_id(
2435 field.did,
2436 field.name,
2437 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2438 cx,
2439 )
2440 })
2441 .collect(),
2442 ),
2443 None => VariantKind::Struct(VariantStruct {
2444 fields: variant
2445 .fields
2446 .iter()
2447 .map(|field| {
2448 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2449
2450 let ty = infcx
2454 .at(&ObligationCause::dummy(), cx.param_env)
2455 .query_normalize(ty)
2456 .map(|normalized| normalized.value)
2457 .unwrap_or(ty);
2458
2459 clean_field_with_def_id(
2460 field.did,
2461 field.name,
2462 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2463 cx,
2464 )
2465 })
2466 .collect(),
2467 }),
2468 };
2469
2470 Item::from_def_id_and_parts(
2471 variant.def_id,
2472 Some(variant.name),
2473 VariantItem(Variant { kind, discriminant }),
2474 cx,
2475 )
2476}
2477
2478fn clean_variant_data<'tcx>(
2479 variant: &hir::VariantData<'tcx>,
2480 disr_expr: &Option<&hir::AnonConst>,
2481 cx: &mut DocContext<'tcx>,
2482) -> Variant {
2483 let discriminant = disr_expr
2484 .map(|disr| Discriminant { expr: Some(disr.body), value: disr.def_id.to_def_id() });
2485
2486 let kind = match variant {
2487 hir::VariantData::Struct { fields, .. } => VariantKind::Struct(VariantStruct {
2488 fields: fields.iter().map(|x| clean_field(x, cx)).collect(),
2489 }),
2490 hir::VariantData::Tuple(..) => {
2491 VariantKind::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
2492 }
2493 hir::VariantData::Unit(..) => VariantKind::CLike,
2494 };
2495
2496 Variant { discriminant, kind }
2497}
2498
2499fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
2500 Path {
2501 res: path.res,
2502 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
2503 }
2504}
2505
2506fn clean_generic_args<'tcx>(
2507 generic_args: &hir::GenericArgs<'tcx>,
2508 cx: &mut DocContext<'tcx>,
2509) -> GenericArgs {
2510 match generic_args.parenthesized {
2511 hir::GenericArgsParentheses::No => {
2512 let args = generic_args
2513 .args
2514 .iter()
2515 .map(|arg| match arg {
2516 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
2517 GenericArg::Lifetime(clean_lifetime(lt, cx))
2518 }
2519 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2520 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)),
2521 hir::GenericArg::Const(ct) => {
2522 GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct(), cx)))
2523 }
2524 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
2525 })
2526 .collect();
2527 let constraints = generic_args
2528 .constraints
2529 .iter()
2530 .map(|c| clean_assoc_item_constraint(c, cx))
2531 .collect::<ThinVec<_>>();
2532 GenericArgs::AngleBracketed { args, constraints }
2533 }
2534 hir::GenericArgsParentheses::ParenSugar => {
2535 let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else {
2536 bug!();
2537 };
2538 let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect();
2539 let output = match output.kind {
2540 hir::TyKind::Tup(&[]) => None,
2541 _ => Some(Box::new(clean_ty(output, cx))),
2542 };
2543 GenericArgs::Parenthesized { inputs, output }
2544 }
2545 hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
2546 }
2547}
2548
2549fn clean_path_segment<'tcx>(
2550 path: &hir::PathSegment<'tcx>,
2551 cx: &mut DocContext<'tcx>,
2552) -> PathSegment {
2553 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
2554}
2555
2556fn clean_bare_fn_ty<'tcx>(
2557 bare_fn: &hir::FnPtrTy<'tcx>,
2558 cx: &mut DocContext<'tcx>,
2559) -> BareFunctionDecl {
2560 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
2561 let generic_params = bare_fn
2563 .generic_params
2564 .iter()
2565 .filter(|p| !is_elided_lifetime(p))
2566 .map(|x| clean_generic_param(cx, None, x))
2567 .collect();
2568 let filter = |ident: Option<Ident>| {
2572 ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore)
2573 };
2574 let fallback =
2575 bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore);
2576 let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents, |ident| {
2577 filter(ident).or(fallback)
2578 });
2579 let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params);
2580 (generic_params, decl)
2581 });
2582 BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params }
2583}
2584
2585fn clean_unsafe_binder_ty<'tcx>(
2586 unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>,
2587 cx: &mut DocContext<'tcx>,
2588) -> UnsafeBinderTy {
2589 let generic_params = unsafe_binder_ty
2590 .generic_params
2591 .iter()
2592 .filter(|p| !is_elided_lifetime(p))
2593 .map(|x| clean_generic_param(cx, None, x))
2594 .collect();
2595 let ty = clean_ty(unsafe_binder_ty.inner_ty, cx);
2596 UnsafeBinderTy { generic_params, ty }
2597}
2598
2599pub(crate) fn reexport_chain(
2600 tcx: TyCtxt<'_>,
2601 import_def_id: LocalDefId,
2602 target_def_id: DefId,
2603) -> &[Reexport] {
2604 for child in tcx.module_children_local(tcx.local_parent(import_def_id)) {
2605 if child.res.opt_def_id() == Some(target_def_id)
2606 && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id())
2607 {
2608 return &child.reexport_chain;
2609 }
2610 }
2611 &[]
2612}
2613
2614fn get_all_import_attributes<'hir>(
2616 cx: &mut DocContext<'hir>,
2617 import_def_id: LocalDefId,
2618 target_def_id: DefId,
2619 is_inline: bool,
2620) -> Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)> {
2621 let mut attrs = Vec::new();
2622 let mut first = true;
2623 for def_id in reexport_chain(cx.tcx, import_def_id, target_def_id)
2624 .iter()
2625 .flat_map(|reexport| reexport.id())
2626 {
2627 let import_attrs = inline::load_attrs(cx, def_id);
2628 if first {
2629 attrs = import_attrs.iter().map(|attr| (Cow::Borrowed(attr), Some(def_id))).collect();
2631 first = false;
2632 } else if cx.render_options.document_hidden || !cx.tcx.is_doc_hidden(def_id) {
2634 add_without_unwanted_attributes(&mut attrs, import_attrs, is_inline, Some(def_id));
2635 }
2636 }
2637 attrs
2638}
2639
2640fn filter_tokens_from_list(
2641 args_tokens: &TokenStream,
2642 should_retain: impl Fn(&TokenTree) -> bool,
2643) -> Vec<TokenTree> {
2644 let mut tokens = Vec::with_capacity(args_tokens.len());
2645 let mut skip_next_comma = false;
2646 for token in args_tokens.iter() {
2647 match token {
2648 TokenTree::Token(Token { kind: TokenKind::Comma, .. }, _) if skip_next_comma => {
2649 skip_next_comma = false;
2650 }
2651 token if should_retain(token) => {
2652 skip_next_comma = false;
2653 tokens.push(token.clone());
2654 }
2655 _ => {
2656 skip_next_comma = true;
2657 }
2658 }
2659 }
2660 tokens
2661}
2662
2663fn filter_doc_attr_ident(ident: Symbol, is_inline: bool) -> bool {
2664 if is_inline {
2665 ident == sym::hidden || ident == sym::inline || ident == sym::no_inline
2666 } else {
2667 ident == sym::cfg
2668 }
2669}
2670
2671fn filter_doc_attr(args: &mut hir::AttrArgs, is_inline: bool) {
2674 match args {
2675 hir::AttrArgs::Delimited(args) => {
2676 let tokens = filter_tokens_from_list(&args.tokens, |token| {
2677 !matches!(
2678 token,
2679 TokenTree::Token(
2680 Token {
2681 kind: TokenKind::Ident(
2682 ident,
2683 _,
2684 ),
2685 ..
2686 },
2687 _,
2688 ) if filter_doc_attr_ident(*ident, is_inline),
2689 )
2690 });
2691 args.tokens = TokenStream::new(tokens);
2692 }
2693 hir::AttrArgs::Empty | hir::AttrArgs::Eq { .. } => {}
2694 }
2695}
2696
2697fn add_without_unwanted_attributes<'hir>(
2718 attrs: &mut Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)>,
2719 new_attrs: &'hir [hir::Attribute],
2720 is_inline: bool,
2721 import_parent: Option<DefId>,
2722) {
2723 for attr in new_attrs {
2724 if attr.is_doc_comment() {
2725 attrs.push((Cow::Borrowed(attr), import_parent));
2726 continue;
2727 }
2728 let mut attr = attr.clone();
2729 match attr {
2730 hir::Attribute::Unparsed(ref mut normal) if let [ident] = &*normal.path.segments => {
2731 let ident = ident.name;
2732 if ident == sym::doc {
2733 filter_doc_attr(&mut normal.args, is_inline);
2734 attrs.push((Cow::Owned(attr), import_parent));
2735 } else if is_inline || ident != sym::cfg_trace {
2736 attrs.push((Cow::Owned(attr), import_parent));
2738 }
2739 }
2740 hir::Attribute::Parsed(..) => {
2742 attrs.push((Cow::Owned(attr), import_parent));
2743 }
2744 _ => {}
2745 }
2746 }
2747}
2748
2749fn clean_maybe_renamed_item<'tcx>(
2750 cx: &mut DocContext<'tcx>,
2751 item: &hir::Item<'tcx>,
2752 renamed: Option<Symbol>,
2753 import_ids: &[LocalDefId],
2754) -> Vec<Item> {
2755 use hir::ItemKind;
2756 fn get_name(
2757 cx: &DocContext<'_>,
2758 item: &hir::Item<'_>,
2759 renamed: Option<Symbol>,
2760 ) -> Option<Symbol> {
2761 renamed.or_else(|| cx.tcx.hir_opt_name(item.hir_id()))
2762 }
2763
2764 let def_id = item.owner_id.to_def_id();
2765 cx.with_param_env(def_id, |cx| {
2766 match item.kind {
2769 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.owner_id.def_id, cx),
2770 ItemKind::Use(path, kind) => {
2771 return clean_use_statement(
2772 item,
2773 get_name(cx, item, renamed),
2774 path,
2775 kind,
2776 cx,
2777 &mut FxHashSet::default(),
2778 );
2779 }
2780 _ => {}
2781 }
2782
2783 let mut name = get_name(cx, item, renamed).unwrap();
2784
2785 let kind = match item.kind {
2786 ItemKind::Static(mutability, _, ty, body_id) => StaticItem(Static {
2787 type_: Box::new(clean_ty(ty, cx)),
2788 mutability,
2789 expr: Some(body_id),
2790 }),
2791 ItemKind::Const(_, generics, ty, body_id) => ConstantItem(Box::new(Constant {
2792 generics: clean_generics(generics, cx),
2793 type_: clean_ty(ty, cx),
2794 kind: ConstantKind::Local { body: body_id, def_id },
2795 })),
2796 ItemKind::TyAlias(_, generics, ty) => {
2797 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2798 let rustdoc_ty = clean_ty(ty, cx);
2799 let type_ =
2800 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, ty)), cx, None, None);
2801 let generics = clean_generics(generics, cx);
2802 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2803 *count -= 1;
2804 if *count == 0 {
2805 cx.current_type_aliases.remove(&def_id);
2806 }
2807 }
2808
2809 let ty = cx.tcx.type_of(def_id).instantiate_identity();
2810
2811 let mut ret = Vec::new();
2812 let inner_type = clean_ty_alias_inner_type(ty, cx, &mut ret);
2813
2814 ret.push(generate_item_with_correct_attrs(
2815 cx,
2816 TypeAliasItem(Box::new(TypeAlias {
2817 generics,
2818 inner_type,
2819 type_: rustdoc_ty,
2820 item_type: Some(type_),
2821 })),
2822 item.owner_id.def_id.to_def_id(),
2823 name,
2824 import_ids,
2825 renamed,
2826 ));
2827 return ret;
2828 }
2829 ItemKind::Enum(_, generics, def) => EnumItem(Enum {
2830 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2831 generics: clean_generics(generics, cx),
2832 }),
2833 ItemKind::TraitAlias(_, generics, bounds) => TraitAliasItem(TraitAlias {
2834 generics: clean_generics(generics, cx),
2835 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2836 }),
2837 ItemKind::Union(_, generics, variant_data) => UnionItem(Union {
2838 generics: clean_generics(generics, cx),
2839 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2840 }),
2841 ItemKind::Struct(_, generics, variant_data) => StructItem(Struct {
2842 ctor_kind: variant_data.ctor_kind(),
2843 generics: clean_generics(generics, cx),
2844 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2845 }),
2846 ItemKind::Macro(_, macro_def, MacroKinds::BANG) => MacroItem(Macro {
2849 source: display_macro_source(cx, name, macro_def),
2850 macro_rules: macro_def.macro_rules,
2851 }),
2852 ItemKind::Macro(_, _, MacroKinds::ATTR) => {
2853 clean_proc_macro(item, &mut name, MacroKind::Attr, cx)
2854 }
2855 ItemKind::Macro(_, _, MacroKinds::DERIVE) => {
2856 clean_proc_macro(item, &mut name, MacroKind::Derive, cx)
2857 }
2858 ItemKind::Macro(_, _, _) => todo!("Handle macros with multiple kinds"),
2859 ItemKind::Fn { ref sig, generics, body: body_id, .. } => {
2861 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2862 }
2863 ItemKind::Trait(_, _, _, _, generics, bounds, item_ids) => {
2864 let items = item_ids
2865 .iter()
2866 .map(|&ti| clean_trait_item(cx.tcx.hir_trait_item(ti), cx))
2867 .collect();
2868
2869 TraitItem(Box::new(Trait {
2870 def_id,
2871 items,
2872 generics: clean_generics(generics, cx),
2873 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2874 }))
2875 }
2876 ItemKind::ExternCrate(orig_name, _) => {
2877 return clean_extern_crate(item, name, orig_name, cx);
2878 }
2879 _ => span_bug!(item.span, "not yet converted"),
2880 };
2881
2882 vec![generate_item_with_correct_attrs(
2883 cx,
2884 kind,
2885 item.owner_id.def_id.to_def_id(),
2886 name,
2887 import_ids,
2888 renamed,
2889 )]
2890 })
2891}
2892
2893fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2894 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2895 Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx)
2896}
2897
2898fn clean_impl<'tcx>(
2899 impl_: &hir::Impl<'tcx>,
2900 def_id: LocalDefId,
2901 cx: &mut DocContext<'tcx>,
2902) -> Vec<Item> {
2903 let tcx = cx.tcx;
2904 let mut ret = Vec::new();
2905 let trait_ = impl_.of_trait.map(|t| clean_trait_ref(&t.trait_ref, cx));
2906 let items = impl_
2907 .items
2908 .iter()
2909 .map(|&ii| clean_impl_item(tcx.hir_impl_item(ii), cx))
2910 .collect::<Vec<_>>();
2911
2912 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2915 build_deref_target_impls(cx, &items, &mut ret);
2916 }
2917
2918 let for_ = clean_ty(impl_.self_ty, cx);
2919 let type_alias =
2920 for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) {
2921 DefKind::TyAlias => Some(clean_middle_ty(
2922 ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()),
2923 cx,
2924 Some(def_id.to_def_id()),
2925 None,
2926 )),
2927 _ => None,
2928 });
2929 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2930 let kind = ImplItem(Box::new(Impl {
2931 safety: match impl_.of_trait {
2932 Some(of_trait) => of_trait.safety,
2933 None => hir::Safety::Safe,
2934 },
2935 generics: clean_generics(impl_.generics, cx),
2936 trait_,
2937 for_,
2938 items,
2939 polarity: tcx.impl_polarity(def_id),
2940 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2941 ImplKind::FakeVariadic
2942 } else {
2943 ImplKind::Normal
2944 },
2945 }));
2946 Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, cx)
2947 };
2948 if let Some(type_alias) = type_alias {
2949 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2950 }
2951 ret.push(make_item(trait_, for_, items));
2952 ret
2953}
2954
2955fn clean_extern_crate<'tcx>(
2956 krate: &hir::Item<'tcx>,
2957 name: Symbol,
2958 orig_name: Option<Symbol>,
2959 cx: &mut DocContext<'tcx>,
2960) -> Vec<Item> {
2961 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2963 let crate_def_id = cnum.as_def_id();
2965 let attrs = cx.tcx.hir_attrs(krate.hir_id());
2966 let ty_vis = cx.tcx.visibility(krate.owner_id);
2967 let please_inline = ty_vis.is_public()
2968 && attrs.iter().any(|a| {
2969 a.has_name(sym::doc)
2970 && match a.meta_item_list() {
2971 Some(l) => ast::attr::list_contains_name(&l, sym::inline),
2972 None => false,
2973 }
2974 })
2975 && !cx.is_json_output();
2976
2977 let krate_owner_def_id = krate.owner_id.def_id;
2978
2979 if please_inline
2980 && let Some(items) = inline::try_inline(
2981 cx,
2982 Res::Def(DefKind::Mod, crate_def_id),
2983 name,
2984 Some((attrs, Some(krate_owner_def_id))),
2985 &mut Default::default(),
2986 )
2987 {
2988 return items;
2989 }
2990
2991 vec![Item::from_def_id_and_parts(
2992 krate_owner_def_id.to_def_id(),
2993 Some(name),
2994 ExternCrateItem { src: orig_name },
2995 cx,
2996 )]
2997}
2998
2999fn clean_use_statement<'tcx>(
3000 import: &hir::Item<'tcx>,
3001 name: Option<Symbol>,
3002 path: &hir::UsePath<'tcx>,
3003 kind: hir::UseKind,
3004 cx: &mut DocContext<'tcx>,
3005 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3006) -> Vec<Item> {
3007 let mut items = Vec::new();
3008 let hir::UsePath { segments, ref res, span } = *path;
3009 for res in res.present_items() {
3010 let path = hir::Path { segments, res, span };
3011 items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
3012 }
3013 items
3014}
3015
3016fn clean_use_statement_inner<'tcx>(
3017 import: &hir::Item<'tcx>,
3018 name: Option<Symbol>,
3019 path: &hir::Path<'tcx>,
3020 kind: hir::UseKind,
3021 cx: &mut DocContext<'tcx>,
3022 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3023) -> Vec<Item> {
3024 if should_ignore_res(path.res) {
3025 return Vec::new();
3026 }
3027 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
3031 return Vec::new();
3032 }
3033
3034 let visibility = cx.tcx.visibility(import.owner_id);
3035 let attrs = cx.tcx.hir_attrs(import.hir_id());
3036 let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline);
3037 let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
3038 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
3039 let import_def_id = import.owner_id.def_id;
3040
3041 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
3045
3046 let is_visible_from_parent_mod =
3052 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3053
3054 if pub_underscore && let Some(ref inline) = inline_attr {
3055 struct_span_code_err!(
3056 cx.tcx.dcx(),
3057 inline.span(),
3058 E0780,
3059 "anonymous imports cannot be inlined"
3060 )
3061 .with_span_label(import.span, "anonymous import")
3062 .emit();
3063 }
3064
3065 let mut denied = cx.is_json_output()
3070 || !(visibility.is_public()
3071 || (cx.render_options.document_private && is_visible_from_parent_mod))
3072 || pub_underscore
3073 || attrs.iter().any(|a| {
3074 a.has_name(sym::doc)
3075 && match a.meta_item_list() {
3076 Some(l) => {
3077 ast::attr::list_contains_name(&l, sym::no_inline)
3078 || ast::attr::list_contains_name(&l, sym::hidden)
3079 }
3080 None => false,
3081 }
3082 });
3083
3084 let path = clean_path(path, cx);
3087 let inner = if kind == hir::UseKind::Glob {
3088 if !denied {
3089 let mut visited = DefIdSet::default();
3090 if let Some(items) = inline::try_inline_glob(
3091 cx,
3092 path.res,
3093 current_mod,
3094 &mut visited,
3095 inlined_names,
3096 import,
3097 ) {
3098 return items;
3099 }
3100 }
3101 Import::new_glob(resolve_use_source(cx, path), true)
3102 } else {
3103 let name = name.unwrap();
3104 if inline_attr.is_none()
3105 && let Res::Def(DefKind::Mod, did) = path.res
3106 && !did.is_local()
3107 && did.is_crate_root()
3108 {
3109 denied = true;
3112 }
3113 if !denied
3114 && let Some(mut items) = inline::try_inline(
3115 cx,
3116 path.res,
3117 name,
3118 Some((attrs, Some(import_def_id))),
3119 &mut Default::default(),
3120 )
3121 {
3122 items.push(Item::from_def_id_and_parts(
3123 import_def_id.to_def_id(),
3124 None,
3125 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3126 cx,
3127 ));
3128 return items;
3129 }
3130 Import::new_simple(name, resolve_use_source(cx, path), true)
3131 };
3132
3133 vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx)]
3134}
3135
3136fn clean_maybe_renamed_foreign_item<'tcx>(
3137 cx: &mut DocContext<'tcx>,
3138 item: &hir::ForeignItem<'tcx>,
3139 renamed: Option<Symbol>,
3140 import_id: Option<LocalDefId>,
3141) -> Item {
3142 let def_id = item.owner_id.to_def_id();
3143 cx.with_param_env(def_id, |cx| {
3144 let kind = match item.kind {
3145 hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3146 clean_function(cx, &sig, generics, ParamsSrc::Idents(idents)),
3147 sig.header.safety(),
3148 ),
3149 hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3150 Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3151 safety,
3152 ),
3153 hir::ForeignItemKind::Type => ForeignTypeItem,
3154 };
3155
3156 generate_item_with_correct_attrs(
3157 cx,
3158 kind,
3159 item.owner_id.def_id.to_def_id(),
3160 item.ident.name,
3161 import_id.as_slice(),
3162 renamed,
3163 )
3164 })
3165}
3166
3167fn clean_assoc_item_constraint<'tcx>(
3168 constraint: &hir::AssocItemConstraint<'tcx>,
3169 cx: &mut DocContext<'tcx>,
3170) -> AssocItemConstraint {
3171 AssocItemConstraint {
3172 assoc: PathSegment {
3173 name: constraint.ident.name,
3174 args: clean_generic_args(constraint.gen_args, cx),
3175 },
3176 kind: match constraint.kind {
3177 hir::AssocItemConstraintKind::Equality { ref term } => {
3178 AssocItemConstraintKind::Equality { term: clean_hir_term(term, cx) }
3179 }
3180 hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3181 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3182 },
3183 },
3184 }
3185}
3186
3187fn clean_bound_vars<'tcx>(
3188 bound_vars: &ty::List<ty::BoundVariableKind>,
3189 cx: &mut DocContext<'tcx>,
3190) -> Vec<GenericParamDef> {
3191 bound_vars
3192 .into_iter()
3193 .filter_map(|var| match var {
3194 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
3195 let name = cx.tcx.item_name(def_id);
3196 if name != kw::UnderscoreLifetime {
3197 Some(GenericParamDef::lifetime(def_id, name))
3198 } else {
3199 None
3200 }
3201 }
3202 ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
3203 let name = cx.tcx.item_name(def_id);
3204 Some(GenericParamDef {
3205 name,
3206 def_id,
3207 kind: GenericParamDefKind::Type {
3208 bounds: ThinVec::new(),
3209 default: None,
3210 synthetic: false,
3211 },
3212 })
3213 }
3214 ty::BoundVariableKind::Const => None,
3216 _ => None,
3217 })
3218 .collect()
3219}