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