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