mod.rs - source (original) (raw)
rustdoc/clean/
mod.rs
1//! This module defines the primary IR[^1] used in rustdoc together with the procedures that
2//! transform rustc data types into it.
3//!
4//! This IR — commonly referred to as the *cleaned AST* — is modeled after the [AST][ast].
5//!
6//! There are two kinds of transformation — *cleaning* — procedures:
7//!
8//! 1. Cleans [HIR][hir] types. Used for user-written code and inlined local re-exports
9//! both found in the local crate.
10//! 2. Cleans [`rustc_middle::ty`] types. Used for inlined cross-crate re-exports and anything
11//! output by the trait solver (e.g., when synthesizing blanket and auto-trait impls).
12//! They usually have `ty` or `middle` in their name.
13//!
14//! Their name is prefixed by `clean_`.
15//!
16//! Both the HIR and the `rustc_middle::ty` IR are quite removed from the source code.
17//! The cleaned AST on the other hand is closer to it which simplifies the rendering process.
18//! Furthermore, operating on a single IR instead of two avoids duplicating efforts down the line.
19//!
20//! This IR is consumed by both the HTML and the JSON backend.
21//!
22//! [^1]: Intermediate representation.
23
24mod 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:🪥:{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 // Hidden modules are stripped at a later stage.
85 // If a hidden module has the same name as a visible one, we want
86 // to keep both of them around.
87 inserted.remove(&(ItemType::Module, x.name));
88 }
89 Some(item)
90 }));
91
92 // Split up imports from all other items.
93 //
94 // This covers the case where somebody does an import which should pull in an item,
95 // but there's already an item with the same namespace and same name. Rust gives
96 // priority to the not-imported one, so we should, too.
97 items.extend(doc.items.values().flat_map(|(item, renamed, import_id)| {
98 // First, lower everything other than glob imports.
99 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 // Now we actually lower the imports, skipping everything else.
134 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 // skip everything else
138 Vec::new()
139 }
140 }));
141
142 // determine if we should display the inner contents or
143 // the outer `mod` item for the source code.
144
145 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 // mod foo { ... }
152 where_outer
153 } else {
154 // mod foo; (and a separate SourceFile for the contents)
155 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 // glob reexports are treated the same as `#[doc(inline)]` items.
191 //
192 // For glob re-exports the item may or may not exist to be re-exported (potentially the cfgs
193 // on the path up until the glob can be removed, and only cfgs on the globbed item itself
194 // matter), for non-inlined re-exports see #85043.
195 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 // We only keep the item's attributes.
205 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(ref t) => {
230 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
231 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()),
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 // FIXME: instead of storing the stringified expression, store `self` directly instead.
325 ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() }
326}
327
328pub(crate) fn clean_middle_region(region: ty::Region<'_>) -> Option<Lifetime> {
329 match region.kind() {
330 ty::ReStatic => Some(Lifetime::statik()),
331 _ if !region.has_name() => None,
332 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(_, name), .. }) => {
333 Some(Lifetime(name))
334 }
335 ty::ReEarlyParam(ref data) => Some(Lifetime(data.name)),
336 ty::ReBound(..)
337 | ty::ReLateParam(..)
338 | ty::ReVar(..)
339 | ty::ReError(_)
340 | ty::RePlaceholder(..)
341 | ty::ReErased => {
342 debug!("cannot clean region {region:?}");
343 None
344 }
345 }
346}
347
348fn clean_where_predicate<'tcx>(
349 predicate: &hir::WherePredicate<'tcx>,
350 cx: &mut DocContext<'tcx>,
351) -> Option<WherePredicate> {
352 if !predicate.kind.in_where_clause() {
353 return None;
354 }
355 Some(match *predicate.kind {
356 hir::WherePredicateKind::BoundPredicate(ref wbp) => {
357 let bound_params = wbp
358 .bound_generic_params
359 .iter()
360 .map(|param| clean_generic_param(cx, None, param))
361 .collect();
362 WherePredicate::BoundPredicate {
363 ty: clean_ty(wbp.bounded_ty, cx),
364 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
365 bound_params,
366 }
367 }
368
369 hir::WherePredicateKind::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
370 lifetime: clean_lifetime(wrp.lifetime, cx),
371 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
372 },
373
374 hir::WherePredicateKind::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
375 lhs: clean_ty(wrp.lhs_ty, cx),
376 rhs: clean_ty(wrp.rhs_ty, cx).into(),
377 },
378 })
379}
380
381pub(crate) fn clean_predicate<'tcx>(
382 predicate: ty::Clause<'tcx>,
383 cx: &mut DocContext<'tcx>,
384) -> Option<WherePredicate> {
385 let bound_predicate = predicate.kind();
386 match bound_predicate.skip_binder() {
387 ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_predicate.rebind(pred), cx),
388 ty::ClauseKind::RegionOutlives(pred) => Some(clean_region_outlives_predicate(pred)),
389 ty::ClauseKind::TypeOutlives(pred) => {
390 Some(clean_type_outlives_predicate(bound_predicate.rebind(pred), cx))
391 }
392 ty::ClauseKind::Projection(pred) => {
393 Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
394 }
395 // FIXME(generic_const_exprs): should this do something?
396 ty::ClauseKind::ConstEvaluatable(..)
397 | ty::ClauseKind::WellFormed(..)
398 | ty::ClauseKind::ConstArgHasType(..)
399 // FIXME(const_trait_impl): We can probably use this `HostEffect` pred to render `~const`.
400 | ty::ClauseKind::HostEffect(_) => None,
401 }
402}
403
404fn clean_poly_trait_predicate<'tcx>(
405 pred: ty::PolyTraitPredicate<'tcx>,
406 cx: &mut DocContext<'tcx>,
407) -> Option<WherePredicate> {
408 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
409 // FIXME(const_trait_impl) check constness
410 if Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait() {
411 return None;
412 }
413
414 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
415 Some(WherePredicate::BoundPredicate {
416 ty: clean_middle_ty(poly_trait_ref.self_ty(), cx, None, None),
417 bounds: vec![clean_poly_trait_ref_with_constraints(cx, poly_trait_ref, ThinVec::new())],
418 bound_params: Vec::new(),
419 })
420}
421
422fn clean_region_outlives_predicate(pred: ty::RegionOutlivesPredicate<'_>) -> WherePredicate {
423 let ty::OutlivesPredicate(a, b) = pred;
424
425 WherePredicate::RegionPredicate {
426 lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
427 bounds: vec![GenericBound::Outlives(
428 clean_middle_region(b).expect("failed to clean bounds"),
429 )],
430 }
431}
432
433fn clean_type_outlives_predicate<'tcx>(
434 pred: ty::Binder<'tcx, ty::TypeOutlivesPredicate<'tcx>>,
435 cx: &mut DocContext<'tcx>,
436) -> WherePredicate {
437 let ty::OutlivesPredicate(ty, lt) = pred.skip_binder();
438
439 WherePredicate::BoundPredicate {
440 ty: clean_middle_ty(pred.rebind(ty), cx, None, None),
441 bounds: vec![GenericBound::Outlives(
442 clean_middle_region(lt).expect("failed to clean lifetimes"),
443 )],
444 bound_params: Vec::new(),
445 }
446}
447
448fn clean_middle_term<'tcx>(
449 term: ty::Binder<'tcx, ty::Term<'tcx>>,
450 cx: &mut DocContext<'tcx>,
451) -> Term {
452 match term.skip_binder().unpack() {
453 ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(term.rebind(ty), cx, None, None)),
454 ty::TermKind::Const(c) => Term::Constant(clean_middle_const(term.rebind(c), cx)),
455 }
456}
457
458fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
459 match term {
460 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
461 hir::Term::Const(c) => {
462 let ct = lower_const_arg_for_rustdoc(cx.tcx, c, FeedConstTy::No);
463 Term::Constant(clean_middle_const(ty::Binder::dummy(ct), cx))
464 }
465 }
466}
467
468fn clean_projection_predicate<'tcx>(
469 pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
470 cx: &mut DocContext<'tcx>,
471) -> WherePredicate {
472 WherePredicate::EqPredicate {
473 lhs: clean_projection(
474 pred.map_bound(|p| {
475 // FIXME: This needs to be made resilient for `AliasTerm`s that
476 // are associated consts.
477 p.projection_term.expect_ty(cx.tcx)
478 }),
479 cx,
480 None,
481 ),
482 rhs: clean_middle_term(pred.map_bound(|p| p.term), cx),
483 }
484}
485
486fn clean_projection<'tcx>(
487 ty: ty::Binder<'tcx, ty::AliasTy<'tcx>>,
488 cx: &mut DocContext<'tcx>,
489 def_id: Option<DefId>,
490) -> Type {
491 if cx.tcx.is_impl_trait_in_trait(ty.skip_binder().def_id) {
492 return clean_middle_opaque_bounds(cx, ty.skip_binder().def_id, ty.skip_binder().args);
493 }
494
495 let trait_ = clean_trait_ref_with_constraints(
496 cx,
497 ty.map_bound(|ty| ty.trait_ref(cx.tcx)),
498 ThinVec::new(),
499 );
500 let self_type = clean_middle_ty(ty.map_bound(|ty| ty.self_ty()), cx, None, None);
501 let self_def_id = if let Some(def_id) = def_id {
502 cx.tcx.opt_parent(def_id).or(Some(def_id))
503 } else {
504 self_type.def_id(&cx.cache)
505 };
506 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
507 Type::QPath(Box::new(QPathData {
508 assoc: projection_to_path_segment(ty, cx),
509 should_show_cast,
510 self_type,
511 trait_: Some(trait_),
512 }))
513}
514
515fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
516 !trait_.segments.is_empty()
517 && self_def_id
518 .zip(Some(trait_.def_id()))
519 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
520}
521
522fn projection_to_path_segment<'tcx>(
523 ty: ty::Binder<'tcx, ty::AliasTy<'tcx>>,
524 cx: &mut DocContext<'tcx>,
525) -> PathSegment {
526 let def_id = ty.skip_binder().def_id;
527 let item = cx.tcx.associated_item(def_id);
528 let generics = cx.tcx.generics_of(def_id);
529 PathSegment {
530 name: item.name(),
531 args: GenericArgs::AngleBracketed {
532 args: clean_middle_generic_args(
533 cx,
534 ty.map_bound(|ty| &ty.args[generics.parent_count..]),
535 false,
536 def_id,
537 ),
538 constraints: Default::default(),
539 },
540 }
541}
542
543fn clean_generic_param_def(
544 def: &ty::GenericParamDef,
545 defaults: ParamDefaults,
546 cx: &mut DocContext<'_>,
547) -> GenericParamDef {
548 let (name, kind) = match def.kind {
549 ty::GenericParamDefKind::Lifetime => {
550 (def.name, GenericParamDefKind::Lifetime { outlives: ThinVec::new() })
551 }
552 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
553 let default = if let ParamDefaults::Yes = defaults
554 && has_default
555 {
556 Some(clean_middle_ty(
557 ty::Binder::dummy(cx.tcx.type_of(def.def_id).instantiate_identity()),
558 cx,
559 Some(def.def_id),
560 None,
561 ))
562 } else {
563 None
564 };
565 (
566 def.name,
567 GenericParamDefKind::Type {
568 bounds: ThinVec::new(), // These are filled in from the where-clauses.
569 default: default.map(Box::new),
570 synthetic,
571 },
572 )
573 }
574 ty::GenericParamDefKind::Const { has_default, synthetic } => (
575 def.name,
576 GenericParamDefKind::Const {
577 ty: Box::new(clean_middle_ty(
578 ty::Binder::dummy(
579 cx.tcx
580 .type_of(def.def_id)
581 .no_bound_vars()
582 .expect("const parameter types cannot be generic"),
583 ),
584 cx,
585 Some(def.def_id),
586 None,
587 )),
588 default: if let ParamDefaults::Yes = defaults
589 && has_default
590 {
591 Some(Box::new(
592 cx.tcx.const_param_default(def.def_id).instantiate_identity().to_string(),
593 ))
594 } else {
595 None
596 },
597 synthetic,
598 },
599 ),
600 };
601
602 GenericParamDef { name, def_id: def.def_id, kind }
603}
604
605/// Whether to clean generic parameter defaults or not.
606enum ParamDefaults {
607 Yes,
608 No,
609}
610
611fn clean_generic_param<'tcx>(
612 cx: &mut DocContext<'tcx>,
613 generics: Option<&hir::Generics<'tcx>>,
614 param: &hir::GenericParam<'tcx>,
615) -> GenericParamDef {
616 let (name, kind) = match param.kind {
617 hir::GenericParamKind::Lifetime { .. } => {
618 let outlives = if let Some(generics) = generics {
619 generics
620 .outlives_for_param(param.def_id)
621 .filter(|bp| !bp.in_where_clause)
622 .flat_map(|bp| bp.bounds)
623 .map(|bound| match bound {
624 hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
625 _ => panic!(),
626 })
627 .collect()
628 } else {
629 ThinVec::new()
630 };
631 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
632 }
633 hir::GenericParamKind::Type { ref default, synthetic } => {
634 let bounds = if let Some(generics) = generics {
635 generics
636 .bounds_for_param(param.def_id)
637 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
638 .flat_map(|bp| bp.bounds)
639 .filter_map(|x| clean_generic_bound(x, cx))
640 .collect()
641 } else {
642 ThinVec::new()
643 };
644 (
645 param.name.ident().name,
646 GenericParamDefKind::Type {
647 bounds,
648 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
649 synthetic,
650 },
651 )
652 }
653 hir::GenericParamKind::Const { ty, default, synthetic } => (
654 param.name.ident().name,
655 GenericParamDefKind::Const {
656 ty: Box::new(clean_ty(ty, cx)),
657 default: default.map(|ct| {
658 Box::new(lower_const_arg_for_rustdoc(cx.tcx, ct, FeedConstTy::No).to_string())
659 }),
660 synthetic,
661 },
662 ),
663 };
664
665 GenericParamDef { name, def_id: param.def_id.to_def_id(), kind }
666}
667
668/// Synthetic type-parameters are inserted after normal ones.
669/// In order for normal parameters to be able to refer to synthetic ones,
670/// scans them first.
671fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
672 match param.kind {
673 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
674 _ => false,
675 }
676}
677
678/// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
679///
680/// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
681fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
682 matches!(
683 param.kind,
684 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) }
685 )
686}
687
688pub(crate) fn clean_generics<'tcx>(
689 gens: &hir::Generics<'tcx>,
690 cx: &mut DocContext<'tcx>,
691) -> Generics {
692 let impl_trait_params = gens
693 .params
694 .iter()
695 .filter(|param| is_impl_trait(param))
696 .map(|param| {
697 let param = clean_generic_param(cx, Some(gens), param);
698 match param.kind {
699 GenericParamDefKind::Lifetime { .. } => unreachable!(),
700 GenericParamDefKind::Type { ref bounds, .. } => {
701 cx.impl_trait_bounds.insert(param.def_id.into(), bounds.to_vec());
702 }
703 GenericParamDefKind::Const { .. } => unreachable!(),
704 }
705 param
706 })
707 .collect::<Vec<_>>();
708
709 let mut bound_predicates = FxIndexMap::default();
710 let mut region_predicates = FxIndexMap::default();
711 let mut eq_predicates = ThinVec::default();
712 for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
713 match pred {
714 WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
715 match bound_predicates.entry(ty) {
716 IndexEntry::Vacant(v) => {
717 v.insert((bounds, bound_params));
718 }
719 IndexEntry::Occupied(mut o) => {
720 // we merge both bounds.
721 for bound in bounds {
722 if !o.get().0.contains(&bound) {
723 o.get_mut().0.push(bound);
724 }
725 }
726 for bound_param in bound_params {
727 if !o.get().1.contains(&bound_param) {
728 o.get_mut().1.push(bound_param);
729 }
730 }
731 }
732 }
733 }
734 WherePredicate::RegionPredicate { lifetime, bounds } => {
735 match region_predicates.entry(lifetime) {
736 IndexEntry::Vacant(v) => {
737 v.insert(bounds);
738 }
739 IndexEntry::Occupied(mut o) => {
740 // we merge both bounds.
741 for bound in bounds {
742 if !o.get().contains(&bound) {
743 o.get_mut().push(bound);
744 }
745 }
746 }
747 }
748 }
749 WherePredicate::EqPredicate { lhs, rhs } => {
750 eq_predicates.push(WherePredicate::EqPredicate { lhs, rhs });
751 }
752 }
753 }
754
755 let mut params = ThinVec::with_capacity(gens.params.len());
756 // In this loop, we gather the generic parameters (`<'a, B: 'a>`) and check if they have
757 // bounds in the where predicates. If so, we move their bounds into the where predicates
758 // while also preventing duplicates.
759 for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
760 let mut p = clean_generic_param(cx, Some(gens), p);
761 match &mut p.kind {
762 GenericParamDefKind::Lifetime { outlives } => {
763 if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
764 // We merge bounds in the `where` clause.
765 for outlive in outlives.drain(..) {
766 let outlive = GenericBound::Outlives(outlive);
767 if !region_pred.contains(&outlive) {
768 region_pred.push(outlive);
769 }
770 }
771 }
772 }
773 GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
774 if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
775 // We merge bounds in the `where` clause.
776 for bound in bounds.drain(..) {
777 if !bound_pred.0.contains(&bound) {
778 bound_pred.0.push(bound);
779 }
780 }
781 }
782 }
783 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
784 // nothing to do here.
785 }
786 }
787 params.push(p);
788 }
789 params.extend(impl_trait_params);
790
791 Generics {
792 params,
793 where_predicates: bound_predicates
794 .into_iter()
795 .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
796 ty,
797 bounds,
798 bound_params,
799 })
800 .chain(
801 region_predicates
802 .into_iter()
803 .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
804 )
805 .chain(eq_predicates)
806 .collect(),
807 }
808}
809
810fn clean_ty_generics<'tcx>(
811 cx: &mut DocContext<'tcx>,
812 gens: &ty::Generics,
813 preds: ty::GenericPredicates<'tcx>,
814) -> Generics {
815 // Don't populate `cx.impl_trait_bounds` before cleaning where clauses,
816 // since `clean_predicate` would consume them.
817 let mut impl_trait = BTreeMap::<u32, Vec<GenericBound>>::default();
818
819 let params: ThinVec<_> = gens
820 .own_params
821 .iter()
822 .filter(|param| match param.kind {
823 ty::GenericParamDefKind::Lifetime => !param.is_anonymous_lifetime(),
824 ty::GenericParamDefKind::Type { synthetic, .. } => {
825 if param.name == kw::SelfUpper {
826 debug_assert_eq!(param.index, 0);
827 return false;
828 }
829 if synthetic {
830 impl_trait.insert(param.index, vec![]);
831 return false;
832 }
833 true
834 }
835 ty::GenericParamDefKind::Const { .. } => true,
836 })
837 .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx))
838 .collect();
839
840 // param index -> [(trait DefId, associated type name & generics, term)]
841 let mut impl_trait_proj =
842 FxHashMap::<u32, Vec<(DefId, PathSegment, ty::Binder<'_, ty::Term<'_>>)>>::default();
843
844 let where_predicates = preds
845 .predicates
846 .iter()
847 .flat_map(|(pred, _)| {
848 let mut projection = None;
849 let param_idx = {
850 let bound_p = pred.kind();
851 match bound_p.skip_binder() {
852 ty::ClauseKind::Trait(pred) if let ty::Param(param) = pred.self_ty().kind() => {
853 Some(param.index)
854 }
855 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg))
856 if let ty::Param(param) = ty.kind() =>
857 {
858 Some(param.index)
859 }
860 ty::ClauseKind::Projection(p)
861 if let ty::Param(param) = p.projection_term.self_ty().kind() =>
862 {
863 projection = Some(bound_p.rebind(p));
864 Some(param.index)
865 }
866 _ => None,
867 }
868 };
869
870 if let Some(param_idx) = param_idx
871 && let Some(bounds) = impl_trait.get_mut(¶m_idx)
872 {
873 let pred = clean_predicate(*pred, cx)?;
874
875 bounds.extend(pred.get_bounds().into_iter().flatten().cloned());
876
877 if let Some(proj) = projection
878 && let lhs = clean_projection(
879 proj.map_bound(|p| {
880 // FIXME: This needs to be made resilient for `AliasTerm`s that
881 // are associated consts.
882 p.projection_term.expect_ty(cx.tcx)
883 }),
884 cx,
885 None,
886 )
887 && let Some((_, trait_did, name)) = lhs.projection()
888 {
889 impl_trait_proj.entry(param_idx).or_default().push((
890 trait_did,
891 name,
892 proj.map_bound(|p| p.term),
893 ));
894 }
895
896 return None;
897 }
898
899 Some(pred)
900 })
901 .collect::<Vec<_>>();
902
903 for (idx, mut bounds) in impl_trait {
904 let mut has_sized = false;
905 bounds.retain(|b| {
906 if b.is_sized_bound(cx) {
907 has_sized = true;
908 false
909 } else {
910 true
911 }
912 });
913 if !has_sized {
914 bounds.push(GenericBound::maybe_sized(cx));
915 }
916
917 // Move trait bounds to the front.
918 bounds.sort_by_key(|b| !b.is_trait_bound());
919
920 // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`).
921 // Since all potential trait bounds are at the front we can just check the first bound.
922 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
923 bounds.insert(0, GenericBound::sized(cx));
924 }
925
926 if let Some(proj) = impl_trait_proj.remove(&idx) {
927 for (trait_did, name, rhs) in proj {
928 let rhs = clean_middle_term(rhs, cx);
929 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
930 }
931 }
932
933 cx.impl_trait_bounds.insert(idx.into(), bounds);
934 }
935
936 // Now that `cx.impl_trait_bounds` is populated, we can process
937 // remaining predicates which could contain `impl Trait`.
938 let where_predicates =
939 where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect();
940
941 let mut generics = Generics { params, where_predicates };
942 simplify::sized_bounds(cx, &mut generics);
943 generics.where_predicates = simplify::where_clauses(cx, generics.where_predicates);
944 generics
945}
946
947fn clean_ty_alias_inner_type<'tcx>(
948 ty: Ty<'tcx>,
949 cx: &mut DocContext<'tcx>,
950 ret: &mut Vec<Item>,
951) -> Option<TypeAliasInnerType> {
952 let ty::Adt(adt_def, args) = ty.kind() else {
953 return None;
954 };
955
956 if !adt_def.did().is_local() {
957 cx.with_param_env(adt_def.did(), |cx| {
958 inline::build_impls(cx, adt_def.did(), None, ret);
959 });
960 }
961
962 Some(if adt_def.is_enum() {
963 let variants: rustc_index::IndexVec<_, _> = adt_def
964 .variants()
965 .iter()
966 .map(|variant| clean_variant_def_with_args(variant, args, cx))
967 .collect();
968
969 if !adt_def.did().is_local() {
970 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Enum);
971 }
972
973 TypeAliasInnerType::Enum {
974 variants,
975 is_non_exhaustive: adt_def.is_variant_list_non_exhaustive(),
976 }
977 } else {
978 let variant = adt_def
979 .variants()
980 .iter()
981 .next()
982 .unwrap_or_else(|| bug!("a struct or union should always have one variant def"));
983
984 let fields: Vec<_> =
985 clean_variant_def_with_args(variant, args, cx).kind.inner_items().cloned().collect();
986
987 if adt_def.is_struct() {
988 if !adt_def.did().is_local() {
989 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Struct);
990 }
991 TypeAliasInnerType::Struct { ctor_kind: variant.ctor_kind(), fields }
992 } else {
993 if !adt_def.did().is_local() {
994 inline::record_extern_fqn(cx, adt_def.did(), ItemType::Union);
995 }
996 TypeAliasInnerType::Union { fields }
997 }
998 })
999}
1000
1001fn clean_proc_macro<'tcx>(
1002 item: &hir::Item<'tcx>,
1003 name: &mut Symbol,
1004 kind: MacroKind,
1005 cx: &mut DocContext<'tcx>,
1006) -> ItemKind {
1007 let attrs = cx.tcx.hir_attrs(item.hir_id());
1008 if kind == MacroKind::Derive
1009 && let Some(derive_name) =
1010 hir_attr_lists(attrs, sym::proc_macro_derive).find_map(|mi| mi.ident())
1011 {
1012 *name = derive_name.name;
1013 }
1014
1015 let mut helpers = Vec::new();
1016 for mi in hir_attr_lists(attrs, sym::proc_macro_derive) {
1017 if !mi.has_name(sym::attributes) {
1018 continue;
1019 }
1020
1021 if let Some(list) = mi.meta_item_list() {
1022 for inner_mi in list {
1023 if let Some(ident) = inner_mi.ident() {
1024 helpers.push(ident.name);
1025 }
1026 }
1027 }
1028 }
1029 ProcMacroItem(ProcMacro { kind, helpers })
1030}
1031
1032fn clean_fn_or_proc_macro<'tcx>(
1033 item: &hir::Item<'tcx>,
1034 sig: &hir::FnSig<'tcx>,
1035 generics: &hir::Generics<'tcx>,
1036 body_id: hir::BodyId,
1037 name: &mut Symbol,
1038 cx: &mut DocContext<'tcx>,
1039) -> ItemKind {
1040 let attrs = cx.tcx.hir_attrs(item.hir_id());
1041 let macro_kind = attrs.iter().find_map(|a| {
1042 if a.has_name(sym::proc_macro) {
1043 Some(MacroKind::Bang)
1044 } else if a.has_name(sym::proc_macro_derive) {
1045 Some(MacroKind::Derive)
1046 } else if a.has_name(sym::proc_macro_attribute) {
1047 Some(MacroKind::Attr)
1048 } else {
1049 None
1050 }
1051 });
1052 match macro_kind {
1053 Some(kind) => clean_proc_macro(item, name, kind, cx),
1054 None => {
1055 let mut func = clean_function(cx, sig, generics, ParamsSrc::Body(body_id));
1056 clean_fn_decl_legacy_const_generics(&mut func, attrs);
1057 FunctionItem(func)
1058 }
1059 }
1060}
1061
1062/// This is needed to make it more "readable" when documenting functions using
1063/// `rustc_legacy_const_generics`. More information in
1064/// <https://github.com/rust-lang/rust/issues/83167>.
1065fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) {
1066 for meta_item_list in attrs
1067 .iter()
1068 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
1069 .filter_map(|a| a.meta_item_list())
1070 {
1071 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.lit()).enumerate() {
1072 match literal.kind {
1073 ast::LitKind::Int(a, _) => {
1074 let GenericParamDef { name, kind, .. } = func.generics.params.remove(0);
1075 if let GenericParamDefKind::Const { ty, .. } = kind {
1076 func.decl.inputs.insert(
1077 a.get() as _,
1078 Parameter { name: Some(name), type_: *ty, is_const: true },
1079 );
1080 } else {
1081 panic!("unexpected non const in position {pos}");
1082 }
1083 }
1084 _ => panic!("invalid arg index"),
1085 }
1086 }
1087 }
1088}
1089
1090enum ParamsSrc<'tcx> {
1091 Body(hir::BodyId),
1092 Idents(&'tcx [Option<Ident>]),
1093}
1094
1095fn clean_function<'tcx>(
1096 cx: &mut DocContext<'tcx>,
1097 sig: &hir::FnSig<'tcx>,
1098 generics: &hir::Generics<'tcx>,
1099 params: ParamsSrc<'tcx>,
1100) -> Box<Function> {
1101 let (generics, decl) = enter_impl_trait(cx, |cx| {
1102 // NOTE: Generics must be cleaned before params.
1103 let generics = clean_generics(generics, cx);
1104 let params = match params {
1105 ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl.inputs, body_id),
1106 // Let's not perpetuate anon params from Rust 2015; use `_` for them.
1107 ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents, |ident| {
1108 Some(ident.map_or(kw::Underscore, |ident| ident.name))
1109 }),
1110 };
1111 let decl = clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params);
1112 (generics, decl)
1113 });
1114 Box::new(Function { decl, generics })
1115}
1116
1117fn clean_params<'tcx>(
1118 cx: &mut DocContext<'tcx>,
1119 types: &[hir::Ty<'tcx>],
1120 idents: &[Option<Ident>],
1121 postprocess: impl Fn(Option<Ident>) -> Option<Symbol>,
1122) -> Vec<Parameter> {
1123 types
1124 .iter()
1125 .enumerate()
1126 .map(|(i, ty)| Parameter {
1127 name: postprocess(idents[i]),
1128 type_: clean_ty(ty, cx),
1129 is_const: false,
1130 })
1131 .collect()
1132}
1133
1134fn clean_params_via_body<'tcx>(
1135 cx: &mut DocContext<'tcx>,
1136 types: &[hir::Ty<'tcx>],
1137 body_id: hir::BodyId,
1138) -> Vec<Parameter> {
1139 types
1140 .iter()
1141 .zip(cx.tcx.hir_body(body_id).params)
1142 .map(|(ty, param)| Parameter {
1143 name: Some(name_from_pat(param.pat)),
1144 type_: clean_ty(ty, cx),
1145 is_const: false,
1146 })
1147 .collect()
1148}
1149
1150fn clean_fn_decl_with_params<'tcx>(
1151 cx: &mut DocContext<'tcx>,
1152 decl: &hir::FnDecl<'tcx>,
1153 header: Option<&hir::FnHeader>,
1154 params: Vec<Parameter>,
1155) -> FnDecl {
1156 let mut output = match decl.output {
1157 hir::FnRetTy::Return(typ) => clean_ty(typ, cx),
1158 hir::FnRetTy::DefaultReturn(..) => Type::Tuple(Vec::new()),
1159 };
1160 if let Some(header) = header
1161 && header.is_async()
1162 {
1163 output = output.sugared_async_return_type();
1164 }
1165 FnDecl { inputs: params, output, c_variadic: decl.c_variadic }
1166}
1167
1168fn clean_poly_fn_sig<'tcx>(
1169 cx: &mut DocContext<'tcx>,
1170 did: Option<DefId>,
1171 sig: ty::PolyFnSig<'tcx>,
1172) -> FnDecl {
1173 let mut output = clean_middle_ty(sig.output(), cx, None, None);
1174
1175 // If the return type isn't an `impl Trait`, we can safely assume that this
1176 // function isn't async without needing to execute the query `asyncness` at
1177 // all which gives us a noticeable performance boost.
1178 if let Some(did) = did
1179 && let Type::ImplTrait(_) = output
1180 && cx.tcx.asyncness(did).is_async()
1181 {
1182 output = output.sugared_async_return_type();
1183 }
1184
1185 let mut idents = did.map(|did| cx.tcx.fn_arg_idents(did)).unwrap_or_default().iter().copied();
1186
1187 // If this comes from a fn item, let's not perpetuate anon params from Rust 2015; use `_` for them.
1188 // If this comes from a fn ptr ty, we just keep params unnamed since it's more conventional stylistically.
1189 // Since the param name is not part of the semantic type, these params never bear a name unlike
1190 // in the HIR case, thus we can't peform any fancy fallback logic unlike `clean_bare_fn_ty`.
1191 let fallback = did.map(|_| kw::Underscore);
1192
1193 let params = sig
1194 .inputs()
1195 .iter()
1196 .map(|ty| Parameter {
1197 name: idents.next().flatten().map(|ident| ident.name).or(fallback),
1198 type_: clean_middle_ty(ty.map_bound(|ty| *ty), cx, None, None),
1199 is_const: false,
1200 })
1201 .collect();
1202
1203 FnDecl { inputs: params, output, c_variadic: sig.skip_binder().c_variadic }
1204}
1205
1206fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1207 let path = clean_path(trait_ref.path, cx);
1208 register_res(cx, path.res);
1209 path
1210}
1211
1212fn clean_poly_trait_ref<'tcx>(
1213 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1214 cx: &mut DocContext<'tcx>,
1215) -> PolyTrait {
1216 PolyTrait {
1217 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1218 generic_params: poly_trait_ref
1219 .bound_generic_params
1220 .iter()
1221 .filter(|p| !is_elided_lifetime(p))
1222 .map(|x| clean_generic_param(cx, None, x))
1223 .collect(),
1224 }
1225}
1226
1227fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1228 let local_did = trait_item.owner_id.to_def_id();
1229 cx.with_param_env(local_did, |cx| {
1230 let inner = match trait_item.kind {
1231 hir::TraitItemKind::Const(ty, Some(default)) => {
1232 ProvidedAssocConstItem(Box::new(Constant {
1233 generics: enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)),
1234 kind: ConstantKind::Local { def_id: local_did, body: default },
1235 type_: clean_ty(ty, cx),
1236 }))
1237 }
1238 hir::TraitItemKind::Const(ty, None) => {
1239 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1240 RequiredAssocConstItem(generics, Box::new(clean_ty(ty, cx)))
1241 }
1242 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1243 let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Body(body));
1244 MethodItem(m, None)
1245 }
1246 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(idents)) => {
1247 let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Idents(idents));
1248 RequiredMethodItem(m)
1249 }
1250 hir::TraitItemKind::Type(bounds, Some(default)) => {
1251 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1252 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1253 let item_type =
1254 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, default)), cx, None, None);
1255 AssocTypeItem(
1256 Box::new(TypeAlias {
1257 type_: clean_ty(default, cx),
1258 generics,
1259 inner_type: None,
1260 item_type: Some(item_type),
1261 }),
1262 bounds,
1263 )
1264 }
1265 hir::TraitItemKind::Type(bounds, None) => {
1266 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1267 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1268 RequiredAssocTypeItem(generics, bounds)
1269 }
1270 };
1271 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx)
1272 })
1273}
1274
1275pub(crate) fn clean_impl_item<'tcx>(
1276 impl_: &hir::ImplItem<'tcx>,
1277 cx: &mut DocContext<'tcx>,
1278) -> Item {
1279 let local_did = impl_.owner_id.to_def_id();
1280 cx.with_param_env(local_did, |cx| {
1281 let inner = match impl_.kind {
1282 hir::ImplItemKind::Const(ty, expr) => ImplAssocConstItem(Box::new(Constant {
1283 generics: clean_generics(impl_.generics, cx),
1284 kind: ConstantKind::Local { def_id: local_did, body: expr },
1285 type_: clean_ty(ty, cx),
1286 })),
1287 hir::ImplItemKind::Fn(ref sig, body) => {
1288 let m = clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body));
1289 let defaultness = cx.tcx.defaultness(impl_.owner_id);
1290 MethodItem(m, Some(defaultness))
1291 }
1292 hir::ImplItemKind::Type(hir_ty) => {
1293 let type_ = clean_ty(hir_ty, cx);
1294 let generics = clean_generics(impl_.generics, cx);
1295 let item_type =
1296 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1297 AssocTypeItem(
1298 Box::new(TypeAlias {
1299 type_,
1300 generics,
1301 inner_type: None,
1302 item_type: Some(item_type),
1303 }),
1304 Vec::new(),
1305 )
1306 }
1307 };
1308
1309 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1310 })
1311}
1312
1313pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1314 let tcx = cx.tcx;
1315 let kind = match assoc_item.kind {
1316 ty::AssocKind::Const { .. } => {
1317 let ty = clean_middle_ty(
1318 ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()),
1319 cx,
1320 Some(assoc_item.def_id),
1321 None,
1322 );
1323
1324 let mut generics = clean_ty_generics(
1325 cx,
1326 tcx.generics_of(assoc_item.def_id),
1327 tcx.explicit_predicates_of(assoc_item.def_id),
1328 );
1329 simplify::move_bounds_to_generic_parameters(&mut generics);
1330
1331 match assoc_item.container {
1332 ty::AssocItemContainer::Impl => ImplAssocConstItem(Box::new(Constant {
1333 generics,
1334 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1335 type_: ty,
1336 })),
1337 ty::AssocItemContainer::Trait => {
1338 if tcx.defaultness(assoc_item.def_id).has_value() {
1339 ProvidedAssocConstItem(Box::new(Constant {
1340 generics,
1341 kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1342 type_: ty,
1343 }))
1344 } else {
1345 RequiredAssocConstItem(generics, Box::new(ty))
1346 }
1347 }
1348 }
1349 }
1350 ty::AssocKind::Fn { has_self, .. } => {
1351 let mut item = inline::build_function(cx, assoc_item.def_id);
1352
1353 if has_self {
1354 let self_ty = match assoc_item.container {
1355 ty::AssocItemContainer::Impl => {
1356 tcx.type_of(assoc_item.container_id(tcx)).instantiate_identity()
1357 }
1358 ty::AssocItemContainer::Trait => tcx.types.self_param,
1359 };
1360 let self_param_ty =
1361 tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder();
1362 if self_param_ty == self_ty {
1363 item.decl.inputs[0].type_ = SelfTy;
1364 } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1365 && ty == self_ty
1366 {
1367 match item.decl.inputs[0].type_ {
1368 BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1369 _ => unreachable!(),
1370 }
1371 }
1372 }
1373
1374 let provided = match assoc_item.container {
1375 ty::AssocItemContainer::Impl => true,
1376 ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1377 };
1378 if provided {
1379 let defaultness = match assoc_item.container {
1380 ty::AssocItemContainer::Impl => Some(assoc_item.defaultness(tcx)),
1381 ty::AssocItemContainer::Trait => None,
1382 };
1383 MethodItem(item, defaultness)
1384 } else {
1385 RequiredMethodItem(item)
1386 }
1387 }
1388 ty::AssocKind::Type { .. } => {
1389 let my_name = assoc_item.name();
1390
1391 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1392 match (¶m.kind, arg) {
1393 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1394 if *ty == param.name =>
1395 {
1396 true
1397 }
1398 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1399 if *lt == param.name =>
1400 {
1401 true
1402 }
1403 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1404 ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1405 _ => false,
1406 },
1407 _ => false,
1408 }
1409 }
1410
1411 let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1412 if let ty::AssocItemContainer::Trait = assoc_item.container {
1413 let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied();
1414 predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied()));
1415 }
1416 let mut generics = clean_ty_generics(
1417 cx,
1418 tcx.generics_of(assoc_item.def_id),
1419 ty::GenericPredicates { parent: None, predicates },
1420 );
1421 simplify::move_bounds_to_generic_parameters(&mut generics);
1422
1423 if let ty::AssocItemContainer::Trait = assoc_item.container {
1424 // Move bounds that are (likely) directly attached to the associated type
1425 // from the where-clause to the associated type.
1426 // There is no guarantee that this is what the user actually wrote but we have
1427 // no way of knowing.
1428 let mut bounds: Vec<GenericBound> = Vec::new();
1429 generics.where_predicates.retain_mut(|pred| match *pred {
1430 WherePredicate::BoundPredicate {
1431 ty:
1432 QPath(box QPathData {
1433 ref assoc,
1434 ref self_type,
1435 trait_: Some(ref trait_),
1436 ..
1437 }),
1438 bounds: ref mut pred_bounds,
1439 ..
1440 } => {
1441 if assoc.name != my_name {
1442 return true;
1443 }
1444 if trait_.def_id() != assoc_item.container_id(tcx) {
1445 return true;
1446 }
1447 if *self_type != SelfTy {
1448 return true;
1449 }
1450 match &assoc.args {
1451 GenericArgs::AngleBracketed { args, constraints } => {
1452 if !constraints.is_empty()
1453 || generics
1454 .params
1455 .iter()
1456 .zip(args.iter())
1457 .any(|(param, arg)| !param_eq_arg(param, arg))
1458 {
1459 return true;
1460 }
1461 }
1462 GenericArgs::Parenthesized { .. } => {
1463 // The only time this happens is if we're inside the rustdoc for Fn(),
1464 // which only has one associated type, which is not a GAT, so whatever.
1465 }
1466 GenericArgs::ReturnTypeNotation => {
1467 // Never move these.
1468 }
1469 }
1470 bounds.extend(mem::take(pred_bounds));
1471 false
1472 }
1473 _ => true,
1474 });
1475 // Our Sized/?Sized bound didn't get handled when creating the generics
1476 // because we didn't actually get our whole set of bounds until just now
1477 // (some of them may have come from the trait). If we do have a sized
1478 // bound, we remove it, and if we don't then we add the `?Sized` bound
1479 // at the end.
1480 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1481 Some(i) => {
1482 bounds.remove(i);
1483 }
1484 None => bounds.push(GenericBound::maybe_sized(cx)),
1485 }
1486
1487 if tcx.defaultness(assoc_item.def_id).has_value() {
1488 AssocTypeItem(
1489 Box::new(TypeAlias {
1490 type_: clean_middle_ty(
1491 ty::Binder::dummy(
1492 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1493 ),
1494 cx,
1495 Some(assoc_item.def_id),
1496 None,
1497 ),
1498 generics,
1499 inner_type: None,
1500 item_type: None,
1501 }),
1502 bounds,
1503 )
1504 } else {
1505 RequiredAssocTypeItem(generics, bounds)
1506 }
1507 } else {
1508 AssocTypeItem(
1509 Box::new(TypeAlias {
1510 type_: clean_middle_ty(
1511 ty::Binder::dummy(
1512 tcx.type_of(assoc_item.def_id).instantiate_identity(),
1513 ),
1514 cx,
1515 Some(assoc_item.def_id),
1516 None,
1517 ),
1518 generics,
1519 inner_type: None,
1520 item_type: None,
1521 }),
1522 // Associated types inside trait or inherent impls are not allowed to have
1523 // item bounds. Thus we don't attempt to move any bounds there.
1524 Vec::new(),
1525 )
1526 }
1527 }
1528 };
1529
1530 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, cx)
1531}
1532
1533fn first_non_private_clean_path<'tcx>(
1534 cx: &mut DocContext<'tcx>,
1535 path: &hir::Path<'tcx>,
1536 new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1537 new_path_span: rustc_span::Span,
1538) -> Path {
1539 let new_hir_path =
1540 hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1541 let mut new_clean_path = clean_path(&new_hir_path, cx);
1542 // In here we need to play with the path data one last time to provide it the
1543 // missing `args` and `res` of the final `Path` we get, which, since it comes
1544 // from a re-export, doesn't have the generics that were originally there, so
1545 // we add them by hand.
1546 if let Some(path_last) = path.segments.last().as_ref()
1547 && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1548 && let Some(path_last_args) = path_last.args.as_ref()
1549 && path_last.args.is_some()
1550 {
1551 assert!(new_path_last.args.is_empty());
1552 new_path_last.args = clean_generic_args(path_last_args, cx);
1553 }
1554 new_clean_path
1555}
1556
1557/// The goal of this function is to return the first `Path` which is not private (ie not private
1558/// or `doc(hidden)`). If it's not possible, it'll return the "end type".
1559///
1560/// If the path is not a re-export or is public, it'll return `None`.
1561fn first_non_private<'tcx>(
1562 cx: &mut DocContext<'tcx>,
1563 hir_id: hir::HirId,
1564 path: &hir::Path<'tcx>,
1565) -> Option<Path> {
1566 let target_def_id = path.res.opt_def_id()?;
1567 let (parent_def_id, ident) = match &path.segments {
1568 [] => return None,
1569 // Relative paths are available in the same scope as the owner.
1570 [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1571 // So are self paths.
1572 [parent, leaf] if parent.ident.name == kw::SelfLower => {
1573 (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1574 }
1575 // Crate paths are not. We start from the crate root.
1576 [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1577 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1578 }
1579 [parent, leaf] if parent.ident.name == kw::Super => {
1580 let parent_mod = cx.tcx.parent_module(hir_id);
1581 if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1582 (super_parent, leaf.ident)
1583 } else {
1584 // If we can't find the parent of the parent, then the parent is already the crate.
1585 (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1586 }
1587 }
1588 // Absolute paths are not. We start from the parent of the item.
1589 [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1590 };
1591 // First we try to get the `DefId` of the item.
1592 for child in
1593 cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1594 {
1595 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1596 continue;
1597 }
1598
1599 if let Some(def_id) = child.res.opt_def_id()
1600 && target_def_id == def_id
1601 {
1602 let mut last_path_res = None;
1603 'reexps: for reexp in child.reexport_chain.iter() {
1604 if let Some(use_def_id) = reexp.id()
1605 && let Some(local_use_def_id) = use_def_id.as_local()
1606 && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1607 && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1608 {
1609 for res in &path.res {
1610 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1611 continue;
1612 }
1613 if (cx.render_options.document_hidden ||
1614 !cx.tcx.is_doc_hidden(use_def_id)) &&
1615 // We never check for "cx.render_options.document_private"
1616 // because if a re-export is not fully public, it's never
1617 // documented.
1618 cx.tcx.local_visibility(local_use_def_id).is_public()
1619 {
1620 break 'reexps;
1621 }
1622 last_path_res = Some((path, res));
1623 continue 'reexps;
1624 }
1625 }
1626 }
1627 if !child.reexport_chain.is_empty() {
1628 // So in here, we use the data we gathered from iterating the reexports. If
1629 // `last_path_res` is set, it can mean two things:
1630 //
1631 // 1. We found a public reexport.
1632 // 2. We didn't find a public reexport so it's the "end type" path.
1633 if let Some((new_path, _)) = last_path_res {
1634 return Some(first_non_private_clean_path(
1635 cx,
1636 path,
1637 new_path.segments,
1638 new_path.span,
1639 ));
1640 }
1641 // If `last_path_res` is `None`, it can mean two things:
1642 //
1643 // 1. The re-export is public, no need to change anything, just use the path as is.
1644 // 2. Nothing was found, so let's just return the original path.
1645 return None;
1646 }
1647 }
1648 }
1649 None
1650}
1651
1652fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1653 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1654 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1655
1656 match qpath {
1657 hir::QPath::Resolved(None, path) => {
1658 if let Res::Def(DefKind::TyParam, did) = path.res {
1659 if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1660 return new_ty;
1661 }
1662 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1663 return ImplTrait(bounds);
1664 }
1665 }
1666
1667 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1668 expanded
1669 } else {
1670 // First we check if it's a private re-export.
1671 let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1672 path
1673 } else {
1674 clean_path(path, cx)
1675 };
1676 resolve_type(cx, path)
1677 }
1678 }
1679 hir::QPath::Resolved(Some(qself), p) => {
1680 // Try to normalize `<X as Y>::T` to a type
1681 let ty = lower_ty(cx.tcx, hir_ty);
1682 // `hir_to_ty` can return projection types with escaping vars for GATs, e.g. `<() as Trait>::Gat<'_>`
1683 if !ty.has_escaping_bound_vars()
1684 && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1685 {
1686 return clean_middle_ty(normalized_value, cx, None, None);
1687 }
1688
1689 let trait_segments = &p.segments[..p.segments.len() - 1];
1690 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1691 let trait_ = self::Path {
1692 res: Res::Def(DefKind::Trait, trait_def),
1693 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1694 };
1695 register_res(cx, trait_.res);
1696 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1697 let self_type = clean_ty(qself, cx);
1698 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1699 Type::QPath(Box::new(QPathData {
1700 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1701 should_show_cast,
1702 self_type,
1703 trait_: Some(trait_),
1704 }))
1705 }
1706 hir::QPath::TypeRelative(qself, segment) => {
1707 let ty = lower_ty(cx.tcx, hir_ty);
1708 let self_type = clean_ty(qself, cx);
1709
1710 let (trait_, should_show_cast) = match ty.kind() {
1711 ty::Alias(ty::Projection, proj) => {
1712 let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1713 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1714 register_res(cx, trait_.res);
1715 let self_def_id = res.opt_def_id();
1716 let should_show_cast =
1717 compute_should_show_cast(self_def_id, &trait_, &self_type);
1718
1719 (Some(trait_), should_show_cast)
1720 }
1721 ty::Alias(ty::Inherent, _) => (None, false),
1722 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1723 ty::Error(_) => return Type::Infer,
1724 _ => bug!("clean: expected associated type, found `{ty:?}`"),
1725 };
1726
1727 Type::QPath(Box::new(QPathData {
1728 assoc: clean_path_segment(segment, cx),
1729 should_show_cast,
1730 self_type,
1731 trait_,
1732 }))
1733 }
1734 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1735 }
1736}
1737
1738fn maybe_expand_private_type_alias<'tcx>(
1739 cx: &mut DocContext<'tcx>,
1740 path: &hir::Path<'tcx>,
1741) -> Option<Type> {
1742 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1743 // Substitute private type aliases
1744 let def_id = def_id.as_local()?;
1745 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1746 && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1747 {
1748 &cx.tcx.hir_expect_item(def_id).kind
1749 } else {
1750 return None;
1751 };
1752 let hir::ItemKind::TyAlias(_, ty, generics) = alias else { return None };
1753
1754 let final_seg = &path.segments.last().expect("segments were empty");
1755 let mut args = DefIdMap::default();
1756 let generic_args = final_seg.args();
1757
1758 let mut indices: hir::GenericParamCount = Default::default();
1759 for param in generics.params.iter() {
1760 match param.kind {
1761 hir::GenericParamKind::Lifetime { .. } => {
1762 let mut j = 0;
1763 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1764 hir::GenericArg::Lifetime(lt) => {
1765 if indices.lifetimes == j {
1766 return Some(lt);
1767 }
1768 j += 1;
1769 None
1770 }
1771 _ => None,
1772 });
1773 if let Some(lt) = lifetime {
1774 let lt = if !lt.is_anonymous() {
1775 clean_lifetime(lt, cx)
1776 } else {
1777 Lifetime::elided()
1778 };
1779 args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1780 }
1781 indices.lifetimes += 1;
1782 }
1783 hir::GenericParamKind::Type { ref default, .. } => {
1784 let mut j = 0;
1785 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1786 hir::GenericArg::Type(ty) => {
1787 if indices.types == j {
1788 return Some(ty.as_unambig_ty());
1789 }
1790 j += 1;
1791 None
1792 }
1793 _ => None,
1794 });
1795 if let Some(ty) = type_.or(*default) {
1796 args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1797 }
1798 indices.types += 1;
1799 }
1800 // FIXME(#82852): Instantiate const parameters.
1801 hir::GenericParamKind::Const { .. } => {}
1802 }
1803 }
1804
1805 Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1806 cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1807 }))
1808}
1809
1810pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1811 use rustc_hir::*;
1812
1813 match ty.kind {
1814 TyKind::Never => Primitive(PrimitiveType::Never),
1815 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1816 TyKind::Ref(l, ref m) => {
1817 let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1818 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1819 }
1820 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1821 TyKind::Pat(ty, pat) => Type::Pat(Box::new(clean_ty(ty, cx)), format!("{pat:?}").into()),
1822 TyKind::Array(ty, const_arg) => {
1823 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1824 // as we currently do not supply the parent generics to anonymous constants
1825 // but do allow `ConstKind::Param`.
1826 //
1827 // `const_eval_poly` tries to first substitute generic parameters which
1828 // results in an ICE while manually constructing the constant and using `eval`
1829 // does nothing for `ConstKind::Param`.
1830 let length = match const_arg.kind {
1831 hir::ConstArgKind::Infer(..) => "_".to_string(),
1832 hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1833 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1834 let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1835 let ct = cx.tcx.normalize_erasing_regions(typing_env, ct);
1836 print_const(cx, ct)
1837 }
1838 hir::ConstArgKind::Path(..) => {
1839 let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1840 print_const(cx, ct)
1841 }
1842 };
1843 Array(Box::new(clean_ty(ty, cx)), length.into())
1844 }
1845 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1846 TyKind::OpaqueDef(ty) => {
1847 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1848 }
1849 TyKind::Path(_) => clean_qpath(ty, cx),
1850 TyKind::TraitObject(bounds, lifetime) => {
1851 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1852 let lifetime = if !lifetime.is_elided() {
1853 Some(clean_lifetime(lifetime.pointer(), cx))
1854 } else {
1855 None
1856 };
1857 DynTrait(bounds, lifetime)
1858 }
1859 TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1860 TyKind::UnsafeBinder(unsafe_binder_ty) => {
1861 UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1862 }
1863 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1864 TyKind::Infer(())
1865 | TyKind::Err(_)
1866 | TyKind::Typeof(..)
1867 | TyKind::InferDelegation(..)
1868 | TyKind::TraitAscription(_) => Infer,
1869 }
1870}
1871
1872/// Returns `None` if the type could not be normalized
1873fn normalize<'tcx>(
1874 cx: &DocContext<'tcx>,
1875 ty: ty::Binder<'tcx, Ty<'tcx>>,
1876) -> Option<ty::Binder<'tcx, Ty<'tcx>>> {
1877 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1878 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1879 return None;
1880 }
1881
1882 use rustc_middle::traits::ObligationCause;
1883 use rustc_trait_selection::infer::TyCtxtInferExt;
1884 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1885
1886 // Try to normalize `<X as Y>::T` to a type
1887 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1888 let normalized = infcx
1889 .at(&ObligationCause::dummy(), cx.param_env)
1890 .query_normalize(ty)
1891 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1892 match normalized {
1893 Ok(normalized_value) => {
1894 debug!("normalized {ty:?} to {normalized_value:?}");
1895 Some(normalized_value)
1896 }
1897 Err(err) => {
1898 debug!("failed to normalize {ty:?}: {err:?}");
1899 None
1900 }
1901 }
1902}
1903
1904fn clean_trait_object_lifetime_bound<'tcx>(
1905 region: ty::Region<'tcx>,
1906 container: Option<ContainerTy<'_, 'tcx>>,
1907 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1908 tcx: TyCtxt<'tcx>,
1909) -> Option<Lifetime> {
1910 if can_elide_trait_object_lifetime_bound(region, container, preds, tcx) {
1911 return None;
1912 }
1913
1914 // Since there is a semantic difference between an implicitly elided (i.e. "defaulted") object
1915 // lifetime and an explicitly elided object lifetime (`'_`), we intentionally don't hide the
1916 // latter contrary to `clean_middle_region`.
1917 match region.kind() {
1918 ty::ReStatic => Some(Lifetime::statik()),
1919 ty::ReEarlyParam(region) => Some(Lifetime(region.name)),
1920 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(_, name), .. }) => {
1921 Some(Lifetime(name))
1922 }
1923 ty::ReBound(..)
1924 | ty::ReLateParam(_)
1925 | ty::ReVar(_)
1926 | ty::RePlaceholder(_)
1927 | ty::ReErased
1928 | ty::ReError(_) => None,
1929 }
1930}
1931
1932fn can_elide_trait_object_lifetime_bound<'tcx>(
1933 region: ty::Region<'tcx>,
1934 container: Option<ContainerTy<'_, 'tcx>>,
1935 preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1936 tcx: TyCtxt<'tcx>,
1937) -> bool {
1938 // Below we quote extracts from https://doc.rust-lang.org/stable/reference/lifetime-elision.html#default-trait-object-lifetimes
1939
1940 // > If the trait object is used as a type argument of a generic type then the containing type is
1941 // > first used to try to infer a bound.
1942 let default = container
1943 .map_or(ObjectLifetimeDefault::Empty, |container| container.object_lifetime_default(tcx));
1944
1945 // > If there is a unique bound from the containing type then that is the default
1946 // If there is a default object lifetime and the given region is lexically equal to it, elide it.
1947 match default {
1948 ObjectLifetimeDefault::Static => return region.kind() == ty::ReStatic,
1949 // FIXME(fmease): Don't compare lexically but respect de Bruijn indices etc. to handle shadowing correctly.
1950 ObjectLifetimeDefault::Arg(default) => return region.get_name() == default.get_name(),
1951 // > If there is more than one bound from the containing type then an explicit bound must be specified
1952 // Due to ambiguity there is no default trait-object lifetime and thus elision is impossible.
1953 // Don't elide the lifetime.
1954 ObjectLifetimeDefault::Ambiguous => return false,
1955 // There is no meaningful bound. Further processing is needed...
1956 ObjectLifetimeDefault::Empty => {}
1957 }
1958
1959 // > If neither of those rules apply, then the bounds on the trait are used:
1960 match *object_region_bounds(tcx, preds) {
1961 // > If the trait has no lifetime bounds, then the lifetime is inferred in expressions
1962 // > and is 'static outside of expressions.
1963 // FIXME: If we are in an expression context (i.e. fn bodies and const exprs) then the default is
1964 // `'_` and not `'static`. Only if we are in a non-expression one, the default is `'static`.
1965 // Note however that at the time of this writing it should be fine to disregard this subtlety
1966 // as we neither render const exprs faithfully anyway (hiding them in some places or using `_` instead)
1967 // nor show the contents of fn bodies.
1968 [] => region.kind() == ty::ReStatic,
1969 // > If the trait is defined with a single lifetime bound then that bound is used.
1970 // > If 'static is used for any lifetime bound then 'static is used.
1971 // FIXME(fmease): Don't compare lexically but respect de Bruijn indices etc. to handle shadowing correctly.
1972 [object_region] => object_region.get_name() == region.get_name(),
1973 // There are several distinct trait regions and none are `'static`.
1974 // Due to ambiguity there is no default trait-object lifetime and thus elision is impossible.
1975 // Don't elide the lifetime.
1976 _ => false,
1977 }
1978}
1979
1980#[derive(Debug)]
1981pub(crate) enum ContainerTy<'a, 'tcx> {
1982 Ref(ty::Region<'tcx>),
1983 Regular {
1984 ty: DefId,
1985 /// The arguments *have* to contain an arg for the self type if the corresponding generics
1986 /// contain a self type.
1987 args: ty::Binder<'tcx, &'a [ty::GenericArg<'tcx>]>,
1988 arg: usize,
1989 },
1990}
1991
1992impl<'tcx> ContainerTy<'_, 'tcx> {
1993 fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> {
1994 match self {
1995 Self::Ref(region) => ObjectLifetimeDefault::Arg(region),
1996 Self::Regular { ty: container, args, arg: index } => {
1997 let (DefKind::Struct
1998 | DefKind::Union
1999 | DefKind::Enum
2000 | DefKind::TyAlias
2001 | DefKind::Trait) = tcx.def_kind(container)
2002 else {
2003 return ObjectLifetimeDefault::Empty;
2004 };
2005
2006 let generics = tcx.generics_of(container);
2007 debug_assert_eq!(generics.parent_count, 0);
2008
2009 let param = generics.own_params[index].def_id;
2010 let default = tcx.object_lifetime_default(param);
2011 match default {
2012 rbv::ObjectLifetimeDefault::Param(lifetime) => {
2013 // The index is relative to the parent generics but since we don't have any,
2014 // we don't need to translate it.
2015 let index = generics.param_def_id_to_index[&lifetime];
2016 let arg = args.skip_binder()[index as usize].expect_region();
2017 ObjectLifetimeDefault::Arg(arg)
2018 }
2019 rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty,
2020 rbv::ObjectLifetimeDefault::Static => ObjectLifetimeDefault::Static,
2021 rbv::ObjectLifetimeDefault::Ambiguous => ObjectLifetimeDefault::Ambiguous,
2022 }
2023 }
2024 }
2025 }
2026}
2027
2028#[derive(Debug, Clone, Copy)]
2029pub(crate) enum ObjectLifetimeDefault<'tcx> {
2030 Empty,
2031 Static,
2032 Ambiguous,
2033 Arg(ty::Region<'tcx>),
2034}
2035
2036#[instrument(level = "trace", skip(cx), ret)]
2037pub(crate) fn clean_middle_ty<'tcx>(
2038 bound_ty: ty::Binder<'tcx, Ty<'tcx>>,
2039 cx: &mut DocContext<'tcx>,
2040 parent_def_id: Option<DefId>,
2041 container: Option<ContainerTy<'_, 'tcx>>,
2042) -> Type {
2043 let bound_ty = normalize(cx, bound_ty).unwrap_or(bound_ty);
2044 match *bound_ty.skip_binder().kind() {
2045 ty::Never => Primitive(PrimitiveType::Never),
2046 ty::Bool => Primitive(PrimitiveType::Bool),
2047 ty::Char => Primitive(PrimitiveType::Char),
2048 ty::Int(int_ty) => Primitive(int_ty.into()),
2049 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
2050 ty::Float(float_ty) => Primitive(float_ty.into()),
2051 ty::Str => Primitive(PrimitiveType::Str),
2052 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None))),
2053 ty::Pat(ty, pat) => Type::Pat(
2054 Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)),
2055 format!("{pat:?}").into_boxed_str(),
2056 ),
2057 ty::Array(ty, n) => {
2058 let n = cx.tcx.normalize_erasing_regions(cx.typing_env(), n);
2059 let n = print_const(cx, n);
2060 Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into())
2061 }
2062 ty::RawPtr(ty, mutbl) => {
2063 RawPointer(mutbl, Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)))
2064 }
2065 ty::Ref(r, ty, mutbl) => BorrowedRef {
2066 lifetime: clean_middle_region(r),
2067 mutability: mutbl,
2068 type_: Box::new(clean_middle_ty(
2069 bound_ty.rebind(ty),
2070 cx,
2071 None,
2072 Some(ContainerTy::Ref(r)),
2073 )),
2074 },
2075 ty::FnDef(..) | ty::FnPtr(..) => {
2076 // FIXME: should we merge the outer and inner binders somehow?
2077 let sig = bound_ty.skip_binder().fn_sig(cx.tcx);
2078 let decl = clean_poly_fn_sig(cx, None, sig);
2079 let generic_params = clean_bound_vars(sig.bound_vars());
2080
2081 BareFunction(Box::new(BareFunctionDecl {
2082 safety: sig.safety(),
2083 generic_params,
2084 decl,
2085 abi: sig.abi(),
2086 }))
2087 }
2088 ty::UnsafeBinder(inner) => {
2089 let generic_params = clean_bound_vars(inner.bound_vars());
2090 let ty = clean_middle_ty(inner.into(), cx, None, None);
2091 UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, ty }))
2092 }
2093 ty::Adt(def, args) => {
2094 let did = def.did();
2095 let kind = match def.adt_kind() {
2096 AdtKind::Struct => ItemType::Struct,
2097 AdtKind::Union => ItemType::Union,
2098 AdtKind::Enum => ItemType::Enum,
2099 };
2100 inline::record_extern_fqn(cx, did, kind);
2101 let path = clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args));
2102 Type::Path { path }
2103 }
2104 ty::Foreign(did) => {
2105 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
2106 let path = clean_middle_path(
2107 cx,
2108 did,
2109 false,
2110 ThinVec::new(),
2111 ty::Binder::dummy(ty::GenericArgs::empty()),
2112 );
2113 Type::Path { path }
2114 }
2115 ty::Dynamic(obj, ref reg, _) => {
2116 // HACK: pick the first `did` as the `did` of the trait object. Someone
2117 // might want to implement "native" support for marker-trait-only
2118 // trait objects.
2119 let mut dids = obj.auto_traits();
2120 let did = obj
2121 .principal_def_id()
2122 .or_else(|| dids.next())
2123 .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?"));
2124 let args = match obj.principal() {
2125 Some(principal) => principal.map_bound(|p| p.args),
2126 // marker traits have no args.
2127 _ => ty::Binder::dummy(ty::GenericArgs::empty()),
2128 };
2129
2130 inline::record_extern_fqn(cx, did, ItemType::Trait);
2131
2132 let lifetime = clean_trait_object_lifetime_bound(*reg, container, obj, cx.tcx);
2133
2134 let mut bounds = dids
2135 .map(|did| {
2136 let empty = ty::Binder::dummy(ty::GenericArgs::empty());
2137 let path = clean_middle_path(cx, did, false, ThinVec::new(), empty);
2138 inline::record_extern_fqn(cx, did, ItemType::Trait);
2139 PolyTrait { trait_: path, generic_params: Vec::new() }
2140 })
2141 .collect::<Vec<_>>();
2142
2143 let constraints = obj
2144 .projection_bounds()
2145 .map(|pb| AssocItemConstraint {
2146 assoc: projection_to_path_segment(
2147 pb.map_bound(|pb| {
2148 pb
2149 // HACK(compiler-errors): Doesn't actually matter what self
2150 // type we put here, because we're only using the GAT's args.
2151 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
2152 .projection_term
2153 // FIXME: This needs to be made resilient for `AliasTerm`s
2154 // that are associated consts.
2155 .expect_ty(cx.tcx)
2156 }),
2157 cx,
2158 ),
2159 kind: AssocItemConstraintKind::Equality {
2160 term: clean_middle_term(pb.map_bound(|pb| pb.term), cx),
2161 },
2162 })
2163 .collect();
2164
2165 let late_bound_regions: FxIndexSet<_> = obj
2166 .iter()
2167 .flat_map(|pred| pred.bound_vars())
2168 .filter_map(|var| match var {
2169 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id, name))
2170 if name != kw::UnderscoreLifetime =>
2171 {
2172 Some(GenericParamDef::lifetime(def_id, name))
2173 }
2174 _ => None,
2175 })
2176 .collect();
2177 let late_bound_regions = late_bound_regions.into_iter().collect();
2178
2179 let path = clean_middle_path(cx, did, false, constraints, args);
2180 bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
2181
2182 DynTrait(bounds, lifetime)
2183 }
2184 ty::Tuple(t) => {
2185 Tuple(t.iter().map(|t| clean_middle_ty(bound_ty.rebind(t), cx, None, None)).collect())
2186 }
2187
2188 ty::Alias(ty::Projection, data) => {
2189 clean_projection(bound_ty.rebind(data), cx, parent_def_id)
2190 }
2191
2192 ty::Alias(ty::Inherent, alias_ty) => {
2193 let def_id = alias_ty.def_id;
2194 let alias_ty = bound_ty.rebind(alias_ty);
2195 let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None, None);
2196
2197 Type::QPath(Box::new(QPathData {
2198 assoc: PathSegment {
2199 name: cx.tcx.associated_item(def_id).name(),
2200 args: GenericArgs::AngleBracketed {
2201 args: clean_middle_generic_args(
2202 cx,
2203 alias_ty.map_bound(|ty| ty.args.as_slice()),
2204 true,
2205 def_id,
2206 ),
2207 constraints: Default::default(),
2208 },
2209 },
2210 should_show_cast: false,
2211 self_type,
2212 trait_: None,
2213 }))
2214 }
2215
2216 ty::Alias(ty::Free, data) => {
2217 if cx.tcx.features().lazy_type_alias() {
2218 // Free type alias `data` represents the `type X` in `type X = Y`. If we need `Y`,
2219 // we need to use `type_of`.
2220 let path = clean_middle_path(
2221 cx,
2222 data.def_id,
2223 false,
2224 ThinVec::new(),
2225 bound_ty.rebind(data.args),
2226 );
2227 Type::Path { path }
2228 } else {
2229 let ty = cx.tcx.type_of(data.def_id).instantiate(cx.tcx, data.args);
2230 clean_middle_ty(bound_ty.rebind(ty), cx, None, None)
2231 }
2232 }
2233
2234 ty::Param(ref p) => {
2235 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
2236 ImplTrait(bounds)
2237 } else if p.name == kw::SelfUpper {
2238 SelfTy
2239 } else {
2240 Generic(p.name)
2241 }
2242 }
2243
2244 ty::Bound(_, ref ty) => match ty.kind {
2245 ty::BoundTyKind::Param(_, name) => Generic(name),
2246 ty::BoundTyKind::Anon => panic!("unexpected anonymous bound type variable"),
2247 },
2248
2249 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2250 // If it's already in the same alias, don't get an infinite loop.
2251 if cx.current_type_aliases.contains_key(&def_id) {
2252 let path =
2253 clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2254 Type::Path { path }
2255 } else {
2256 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2257 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
2258 // by looking up the bounds associated with the def_id.
2259 let ty = clean_middle_opaque_bounds(cx, def_id, args);
2260 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2261 *count -= 1;
2262 if *count == 0 {
2263 cx.current_type_aliases.remove(&def_id);
2264 }
2265 }
2266 ty
2267 }
2268 }
2269
2270 ty::Closure(..) => panic!("Closure"),
2271 ty::CoroutineClosure(..) => panic!("CoroutineClosure"),
2272 ty::Coroutine(..) => panic!("Coroutine"),
2273 ty::Placeholder(..) => panic!("Placeholder"),
2274 ty::CoroutineWitness(..) => panic!("CoroutineWitness"),
2275 ty::Infer(..) => panic!("Infer"),
2276
2277 ty::Error(_) => FatalError.raise(),
2278 }
2279}
2280
2281fn clean_middle_opaque_bounds<'tcx>(
2282 cx: &mut DocContext<'tcx>,
2283 impl_trait_def_id: DefId,
2284 args: ty::GenericArgsRef<'tcx>,
2285) -> Type {
2286 let mut has_sized = false;
2287
2288 let bounds: Vec<_> = cx
2289 .tcx
2290 .explicit_item_bounds(impl_trait_def_id)
2291 .iter_instantiated_copied(cx.tcx, args)
2292 .collect();
2293
2294 let mut bounds = bounds
2295 .iter()
2296 .filter_map(|(bound, _)| {
2297 let bound_predicate = bound.kind();
2298 let trait_ref = match bound_predicate.skip_binder() {
2299 ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
2300 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
2301 return clean_middle_region(reg).map(GenericBound::Outlives);
2302 }
2303 _ => return None,
2304 };
2305
2306 if let Some(sized) = cx.tcx.lang_items().sized_trait()
2307 && trait_ref.def_id() == sized
2308 {
2309 has_sized = true;
2310 return None;
2311 }
2312
2313 let bindings: ThinVec<_> = bounds
2314 .iter()
2315 .filter_map(|(bound, _)| {
2316 if let ty::ClauseKind::Projection(proj) = bound.kind().skip_binder()
2317 && proj.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
2318 {
2319 return Some(AssocItemConstraint {
2320 assoc: projection_to_path_segment(
2321 // FIXME: This needs to be made resilient for `AliasTerm`s that
2322 // are associated consts.
2323 bound.kind().rebind(proj.projection_term.expect_ty(cx.tcx)),
2324 cx,
2325 ),
2326 kind: AssocItemConstraintKind::Equality {
2327 term: clean_middle_term(bound.kind().rebind(proj.term), cx),
2328 },
2329 });
2330 }
2331 None
2332 })
2333 .collect();
2334
2335 Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings))
2336 })
2337 .collect::<Vec<_>>();
2338
2339 if !has_sized {
2340 bounds.push(GenericBound::maybe_sized(cx));
2341 }
2342
2343 // Move trait bounds to the front.
2344 bounds.sort_by_key(|b| !b.is_trait_bound());
2345
2346 // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`).
2347 // Since all potential trait bounds are at the front we can just check the first bound.
2348 if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
2349 bounds.insert(0, GenericBound::sized(cx));
2350 }
2351
2352 if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) {
2353 bounds.push(GenericBound::Use(
2354 args.iter()
2355 .map(|arg| match arg {
2356 hir::PreciseCapturingArgKind::Lifetime(lt) => {
2357 PreciseCapturingArg::Lifetime(Lifetime(*lt))
2358 }
2359 hir::PreciseCapturingArgKind::Param(param) => {
2360 PreciseCapturingArg::Param(*param)
2361 }
2362 })
2363 .collect(),
2364 ));
2365 }
2366
2367 ImplTrait(bounds)
2368}
2369
2370pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2371 clean_field_with_def_id(field.def_id.to_def_id(), field.ident.name, clean_ty(field.ty, cx), cx)
2372}
2373
2374pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item {
2375 clean_field_with_def_id(
2376 field.did,
2377 field.name,
2378 clean_middle_ty(
2379 ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity()),
2380 cx,
2381 Some(field.did),
2382 None,
2383 ),
2384 cx,
2385 )
2386}
2387
2388pub(crate) fn clean_field_with_def_id(
2389 def_id: DefId,
2390 name: Symbol,
2391 ty: Type,
2392 cx: &mut DocContext<'_>,
2393) -> Item {
2394 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
2395}
2396
2397pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item {
2398 let discriminant = match variant.discr {
2399 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2400 ty::VariantDiscr::Relative(_) => None,
2401 };
2402
2403 let kind = match variant.ctor_kind() {
2404 Some(CtorKind::Const) => VariantKind::CLike,
2405 Some(CtorKind::Fn) => VariantKind::Tuple(
2406 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2407 ),
2408 None => VariantKind::Struct(VariantStruct {
2409 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2410 }),
2411 };
2412
2413 Item::from_def_id_and_parts(
2414 variant.def_id,
2415 Some(variant.name),
2416 VariantItem(Variant { kind, discriminant }),
2417 cx,
2418 )
2419}
2420
2421pub(crate) fn clean_variant_def_with_args<'tcx>(
2422 variant: &ty::VariantDef,
2423 args: &GenericArgsRef<'tcx>,
2424 cx: &mut DocContext<'tcx>,
2425) -> Item {
2426 let discriminant = match variant.discr {
2427 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2428 ty::VariantDiscr::Relative(_) => None,
2429 };
2430
2431 use rustc_middle::traits::ObligationCause;
2432 use rustc_trait_selection::infer::TyCtxtInferExt;
2433 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
2434
2435 let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2436 let kind = match variant.ctor_kind() {
2437 Some(CtorKind::Const) => VariantKind::CLike,
2438 Some(CtorKind::Fn) => VariantKind::Tuple(
2439 variant
2440 .fields
2441 .iter()
2442 .map(|field| {
2443 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2444
2445 // normalize the type to only show concrete types
2446 // note: we do not use try_normalize_erasing_regions since we
2447 // do care about showing the regions
2448 let ty = infcx
2449 .at(&ObligationCause::dummy(), cx.param_env)
2450 .query_normalize(ty)
2451 .map(|normalized| normalized.value)
2452 .unwrap_or(ty);
2453
2454 clean_field_with_def_id(
2455 field.did,
2456 field.name,
2457 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2458 cx,
2459 )
2460 })
2461 .collect(),
2462 ),
2463 None => VariantKind::Struct(VariantStruct {
2464 fields: variant
2465 .fields
2466 .iter()
2467 .map(|field| {
2468 let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args);
2469
2470 // normalize the type to only show concrete types
2471 // note: we do not use try_normalize_erasing_regions since we
2472 // do care about showing the regions
2473 let ty = infcx
2474 .at(&ObligationCause::dummy(), cx.param_env)
2475 .query_normalize(ty)
2476 .map(|normalized| normalized.value)
2477 .unwrap_or(ty);
2478
2479 clean_field_with_def_id(
2480 field.did,
2481 field.name,
2482 clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2483 cx,
2484 )
2485 })
2486 .collect(),
2487 }),
2488 };
2489
2490 Item::from_def_id_and_parts(
2491 variant.def_id,
2492 Some(variant.name),
2493 VariantItem(Variant { kind, discriminant }),
2494 cx,
2495 )
2496}
2497
2498fn clean_variant_data<'tcx>(
2499 variant: &hir::VariantData<'tcx>,
2500 disr_expr: &Option<&hir::AnonConst>,
2501 cx: &mut DocContext<'tcx>,
2502) -> Variant {
2503 let discriminant = disr_expr
2504 .map(|disr| Discriminant { expr: Some(disr.body), value: disr.def_id.to_def_id() });
2505
2506 let kind = match variant {
2507 hir::VariantData::Struct { fields, .. } => VariantKind::Struct(VariantStruct {
2508 fields: fields.iter().map(|x| clean_field(x, cx)).collect(),
2509 }),
2510 hir::VariantData::Tuple(..) => {
2511 VariantKind::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
2512 }
2513 hir::VariantData::Unit(..) => VariantKind::CLike,
2514 };
2515
2516 Variant { discriminant, kind }
2517}
2518
2519fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
2520 Path {
2521 res: path.res,
2522 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
2523 }
2524}
2525
2526fn clean_generic_args<'tcx>(
2527 generic_args: &hir::GenericArgs<'tcx>,
2528 cx: &mut DocContext<'tcx>,
2529) -> GenericArgs {
2530 match generic_args.parenthesized {
2531 hir::GenericArgsParentheses::No => {
2532 let args = generic_args
2533 .args
2534 .iter()
2535 .map(|arg| match arg {
2536 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
2537 GenericArg::Lifetime(clean_lifetime(lt, cx))
2538 }
2539 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2540 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)),
2541 hir::GenericArg::Const(ct) => {
2542 GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct(), cx)))
2543 }
2544 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
2545 })
2546 .collect();
2547 let constraints = generic_args
2548 .constraints
2549 .iter()
2550 .map(|c| clean_assoc_item_constraint(c, cx))
2551 .collect::<ThinVec<_>>();
2552 GenericArgs::AngleBracketed { args, constraints }
2553 }
2554 hir::GenericArgsParentheses::ParenSugar => {
2555 let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else {
2556 bug!();
2557 };
2558 let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect();
2559 let output = match output.kind {
2560 hir::TyKind::Tup(&[]) => None,
2561 _ => Some(Box::new(clean_ty(output, cx))),
2562 };
2563 GenericArgs::Parenthesized { inputs, output }
2564 }
2565 hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
2566 }
2567}
2568
2569fn clean_path_segment<'tcx>(
2570 path: &hir::PathSegment<'tcx>,
2571 cx: &mut DocContext<'tcx>,
2572) -> PathSegment {
2573 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
2574}
2575
2576fn clean_bare_fn_ty<'tcx>(
2577 bare_fn: &hir::BareFnTy<'tcx>,
2578 cx: &mut DocContext<'tcx>,
2579) -> BareFunctionDecl {
2580 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
2581 // NOTE: Generics must be cleaned before params.
2582 let generic_params = bare_fn
2583 .generic_params
2584 .iter()
2585 .filter(|p| !is_elided_lifetime(p))
2586 .map(|x| clean_generic_param(cx, None, x))
2587 .collect();
2588 // Since it's more conventional stylistically, elide the name of all params called `_`
2589 // unless there's at least one interestingly named param in which case don't elide any
2590 // name since mixing named and unnamed params is less legible.
2591 let filter = |ident: Option<Ident>| {
2592 ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore)
2593 };
2594 let fallback =
2595 bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore);
2596 let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents, |ident| {
2597 filter(ident).or(fallback)
2598 });
2599 let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params);
2600 (generic_params, decl)
2601 });
2602 BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params }
2603}
2604
2605fn clean_unsafe_binder_ty<'tcx>(
2606 unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>,
2607 cx: &mut DocContext<'tcx>,
2608) -> UnsafeBinderTy {
2609 let generic_params = unsafe_binder_ty
2610 .generic_params
2611 .iter()
2612 .filter(|p| !is_elided_lifetime(p))
2613 .map(|x| clean_generic_param(cx, None, x))
2614 .collect();
2615 let ty = clean_ty(unsafe_binder_ty.inner_ty, cx);
2616 UnsafeBinderTy { generic_params, ty }
2617}
2618
2619pub(crate) fn reexport_chain(
2620 tcx: TyCtxt<'_>,
2621 import_def_id: LocalDefId,
2622 target_def_id: DefId,
2623) -> &[Reexport] {
2624 for child in tcx.module_children_local(tcx.local_parent(import_def_id)) {
2625 if child.res.opt_def_id() == Some(target_def_id)
2626 && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id())
2627 {
2628 return &child.reexport_chain;
2629 }
2630 }
2631 &[]
2632}
2633
2634/// Collect attributes from the whole import chain.
2635fn get_all_import_attributes<'hir>(
2636 cx: &mut DocContext<'hir>,
2637 import_def_id: LocalDefId,
2638 target_def_id: DefId,
2639 is_inline: bool,
2640) -> Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)> {
2641 let mut attrs = Vec::new();
2642 let mut first = true;
2643 for def_id in reexport_chain(cx.tcx, import_def_id, target_def_id)
2644 .iter()
2645 .flat_map(|reexport| reexport.id())
2646 {
2647 let import_attrs = inline::load_attrs(cx, def_id);
2648 if first {
2649 // This is the "original" reexport so we get all its attributes without filtering them.
2650 attrs = import_attrs.iter().map(|attr| (Cow::Borrowed(attr), Some(def_id))).collect();
2651 first = false;
2652 // We don't add attributes of an intermediate re-export if it has `#[doc(hidden)]`.
2653 } else if cx.render_options.document_hidden || !cx.tcx.is_doc_hidden(def_id) {
2654 add_without_unwanted_attributes(&mut attrs, import_attrs, is_inline, Some(def_id));
2655 }
2656 }
2657 attrs
2658}
2659
2660fn filter_tokens_from_list(
2661 args_tokens: &TokenStream,
2662 should_retain: impl Fn(&TokenTree) -> bool,
2663) -> Vec<TokenTree> {
2664 let mut tokens = Vec::with_capacity(args_tokens.len());
2665 let mut skip_next_comma = false;
2666 for token in args_tokens.iter() {
2667 match token {
2668 TokenTree::Token(Token { kind: TokenKind::Comma, .. }, _) if skip_next_comma => {
2669 skip_next_comma = false;
2670 }
2671 token if should_retain(token) => {
2672 skip_next_comma = false;
2673 tokens.push(token.clone());
2674 }
2675 _ => {
2676 skip_next_comma = true;
2677 }
2678 }
2679 }
2680 tokens
2681}
2682
2683fn filter_doc_attr_ident(ident: Symbol, is_inline: bool) -> bool {
2684 if is_inline {
2685 ident == sym::hidden || ident == sym::inline || ident == sym::no_inline
2686 } else {
2687 ident == sym::cfg
2688 }
2689}
2690
2691/// Remove attributes from `normal` that should not be inherited by `use` re-export.
2692/// Before calling this function, make sure `normal` is a `#[doc]` attribute.
2693fn filter_doc_attr(args: &mut hir::AttrArgs, is_inline: bool) {
2694 match args {
2695 hir::AttrArgs::Delimited(args) => {
2696 let tokens = filter_tokens_from_list(&args.tokens, |token| {
2697 !matches!(
2698 token,
2699 TokenTree::Token(
2700 Token {
2701 kind: TokenKind::Ident(
2702 ident,
2703 _,
2704 ),
2705 ..
2706 },
2707 _,
2708 ) if filter_doc_attr_ident(*ident, is_inline),
2709 )
2710 });
2711 args.tokens = TokenStream::new(tokens);
2712 }
2713 hir::AttrArgs::Empty | hir::AttrArgs::Eq { .. } => {}
2714 }
2715}
2716
2717/// When inlining items, we merge their attributes (and all the reexports attributes too) with the
2718/// final reexport. For example:
2719///
2720/// ```ignore (just an example)
2721/// #[doc(hidden, cfg(feature = "foo"))]
2722/// pub struct Foo;
2723///
2724/// #[doc(cfg(feature = "bar"))]
2725/// #[doc(hidden, no_inline)]
2726/// pub use Foo as Foo1;
2727///
2728/// #[doc(inline)]
2729/// pub use Foo2 as Bar;
2730/// ```
2731///
2732/// So `Bar` at the end will have both `cfg(feature = "...")`. However, we don't want to merge all
2733/// attributes so we filter out the following ones:
2734/// * `doc(inline)`
2735/// * `doc(no_inline)`
2736/// * `doc(hidden)`
2737fn add_without_unwanted_attributes<'hir>(
2738 attrs: &mut Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)>,
2739 new_attrs: &'hir [hir::Attribute],
2740 is_inline: bool,
2741 import_parent: Option<DefId>,
2742) {
2743 for attr in new_attrs {
2744 if attr.is_doc_comment() {
2745 attrs.push((Cow::Borrowed(attr), import_parent));
2746 continue;
2747 }
2748 let mut attr = attr.clone();
2749 match attr {
2750 hir::Attribute::Unparsed(ref mut normal) if let [ident] = &*normal.path.segments => {
2751 let ident = ident.name;
2752 if ident == sym::doc {
2753 filter_doc_attr(&mut normal.args, is_inline);
2754 attrs.push((Cow::Owned(attr), import_parent));
2755 } else if is_inline || ident != sym::cfg_trace {
2756 // If it's not a `cfg()` attribute, we keep it.
2757 attrs.push((Cow::Owned(attr), import_parent));
2758 }
2759 }
2760 hir::Attribute::Parsed(..) if is_inline => {
2761 attrs.push((Cow::Owned(attr), import_parent));
2762 }
2763 _ => {}
2764 }
2765 }
2766}
2767
2768fn clean_maybe_renamed_item<'tcx>(
2769 cx: &mut DocContext<'tcx>,
2770 item: &hir::Item<'tcx>,
2771 renamed: Option<Symbol>,
2772 import_id: Option<LocalDefId>,
2773) -> Vec<Item> {
2774 use hir::ItemKind;
2775
2776 fn get_name(
2777 cx: &DocContext<'_>,
2778 item: &hir::Item<'_>,
2779 renamed: Option<Symbol>,
2780 ) -> Option<Symbol> {
2781 renamed.or_else(|| cx.tcx.hir_opt_name(item.hir_id()))
2782 }
2783
2784 let def_id = item.owner_id.to_def_id();
2785 cx.with_param_env(def_id, |cx| {
2786 // These kinds of item either don't need a `name` or accept a `None` one so we handle them
2787 // before.
2788 match item.kind {
2789 ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx),
2790 ItemKind::Use(path, kind) => {
2791 return clean_use_statement(
2792 item,
2793 get_name(cx, item, renamed),
2794 path,
2795 kind,
2796 cx,
2797 &mut FxHashSet::default(),
2798 );
2799 }
2800 _ => {}
2801 }
2802
2803 let mut name = get_name(cx, item, renamed).unwrap();
2804
2805 let kind = match item.kind {
2806 ItemKind::Static(_, ty, mutability, body_id) => StaticItem(Static {
2807 type_: Box::new(clean_ty(ty, cx)),
2808 mutability,
2809 expr: Some(body_id),
2810 }),
2811 ItemKind::Const(_, ty, generics, body_id) => ConstantItem(Box::new(Constant {
2812 generics: clean_generics(generics, cx),
2813 type_: clean_ty(ty, cx),
2814 kind: ConstantKind::Local { body: body_id, def_id },
2815 })),
2816 ItemKind::TyAlias(_, hir_ty, generics) => {
2817 *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2818 let rustdoc_ty = clean_ty(hir_ty, cx);
2819 let type_ =
2820 clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
2821 let generics = clean_generics(generics, cx);
2822 if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2823 *count -= 1;
2824 if *count == 0 {
2825 cx.current_type_aliases.remove(&def_id);
2826 }
2827 }
2828
2829 let ty = cx.tcx.type_of(def_id).instantiate_identity();
2830
2831 let mut ret = Vec::new();
2832 let inner_type = clean_ty_alias_inner_type(ty, cx, &mut ret);
2833
2834 ret.push(generate_item_with_correct_attrs(
2835 cx,
2836 TypeAliasItem(Box::new(TypeAlias {
2837 generics,
2838 inner_type,
2839 type_: rustdoc_ty,
2840 item_type: Some(type_),
2841 })),
2842 item.owner_id.def_id.to_def_id(),
2843 name,
2844 import_id,
2845 renamed,
2846 ));
2847 return ret;
2848 }
2849 ItemKind::Enum(_, ref def, generics) => EnumItem(Enum {
2850 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2851 generics: clean_generics(generics, cx),
2852 }),
2853 ItemKind::TraitAlias(_, generics, bounds) => TraitAliasItem(TraitAlias {
2854 generics: clean_generics(generics, cx),
2855 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2856 }),
2857 ItemKind::Union(_, ref variant_data, generics) => UnionItem(Union {
2858 generics: clean_generics(generics, cx),
2859 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2860 }),
2861 ItemKind::Struct(_, ref variant_data, generics) => StructItem(Struct {
2862 ctor_kind: variant_data.ctor_kind(),
2863 generics: clean_generics(generics, cx),
2864 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2865 }),
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 // proc macros can have a name set by attributes
2872 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 _ => span_bug!(item.span, "not yet converted"),
2892 };
2893
2894 vec![generate_item_with_correct_attrs(
2895 cx,
2896 kind,
2897 item.owner_id.def_id.to_def_id(),
2898 name,
2899 import_id,
2900 renamed,
2901 )]
2902 })
2903}
2904
2905fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2906 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2907 Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx)
2908}
2909
2910fn clean_impl<'tcx>(
2911 impl_: &hir::Impl<'tcx>,
2912 def_id: LocalDefId,
2913 cx: &mut DocContext<'tcx>,
2914) -> Vec<Item> {
2915 let tcx = cx.tcx;
2916 let mut ret = Vec::new();
2917 let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
2918 let items = impl_
2919 .items
2920 .iter()
2921 .map(|ii| clean_impl_item(tcx.hir_impl_item(ii.id), cx))
2922 .collect::<Vec<_>>();
2923
2924 // If this impl block is an implementation of the Deref trait, then we
2925 // need to try inlining the target's inherent impl blocks as well.
2926 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2927 build_deref_target_impls(cx, &items, &mut ret);
2928 }
2929
2930 let for_ = clean_ty(impl_.self_ty, cx);
2931 let type_alias =
2932 for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) {
2933 DefKind::TyAlias => Some(clean_middle_ty(
2934 ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()),
2935 cx,
2936 Some(def_id.to_def_id()),
2937 None,
2938 )),
2939 _ => None,
2940 });
2941 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2942 let kind = ImplItem(Box::new(Impl {
2943 safety: impl_.safety,
2944 generics: clean_generics(impl_.generics, cx),
2945 trait_,
2946 for_,
2947 items,
2948 polarity: tcx.impl_polarity(def_id),
2949 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2950 ImplKind::FakeVariadic
2951 } else {
2952 ImplKind::Normal
2953 },
2954 }));
2955 Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, cx)
2956 };
2957 if let Some(type_alias) = type_alias {
2958 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2959 }
2960 ret.push(make_item(trait_, for_, items));
2961 ret
2962}
2963
2964fn clean_extern_crate<'tcx>(
2965 krate: &hir::Item<'tcx>,
2966 name: Symbol,
2967 orig_name: Option<Symbol>,
2968 cx: &mut DocContext<'tcx>,
2969) -> Vec<Item> {
2970 // this is the ID of the `extern crate` statement
2971 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2972 // this is the ID of the crate itself
2973 let crate_def_id = cnum.as_def_id();
2974 let attrs = cx.tcx.hir_attrs(krate.hir_id());
2975 let ty_vis = cx.tcx.visibility(krate.owner_id);
2976 let please_inline = ty_vis.is_public()
2977 && attrs.iter().any(|a| {
2978 a.has_name(sym::doc)
2979 && match a.meta_item_list() {
2980 Some(l) => ast::attr::list_contains_name(&l, sym::inline),
2981 None => false,
2982 }
2983 })
2984 && !cx.is_json_output();
2985
2986 let krate_owner_def_id = krate.owner_id.def_id;
2987 if please_inline
2988 && let Some(items) = inline::try_inline(
2989 cx,
2990 Res::Def(DefKind::Mod, crate_def_id),
2991 name,
2992 Some((attrs, Some(krate_owner_def_id))),
2993 &mut Default::default(),
2994 )
2995 {
2996 return items;
2997 }
2998
2999 vec![Item::from_def_id_and_parts(
3000 krate_owner_def_id.to_def_id(),
3001 Some(name),
3002 ExternCrateItem { src: orig_name },
3003 cx,
3004 )]
3005}
3006
3007fn clean_use_statement<'tcx>(
3008 import: &hir::Item<'tcx>,
3009 name: Option<Symbol>,
3010 path: &hir::UsePath<'tcx>,
3011 kind: hir::UseKind,
3012 cx: &mut DocContext<'tcx>,
3013 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3014) -> Vec<Item> {
3015 let mut items = Vec::new();
3016 let hir::UsePath { segments, ref res, span } = *path;
3017 for &res in res {
3018 let path = hir::Path { segments, res, span };
3019 items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
3020 }
3021 items
3022}
3023
3024fn clean_use_statement_inner<'tcx>(
3025 import: &hir::Item<'tcx>,
3026 name: Option<Symbol>,
3027 path: &hir::Path<'tcx>,
3028 kind: hir::UseKind,
3029 cx: &mut DocContext<'tcx>,
3030 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3031) -> Vec<Item> {
3032 if should_ignore_res(path.res) {
3033 return Vec::new();
3034 }
3035 // We need this comparison because some imports (for std types for example)
3036 // are "inserted" as well but directly by the compiler and they should not be
3037 // taken into account.
3038 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
3039 return Vec::new();
3040 }
3041
3042 let visibility = cx.tcx.visibility(import.owner_id);
3043 let attrs = cx.tcx.hir_attrs(import.hir_id());
3044 let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline);
3045 let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
3046 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
3047 let import_def_id = import.owner_id.def_id;
3048
3049 // The parent of the module in which this import resides. This
3050 // is the same as `current_mod` if that's already the top
3051 // level module.
3052 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
3053
3054 // This checks if the import can be seen from a higher level module.
3055 // In other words, it checks if the visibility is the equivalent of
3056 // `pub(super)` or higher. If the current module is the top level
3057 // module, there isn't really a parent module, which makes the results
3058 // meaningless. In this case, we make sure the answer is `false`.
3059 let is_visible_from_parent_mod =
3060 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3061
3062 if pub_underscore && let Some(ref inline) = inline_attr {
3063 struct_span_code_err!(
3064 cx.tcx.dcx(),
3065 inline.span(),
3066 E0780,
3067 "anonymous imports cannot be inlined"
3068 )
3069 .with_span_label(import.span, "anonymous import")
3070 .emit();
3071 }
3072
3073 // We consider inlining the documentation of `pub use` statements, but we
3074 // forcefully don't inline if this is not public or if the
3075 // #[doc(no_inline)] attribute is present.
3076 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
3077 let mut denied = cx.is_json_output()
3078 || !(visibility.is_public()
3079 || (cx.render_options.document_private && is_visible_from_parent_mod))
3080 || pub_underscore
3081 || attrs.iter().any(|a| {
3082 a.has_name(sym::doc)
3083 && match a.meta_item_list() {
3084 Some(l) => {
3085 ast::attr::list_contains_name(&l, sym::no_inline)
3086 || ast::attr::list_contains_name(&l, sym::hidden)
3087 }
3088 None => false,
3089 }
3090 });
3091
3092 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
3093 // crate in Rust 2018+
3094 let path = clean_path(path, cx);
3095 let inner = if kind == hir::UseKind::Glob {
3096 if !denied {
3097 let mut visited = DefIdSet::default();
3098 if let Some(items) = inline::try_inline_glob(
3099 cx,
3100 path.res,
3101 current_mod,
3102 &mut visited,
3103 inlined_names,
3104 import,
3105 ) {
3106 return items;
3107 }
3108 }
3109 Import::new_glob(resolve_use_source(cx, path), true)
3110 } else {
3111 let name = name.unwrap();
3112 if inline_attr.is_none()
3113 && let Res::Def(DefKind::Mod, did) = path.res
3114 && !did.is_local()
3115 && did.is_crate_root()
3116 {
3117 // if we're `pub use`ing an extern crate root, don't inline it unless we
3118 // were specifically asked for it
3119 denied = true;
3120 }
3121 if !denied
3122 && let Some(mut items) = inline::try_inline(
3123 cx,
3124 path.res,
3125 name,
3126 Some((attrs, Some(import_def_id))),
3127 &mut Default::default(),
3128 )
3129 {
3130 items.push(Item::from_def_id_and_parts(
3131 import_def_id.to_def_id(),
3132 None,
3133 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3134 cx,
3135 ));
3136 return items;
3137 }
3138 Import::new_simple(name, resolve_use_source(cx, path), true)
3139 };
3140
3141 vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx)]
3142}
3143
3144fn clean_maybe_renamed_foreign_item<'tcx>(
3145 cx: &mut DocContext<'tcx>,
3146 item: &hir::ForeignItem<'tcx>,
3147 renamed: Option<Symbol>,
3148) -> Item {
3149 let def_id = item.owner_id.to_def_id();
3150 cx.with_param_env(def_id, |cx| {
3151 let kind = match item.kind {
3152 hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3153 clean_function(cx, &sig, generics, ParamsSrc::Idents(idents)),
3154 sig.header.safety(),
3155 ),
3156 hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3157 Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3158 safety,
3159 ),
3160 hir::ForeignItemKind::Type => ForeignTypeItem,
3161 };
3162
3163 Item::from_def_id_and_parts(
3164 item.owner_id.def_id.to_def_id(),
3165 Some(renamed.unwrap_or(item.ident.name)),
3166 kind,
3167 cx,
3168 )
3169 })
3170}
3171
3172fn clean_assoc_item_constraint<'tcx>(
3173 constraint: &hir::AssocItemConstraint<'tcx>,
3174 cx: &mut DocContext<'tcx>,
3175) -> AssocItemConstraint {
3176 AssocItemConstraint {
3177 assoc: PathSegment {
3178 name: constraint.ident.name,
3179 args: clean_generic_args(constraint.gen_args, cx),
3180 },
3181 kind: match constraint.kind {
3182 hir::AssocItemConstraintKind::Equality { ref term } => {
3183 AssocItemConstraintKind::Equality { term: clean_hir_term(term, cx) }
3184 }
3185 hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3186 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3187 },
3188 },
3189 }
3190}
3191
3192fn clean_bound_vars(bound_vars: &ty::List<ty::BoundVariableKind>) -> Vec<GenericParamDef> {
3193 bound_vars
3194 .into_iter()
3195 .filter_map(|var| match var {
3196 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id, name))
3197 if name != kw::UnderscoreLifetime =>
3198 {
3199 Some(GenericParamDef::lifetime(def_id, name))
3200 }
3201 ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id, name)) => {
3202 Some(GenericParamDef {
3203 name,
3204 def_id,
3205 kind: GenericParamDefKind::Type {
3206 bounds: ThinVec::new(),
3207 default: None,
3208 synthetic: false,
3209 },
3210 })
3211 }
3212 // FIXME(non_lifetime_binders): Support higher-ranked const parameters.
3213 ty::BoundVariableKind::Const => None,
3214 _ => None,
3215 })
3216 .collect()
3217}