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