]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
Auto merge of #105350 - compiler-errors:faster-binder-relate, r=oli-obk
[rust.git] / src / librustdoc / clean / mod.rs
1 //! This module contains the "cleaned" pieces of the AST, and the functions
2 //! that clean them.
3
4 mod auto_trait;
5 mod blanket_impl;
6 pub(crate) mod cfg;
7 pub(crate) mod inline;
8 mod render_macro_matchers;
9 mod simplify;
10 pub(crate) mod types;
11 pub(crate) mod utils;
12
13 use rustc_ast as ast;
14 use rustc_attr as attr;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry};
16 use rustc_hir as hir;
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_hir::PredicateOrigin;
20 use rustc_hir_analysis::hir_ty_to_ty;
21 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
22 use rustc_middle::middle::resolve_lifetime as rl;
23 use rustc_middle::ty::fold::TypeFolder;
24 use rustc_middle::ty::InternalSubsts;
25 use rustc_middle::ty::{self, AdtKind, DefIdTree, EarlyBinder, Ty, TyCtxt};
26 use rustc_middle::{bug, span_bug};
27 use rustc_span::hygiene::{AstPass, MacroKind};
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{self, ExpnKind};
30
31 use std::assert_matches::assert_matches;
32 use std::collections::hash_map::Entry;
33 use std::collections::BTreeMap;
34 use std::default::Default;
35 use std::hash::Hash;
36 use std::mem;
37 use thin_vec::ThinVec;
38
39 use crate::core::{self, DocContext, ImplTraitParam};
40 use crate::formats::item_type::ItemType;
41 use crate::visit_ast::Module as DocModule;
42
43 use utils::*;
44
45 pub(crate) use self::types::*;
46 pub(crate) use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
47
48 pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
49     let mut items: Vec<Item> = vec![];
50     let mut inserted = FxHashSet::default();
51     items.extend(doc.foreigns.iter().map(|(item, renamed)| {
52         let item = clean_maybe_renamed_foreign_item(cx, item, *renamed);
53         if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) {
54             inserted.insert((item.type_(), name));
55         }
56         item
57     }));
58     items.extend(doc.mods.iter().filter_map(|x| {
59         if !inserted.insert((ItemType::Module, x.name)) {
60             return None;
61         }
62         let item = clean_doc_module(x, cx);
63         if item.attrs.lists(sym::doc).has_word(sym::hidden) {
64             // Hidden modules are stripped at a later stage.
65             // If a hidden module has the same name as a visible one, we want
66             // to keep both of them around.
67             inserted.remove(&(ItemType::Module, x.name));
68         }
69         Some(item)
70     }));
71
72     // Split up imports from all other items.
73     //
74     // This covers the case where somebody does an import which should pull in an item,
75     // but there's already an item with the same namespace and same name. Rust gives
76     // priority to the not-imported one, so we should, too.
77     items.extend(doc.items.iter().flat_map(|(item, renamed, import_id)| {
78         // First, lower everything other than imports.
79         if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
80             return Vec::new();
81         }
82         let v = clean_maybe_renamed_item(cx, item, *renamed, *import_id);
83         for item in &v {
84             if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) {
85                 inserted.insert((item.type_(), name));
86             }
87         }
88         v
89     }));
90     items.extend(doc.items.iter().flat_map(|(item, renamed, _)| {
91         // Now we actually lower the imports, skipping everything else.
92         if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
93             let name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
94             clean_use_statement(item, name, path, hir::UseKind::Glob, cx, &mut inserted)
95         } else {
96             // skip everything else
97             Vec::new()
98         }
99     }));
100
101     // determine if we should display the inner contents or
102     // the outer `mod` item for the source code.
103
104     let span = Span::new({
105         let where_outer = doc.where_outer(cx.tcx);
106         let sm = cx.sess().source_map();
107         let outer = sm.lookup_char_pos(where_outer.lo());
108         let inner = sm.lookup_char_pos(doc.where_inner.lo());
109         if outer.file.start_pos == inner.file.start_pos {
110             // mod foo { ... }
111             where_outer
112         } else {
113             // mod foo; (and a separate SourceFile for the contents)
114             doc.where_inner
115         }
116     });
117
118     Item::from_hir_id_and_parts(doc.id, Some(doc.name), ModuleItem(Module { items, span }), cx)
119 }
120
121 fn clean_generic_bound<'tcx>(
122     bound: &hir::GenericBound<'tcx>,
123     cx: &mut DocContext<'tcx>,
124 ) -> Option<GenericBound> {
125     Some(match *bound {
126         hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
127         hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
128             let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
129
130             let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
131
132             let generic_args = clean_generic_args(generic_args, cx);
133             let GenericArgs::AngleBracketed { bindings, .. } = generic_args
134             else {
135                 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
136             };
137
138             let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, bindings);
139             GenericBound::TraitBound(
140                 PolyTrait { trait_, generic_params: vec![] },
141                 hir::TraitBoundModifier::None,
142             )
143         }
144         hir::GenericBound::Trait(ref t, modifier) => {
145             // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
146             if modifier == hir::TraitBoundModifier::MaybeConst
147                 && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
148             {
149                 return None;
150             }
151
152             GenericBound::TraitBound(clean_poly_trait_ref(t, cx), modifier)
153         }
154     })
155 }
156
157 pub(crate) fn clean_trait_ref_with_bindings<'tcx>(
158     cx: &mut DocContext<'tcx>,
159     trait_ref: ty::TraitRef<'tcx>,
160     bindings: ThinVec<TypeBinding>,
161 ) -> Path {
162     let kind = cx.tcx.def_kind(trait_ref.def_id).into();
163     if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
164         span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
165     }
166     inline::record_extern_fqn(cx, trait_ref.def_id, kind);
167     let path = external_path(cx, trait_ref.def_id, true, bindings, trait_ref.substs);
168
169     debug!("ty::TraitRef\n  subst: {:?}\n", trait_ref.substs);
170
171     path
172 }
173
174 fn clean_poly_trait_ref_with_bindings<'tcx>(
175     cx: &mut DocContext<'tcx>,
176     poly_trait_ref: ty::PolyTraitRef<'tcx>,
177     bindings: ThinVec<TypeBinding>,
178 ) -> GenericBound {
179     // collect any late bound regions
180     let late_bound_regions: Vec<_> = cx
181         .tcx
182         .collect_referenced_late_bound_regions(&poly_trait_ref)
183         .into_iter()
184         .filter_map(|br| match br {
185             ty::BrNamed(_, name) if br.is_named() => Some(GenericParamDef::lifetime(name)),
186             _ => None,
187         })
188         .collect();
189
190     let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
191     GenericBound::TraitBound(
192         PolyTrait { trait_, generic_params: late_bound_regions },
193         hir::TraitBoundModifier::None,
194     )
195 }
196
197 fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime {
198     let def = cx.tcx.named_region(lifetime.hir_id);
199     if let Some(
200         rl::Region::EarlyBound(node_id)
201         | rl::Region::LateBound(_, _, node_id)
202         | rl::Region::Free(_, node_id),
203     ) = def
204     {
205         if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
206             return lt;
207         }
208     }
209     Lifetime(lifetime.ident.name)
210 }
211
212 pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant {
213     let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id();
214     Constant {
215         type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
216         kind: ConstantKind::Anonymous { body: constant.value.body },
217     }
218 }
219
220 pub(crate) fn clean_middle_const<'tcx>(
221     constant: ty::Const<'tcx>,
222     cx: &mut DocContext<'tcx>,
223 ) -> Constant {
224     // FIXME: instead of storing the stringified expression, store `self` directly instead.
225     Constant {
226         type_: clean_middle_ty(constant.ty(), cx, None),
227         kind: ConstantKind::TyConst { expr: constant.to_string().into() },
228     }
229 }
230
231 pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Lifetime> {
232     match *region {
233         ty::ReStatic => Some(Lifetime::statik()),
234         _ if !region.has_name() => None,
235         ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
236             Some(Lifetime(name))
237         }
238         ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
239         ty::ReLateBound(..)
240         | ty::ReFree(..)
241         | ty::ReVar(..)
242         | ty::RePlaceholder(..)
243         | ty::ReErased => {
244             debug!("cannot clean region {:?}", region);
245             None
246         }
247     }
248 }
249
250 fn clean_where_predicate<'tcx>(
251     predicate: &hir::WherePredicate<'tcx>,
252     cx: &mut DocContext<'tcx>,
253 ) -> Option<WherePredicate> {
254     if !predicate.in_where_clause() {
255         return None;
256     }
257     Some(match *predicate {
258         hir::WherePredicate::BoundPredicate(ref wbp) => {
259             let bound_params = wbp
260                 .bound_generic_params
261                 .iter()
262                 .map(|param| {
263                     // Higher-ranked params must be lifetimes.
264                     // Higher-ranked lifetimes can't have bounds.
265                     assert_matches!(
266                         param,
267                         hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
268                     );
269                     Lifetime(param.name.ident().name)
270                 })
271                 .collect();
272             WherePredicate::BoundPredicate {
273                 ty: clean_ty(wbp.bounded_ty, cx),
274                 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
275                 bound_params,
276             }
277         }
278
279         hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
280             lifetime: clean_lifetime(wrp.lifetime, cx),
281             bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
282         },
283
284         hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
285             lhs: Box::new(clean_ty(wrp.lhs_ty, cx)),
286             rhs: Box::new(clean_ty(wrp.rhs_ty, cx).into()),
287             bound_params: Vec::new(),
288         },
289     })
290 }
291
292 pub(crate) fn clean_predicate<'tcx>(
293     predicate: ty::Predicate<'tcx>,
294     cx: &mut DocContext<'tcx>,
295 ) -> Option<WherePredicate> {
296     let bound_predicate = predicate.kind();
297     match bound_predicate.skip_binder() {
298         ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
299             clean_poly_trait_predicate(bound_predicate.rebind(pred), cx)
300         }
301         ty::PredicateKind::Clause(ty::Clause::RegionOutlives(pred)) => {
302             clean_region_outlives_predicate(pred)
303         }
304         ty::PredicateKind::Clause(ty::Clause::TypeOutlives(pred)) => {
305             clean_type_outlives_predicate(pred, cx)
306         }
307         ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
308             Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
309         }
310         ty::PredicateKind::ConstEvaluatable(..) => None,
311         ty::PredicateKind::WellFormed(..) => None,
312
313         ty::PredicateKind::Subtype(..)
314         | ty::PredicateKind::Coerce(..)
315         | ty::PredicateKind::ObjectSafe(..)
316         | ty::PredicateKind::ClosureKind(..)
317         | ty::PredicateKind::ConstEquate(..)
318         | ty::PredicateKind::Ambiguous
319         | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
320     }
321 }
322
323 fn clean_poly_trait_predicate<'tcx>(
324     pred: ty::PolyTraitPredicate<'tcx>,
325     cx: &mut DocContext<'tcx>,
326 ) -> Option<WherePredicate> {
327     // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
328     if pred.skip_binder().constness == ty::BoundConstness::ConstIfConst
329         && Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
330     {
331         return None;
332     }
333
334     let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
335     Some(WherePredicate::BoundPredicate {
336         ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None),
337         bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, ThinVec::new())],
338         bound_params: Vec::new(),
339     })
340 }
341
342 fn clean_region_outlives_predicate<'tcx>(
343     pred: ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>,
344 ) -> Option<WherePredicate> {
345     let ty::OutlivesPredicate(a, b) = pred;
346
347     Some(WherePredicate::RegionPredicate {
348         lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
349         bounds: vec![GenericBound::Outlives(
350             clean_middle_region(b).expect("failed to clean bounds"),
351         )],
352     })
353 }
354
355 fn clean_type_outlives_predicate<'tcx>(
356     pred: ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
357     cx: &mut DocContext<'tcx>,
358 ) -> Option<WherePredicate> {
359     let ty::OutlivesPredicate(ty, lt) = pred;
360
361     Some(WherePredicate::BoundPredicate {
362         ty: clean_middle_ty(ty, cx, None),
363         bounds: vec![GenericBound::Outlives(
364             clean_middle_region(lt).expect("failed to clean lifetimes"),
365         )],
366         bound_params: Vec::new(),
367     })
368 }
369
370 fn clean_middle_term<'tcx>(term: ty::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
371     match term.unpack() {
372         ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(ty, cx, None)),
373         ty::TermKind::Const(c) => Term::Constant(clean_middle_const(c, cx)),
374     }
375 }
376
377 fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
378     match term {
379         hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
380         hir::Term::Const(c) => {
381             let def_id = cx.tcx.hir().local_def_id(c.hir_id);
382             Term::Constant(clean_middle_const(ty::Const::from_anon_const(cx.tcx, def_id), cx))
383         }
384     }
385 }
386
387 fn clean_projection_predicate<'tcx>(
388     pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
389     cx: &mut DocContext<'tcx>,
390 ) -> WherePredicate {
391     let late_bound_regions = cx
392         .tcx
393         .collect_referenced_late_bound_regions(&pred)
394         .into_iter()
395         .filter_map(|br| match br {
396             ty::BrNamed(_, name) if br.is_named() => Some(Lifetime(name)),
397             _ => None,
398         })
399         .collect();
400
401     let ty::ProjectionPredicate { projection_ty, term } = pred.skip_binder();
402
403     WherePredicate::EqPredicate {
404         lhs: Box::new(clean_projection(projection_ty, cx, None)),
405         rhs: Box::new(clean_middle_term(term, cx)),
406         bound_params: late_bound_regions,
407     }
408 }
409
410 fn clean_projection<'tcx>(
411     ty: ty::ProjectionTy<'tcx>,
412     cx: &mut DocContext<'tcx>,
413     def_id: Option<DefId>,
414 ) -> Type {
415     if cx.tcx.def_kind(ty.item_def_id) == DefKind::ImplTraitPlaceholder {
416         let bounds = cx
417             .tcx
418             .explicit_item_bounds(ty.item_def_id)
419             .iter()
420             .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, ty.substs))
421             .collect::<Vec<_>>();
422         return clean_middle_opaque_bounds(cx, bounds);
423     }
424
425     let trait_ = clean_trait_ref_with_bindings(cx, ty.trait_ref(cx.tcx), ThinVec::new());
426     let self_type = clean_middle_ty(ty.self_ty(), cx, None);
427     let self_def_id = if let Some(def_id) = def_id {
428         cx.tcx.opt_parent(def_id).or(Some(def_id))
429     } else {
430         self_type.def_id(&cx.cache)
431     };
432     let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
433     Type::QPath(Box::new(QPathData {
434         assoc: projection_to_path_segment(ty, cx),
435         should_show_cast,
436         self_type,
437         trait_,
438     }))
439 }
440
441 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
442     !trait_.segments.is_empty()
443         && self_def_id
444             .zip(Some(trait_.def_id()))
445             .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
446 }
447
448 fn projection_to_path_segment<'tcx>(
449     ty: ty::ProjectionTy<'tcx>,
450     cx: &mut DocContext<'tcx>,
451 ) -> PathSegment {
452     let item = cx.tcx.associated_item(ty.item_def_id);
453     let generics = cx.tcx.generics_of(ty.item_def_id);
454     PathSegment {
455         name: item.name,
456         args: GenericArgs::AngleBracketed {
457             args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
458             bindings: Default::default(),
459         },
460     }
461 }
462
463 fn clean_generic_param_def<'tcx>(
464     def: &ty::GenericParamDef,
465     cx: &mut DocContext<'tcx>,
466 ) -> GenericParamDef {
467     let (name, kind) = match def.kind {
468         ty::GenericParamDefKind::Lifetime => {
469             (def.name, GenericParamDefKind::Lifetime { outlives: vec![] })
470         }
471         ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
472             let default = if has_default {
473                 Some(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id)))
474             } else {
475                 None
476             };
477             (
478                 def.name,
479                 GenericParamDefKind::Type {
480                     did: def.def_id,
481                     bounds: vec![], // These are filled in from the where-clauses.
482                     default: default.map(Box::new),
483                     synthetic,
484                 },
485             )
486         }
487         ty::GenericParamDefKind::Const { has_default } => (
488             def.name,
489             GenericParamDefKind::Const {
490                 did: def.def_id,
491                 ty: Box::new(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id))),
492                 default: match has_default {
493                     true => Some(Box::new(cx.tcx.const_param_default(def.def_id).to_string())),
494                     false => None,
495                 },
496             },
497         ),
498     };
499
500     GenericParamDef { name, kind }
501 }
502
503 fn clean_generic_param<'tcx>(
504     cx: &mut DocContext<'tcx>,
505     generics: Option<&hir::Generics<'tcx>>,
506     param: &hir::GenericParam<'tcx>,
507 ) -> GenericParamDef {
508     let did = cx.tcx.hir().local_def_id(param.hir_id);
509     let (name, kind) = match param.kind {
510         hir::GenericParamKind::Lifetime { .. } => {
511             let outlives = if let Some(generics) = generics {
512                 generics
513                     .outlives_for_param(did)
514                     .filter(|bp| !bp.in_where_clause)
515                     .flat_map(|bp| bp.bounds)
516                     .map(|bound| match bound {
517                         hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
518                         _ => panic!(),
519                     })
520                     .collect()
521             } else {
522                 Vec::new()
523             };
524             (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
525         }
526         hir::GenericParamKind::Type { ref default, synthetic } => {
527             let bounds = if let Some(generics) = generics {
528                 generics
529                     .bounds_for_param(did)
530                     .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
531                     .flat_map(|bp| bp.bounds)
532                     .filter_map(|x| clean_generic_bound(x, cx))
533                     .collect()
534             } else {
535                 Vec::new()
536             };
537             (
538                 param.name.ident().name,
539                 GenericParamDefKind::Type {
540                     did: did.to_def_id(),
541                     bounds,
542                     default: default.map(|t| clean_ty(t, cx)).map(Box::new),
543                     synthetic,
544                 },
545             )
546         }
547         hir::GenericParamKind::Const { ty, default } => (
548             param.name.ident().name,
549             GenericParamDefKind::Const {
550                 did: did.to_def_id(),
551                 ty: Box::new(clean_ty(ty, cx)),
552                 default: default.map(|ct| {
553                     let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
554                     Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
555                 }),
556             },
557         ),
558     };
559
560     GenericParamDef { name, kind }
561 }
562
563 /// Synthetic type-parameters are inserted after normal ones.
564 /// In order for normal parameters to be able to refer to synthetic ones,
565 /// scans them first.
566 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
567     match param.kind {
568         hir::GenericParamKind::Type { synthetic, .. } => synthetic,
569         _ => false,
570     }
571 }
572
573 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
574 ///
575 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
576 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
577     matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
578 }
579
580 pub(crate) fn clean_generics<'tcx>(
581     gens: &hir::Generics<'tcx>,
582     cx: &mut DocContext<'tcx>,
583 ) -> Generics {
584     let impl_trait_params = gens
585         .params
586         .iter()
587         .filter(|param| is_impl_trait(param))
588         .map(|param| {
589             let param = clean_generic_param(cx, Some(gens), param);
590             match param.kind {
591                 GenericParamDefKind::Lifetime { .. } => unreachable!(),
592                 GenericParamDefKind::Type { did, ref bounds, .. } => {
593                     cx.impl_trait_bounds.insert(did.into(), bounds.clone());
594                 }
595                 GenericParamDefKind::Const { .. } => unreachable!(),
596             }
597             param
598         })
599         .collect::<Vec<_>>();
600
601     let mut bound_predicates = FxIndexMap::default();
602     let mut region_predicates = FxIndexMap::default();
603     let mut eq_predicates = ThinVec::default();
604     for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
605         match pred {
606             WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
607                 match bound_predicates.entry(ty) {
608                     IndexEntry::Vacant(v) => {
609                         v.insert((bounds, bound_params));
610                     }
611                     IndexEntry::Occupied(mut o) => {
612                         // we merge both bounds.
613                         for bound in bounds {
614                             if !o.get().0.contains(&bound) {
615                                 o.get_mut().0.push(bound);
616                             }
617                         }
618                         for bound_param in bound_params {
619                             if !o.get().1.contains(&bound_param) {
620                                 o.get_mut().1.push(bound_param);
621                             }
622                         }
623                     }
624                 }
625             }
626             WherePredicate::RegionPredicate { lifetime, bounds } => {
627                 match region_predicates.entry(lifetime) {
628                     IndexEntry::Vacant(v) => {
629                         v.insert(bounds);
630                     }
631                     IndexEntry::Occupied(mut o) => {
632                         // we merge both bounds.
633                         for bound in bounds {
634                             if !o.get().contains(&bound) {
635                                 o.get_mut().push(bound);
636                             }
637                         }
638                     }
639                 }
640             }
641             WherePredicate::EqPredicate { lhs, rhs, bound_params } => {
642                 eq_predicates.push(WherePredicate::EqPredicate { lhs, rhs, bound_params });
643             }
644         }
645     }
646
647     let mut params = ThinVec::with_capacity(gens.params.len());
648     // In this loop, we gather the generic parameters (`<'a, B: 'a>`) and check if they have
649     // bounds in the where predicates. If so, we move their bounds into the where predicates
650     // while also preventing duplicates.
651     for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
652         let mut p = clean_generic_param(cx, Some(gens), p);
653         match &mut p.kind {
654             GenericParamDefKind::Lifetime { ref mut outlives } => {
655                 if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
656                     // We merge bounds in the `where` clause.
657                     for outlive in outlives.drain(..) {
658                         let outlive = GenericBound::Outlives(outlive);
659                         if !region_pred.contains(&outlive) {
660                             region_pred.push(outlive);
661                         }
662                     }
663                 }
664             }
665             GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
666                 if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
667                     // We merge bounds in the `where` clause.
668                     for bound in bounds.drain(..) {
669                         if !bound_pred.0.contains(&bound) {
670                             bound_pred.0.push(bound);
671                         }
672                     }
673                 }
674             }
675             GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
676                 // nothing to do here.
677             }
678         }
679         params.push(p);
680     }
681     params.extend(impl_trait_params);
682
683     Generics {
684         params,
685         where_predicates: bound_predicates
686             .into_iter()
687             .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
688                 ty,
689                 bounds,
690                 bound_params,
691             })
692             .chain(
693                 region_predicates
694                     .into_iter()
695                     .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
696             )
697             .chain(eq_predicates.into_iter())
698             .collect(),
699     }
700 }
701
702 fn clean_ty_generics<'tcx>(
703     cx: &mut DocContext<'tcx>,
704     gens: &ty::Generics,
705     preds: ty::GenericPredicates<'tcx>,
706 ) -> Generics {
707     // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
708     // since `Clean for ty::Predicate` would consume them.
709     let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
710
711     // Bounds in the type_params and lifetimes fields are repeated in the
712     // predicates field (see rustc_hir_analysis::collect::ty_generics), so remove
713     // them.
714     let stripped_params = gens
715         .params
716         .iter()
717         .filter_map(|param| match param.kind {
718             ty::GenericParamDefKind::Lifetime if param.is_anonymous_lifetime() => None,
719             ty::GenericParamDefKind::Lifetime => Some(clean_generic_param_def(param, cx)),
720             ty::GenericParamDefKind::Type { synthetic, .. } => {
721                 if param.name == kw::SelfUpper {
722                     assert_eq!(param.index, 0);
723                     return None;
724                 }
725                 if synthetic {
726                     impl_trait.insert(param.index.into(), vec![]);
727                     return None;
728                 }
729                 Some(clean_generic_param_def(param, cx))
730             }
731             ty::GenericParamDefKind::Const { .. } => Some(clean_generic_param_def(param, cx)),
732         })
733         .collect::<ThinVec<GenericParamDef>>();
734
735     // param index -> [(trait DefId, associated type name & generics, type, higher-ranked params)]
736     let mut impl_trait_proj =
737         FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>, Vec<GenericParamDef>)>>::default();
738
739     let where_predicates = preds
740         .predicates
741         .iter()
742         .flat_map(|(p, _)| {
743             let mut projection = None;
744             let param_idx = (|| {
745                 let bound_p = p.kind();
746                 match bound_p.skip_binder() {
747                     ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
748                         if let ty::Param(param) = pred.self_ty().kind() {
749                             return Some(param.index);
750                         }
751                     }
752                     ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
753                         ty,
754                         _reg,
755                     ))) => {
756                         if let ty::Param(param) = ty.kind() {
757                             return Some(param.index);
758                         }
759                     }
760                     ty::PredicateKind::Clause(ty::Clause::Projection(p)) => {
761                         if let ty::Param(param) = p.projection_ty.self_ty().kind() {
762                             projection = Some(bound_p.rebind(p));
763                             return Some(param.index);
764                         }
765                     }
766                     _ => (),
767                 }
768
769                 None
770             })();
771
772             if let Some(param_idx) = param_idx {
773                 if let Some(b) = impl_trait.get_mut(&param_idx.into()) {
774                     let p: WherePredicate = clean_predicate(*p, cx)?;
775
776                     b.extend(
777                         p.get_bounds()
778                             .into_iter()
779                             .flatten()
780                             .cloned()
781                             .filter(|b| !b.is_sized_bound(cx)),
782                     );
783
784                     let proj = projection.map(|p| {
785                         (
786                             clean_projection(p.skip_binder().projection_ty, cx, None),
787                             p.skip_binder().term,
788                         )
789                     });
790                     if let Some(((_, trait_did, name), rhs)) = proj
791                         .as_ref()
792                         .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
793                     {
794                         // FIXME(...): Remove this unwrap()
795                         impl_trait_proj.entry(param_idx).or_default().push((
796                             trait_did,
797                             name,
798                             rhs.ty().unwrap(),
799                             p.get_bound_params()
800                                 .into_iter()
801                                 .flatten()
802                                 .map(|param| GenericParamDef::lifetime(param.0))
803                                 .collect(),
804                         ));
805                     }
806
807                     return None;
808                 }
809             }
810
811             Some(p)
812         })
813         .collect::<Vec<_>>();
814
815     for (param, mut bounds) in impl_trait {
816         // Move trait bounds to the front.
817         bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
818
819         let crate::core::ImplTraitParam::ParamIndex(idx) = param else { unreachable!() };
820         if let Some(proj) = impl_trait_proj.remove(&idx) {
821             for (trait_did, name, rhs, bound_params) in proj {
822                 let rhs = clean_middle_ty(rhs, cx, None);
823                 simplify::merge_bounds(
824                     cx,
825                     &mut bounds,
826                     bound_params,
827                     trait_did,
828                     name,
829                     &Term::Type(rhs),
830                 );
831             }
832         }
833
834         cx.impl_trait_bounds.insert(param, bounds);
835     }
836
837     // Now that `cx.impl_trait_bounds` is populated, we can process
838     // remaining predicates which could contain `impl Trait`.
839     let mut where_predicates =
840         where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect::<Vec<_>>();
841
842     // In the surface language, all type parameters except `Self` have an
843     // implicit `Sized` bound unless removed with `?Sized`.
844     // However, in the list of where-predicates below, `Sized` appears like a
845     // normal bound: It's either present (the type is sized) or
846     // absent (the type is unsized) but never *maybe* (i.e. `?Sized`).
847     //
848     // This is unsuitable for rendering.
849     // Thus, as a first step remove all `Sized` bounds that should be implicit.
850     //
851     // Note that associated types also have an implicit `Sized` bound but we
852     // don't actually know the set of associated types right here so that's
853     // handled when cleaning associated types.
854     let mut sized_params = FxHashSet::default();
855     where_predicates.retain(|pred| {
856         if let WherePredicate::BoundPredicate { ty: Generic(g), bounds, .. } = pred
857         && *g != kw::SelfUpper
858         && bounds.iter().any(|b| b.is_sized_bound(cx))
859         {
860             sized_params.insert(*g);
861             false
862         } else {
863             true
864         }
865     });
866
867     // As a final step, go through the type parameters again and insert a
868     // `?Sized` bound for each one we didn't find to be `Sized`.
869     for tp in &stripped_params {
870         if let types::GenericParamDefKind::Type { .. } = tp.kind
871         && !sized_params.contains(&tp.name)
872         {
873             where_predicates.push(WherePredicate::BoundPredicate {
874                 ty: Type::Generic(tp.name),
875                 bounds: vec![GenericBound::maybe_sized(cx)],
876                 bound_params: Vec::new(),
877             })
878         }
879     }
880
881     // It would be nice to collect all of the bounds on a type and recombine
882     // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
883     // and instead see `where T: Foo + Bar + Sized + 'a`
884
885     Generics {
886         params: stripped_params,
887         where_predicates: simplify::where_clauses(cx, where_predicates),
888     }
889 }
890
891 fn clean_fn_or_proc_macro<'tcx>(
892     item: &hir::Item<'tcx>,
893     sig: &hir::FnSig<'tcx>,
894     generics: &hir::Generics<'tcx>,
895     body_id: hir::BodyId,
896     name: &mut Symbol,
897     cx: &mut DocContext<'tcx>,
898 ) -> ItemKind {
899     let attrs = cx.tcx.hir().attrs(item.hir_id());
900     let macro_kind = attrs.iter().find_map(|a| {
901         if a.has_name(sym::proc_macro) {
902             Some(MacroKind::Bang)
903         } else if a.has_name(sym::proc_macro_derive) {
904             Some(MacroKind::Derive)
905         } else if a.has_name(sym::proc_macro_attribute) {
906             Some(MacroKind::Attr)
907         } else {
908             None
909         }
910     });
911     match macro_kind {
912         Some(kind) => {
913             if kind == MacroKind::Derive {
914                 *name = attrs
915                     .lists(sym::proc_macro_derive)
916                     .find_map(|mi| mi.ident())
917                     .expect("proc-macro derives require a name")
918                     .name;
919             }
920
921             let mut helpers = Vec::new();
922             for mi in attrs.lists(sym::proc_macro_derive) {
923                 if !mi.has_name(sym::attributes) {
924                     continue;
925                 }
926
927                 if let Some(list) = mi.meta_item_list() {
928                     for inner_mi in list {
929                         if let Some(ident) = inner_mi.ident() {
930                             helpers.push(ident.name);
931                         }
932                     }
933                 }
934             }
935             ProcMacroItem(ProcMacro { kind, helpers })
936         }
937         None => {
938             let mut func = clean_function(cx, sig, generics, FunctionArgs::Body(body_id));
939             clean_fn_decl_legacy_const_generics(&mut func, attrs);
940             FunctionItem(func)
941         }
942     }
943 }
944
945 /// This is needed to make it more "readable" when documenting functions using
946 /// `rustc_legacy_const_generics`. More information in
947 /// <https://github.com/rust-lang/rust/issues/83167>.
948 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
949     for meta_item_list in attrs
950         .iter()
951         .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
952         .filter_map(|a| a.meta_item_list())
953     {
954         for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.lit()).enumerate() {
955             match literal.kind {
956                 ast::LitKind::Int(a, _) => {
957                     let gen = func.generics.params.remove(0);
958                     if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
959                         gen
960                     {
961                         func.decl
962                             .inputs
963                             .values
964                             .insert(a as _, Argument { name, type_: *ty, is_const: true });
965                     } else {
966                         panic!("unexpected non const in position {pos}");
967                     }
968                 }
969                 _ => panic!("invalid arg index"),
970             }
971         }
972     }
973 }
974
975 enum FunctionArgs<'tcx> {
976     Body(hir::BodyId),
977     Names(&'tcx [Ident]),
978 }
979
980 fn clean_function<'tcx>(
981     cx: &mut DocContext<'tcx>,
982     sig: &hir::FnSig<'tcx>,
983     generics: &hir::Generics<'tcx>,
984     args: FunctionArgs<'tcx>,
985 ) -> Box<Function> {
986     let (generics, decl) = enter_impl_trait(cx, |cx| {
987         // NOTE: generics must be cleaned before args
988         let generics = clean_generics(generics, cx);
989         let args = match args {
990             FunctionArgs::Body(body_id) => {
991                 clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id)
992             }
993             FunctionArgs::Names(names) => {
994                 clean_args_from_types_and_names(cx, sig.decl.inputs, names)
995             }
996         };
997         let mut decl = clean_fn_decl_with_args(cx, sig.decl, args);
998         if sig.header.is_async() {
999             decl.output = decl.sugared_async_return_type();
1000         }
1001         (generics, decl)
1002     });
1003     Box::new(Function { decl, generics })
1004 }
1005
1006 fn clean_args_from_types_and_names<'tcx>(
1007     cx: &mut DocContext<'tcx>,
1008     types: &[hir::Ty<'tcx>],
1009     names: &[Ident],
1010 ) -> Arguments {
1011     Arguments {
1012         values: types
1013             .iter()
1014             .enumerate()
1015             .map(|(i, ty)| Argument {
1016                 type_: clean_ty(ty, cx),
1017                 name: names
1018                     .get(i)
1019                     .map(|ident| ident.name)
1020                     .filter(|ident| !ident.is_empty())
1021                     .unwrap_or(kw::Underscore),
1022                 is_const: false,
1023             })
1024             .collect(),
1025     }
1026 }
1027
1028 fn clean_args_from_types_and_body_id<'tcx>(
1029     cx: &mut DocContext<'tcx>,
1030     types: &[hir::Ty<'tcx>],
1031     body_id: hir::BodyId,
1032 ) -> Arguments {
1033     let body = cx.tcx.hir().body(body_id);
1034
1035     Arguments {
1036         values: types
1037             .iter()
1038             .enumerate()
1039             .map(|(i, ty)| Argument {
1040                 name: name_from_pat(body.params[i].pat),
1041                 type_: clean_ty(ty, cx),
1042                 is_const: false,
1043             })
1044             .collect(),
1045     }
1046 }
1047
1048 fn clean_fn_decl_with_args<'tcx>(
1049     cx: &mut DocContext<'tcx>,
1050     decl: &hir::FnDecl<'tcx>,
1051     args: Arguments,
1052 ) -> FnDecl {
1053     let output = match decl.output {
1054         hir::FnRetTy::Return(typ) => Return(clean_ty(typ, cx)),
1055         hir::FnRetTy::DefaultReturn(..) => DefaultReturn,
1056     };
1057     FnDecl { inputs: args, output, c_variadic: decl.c_variadic }
1058 }
1059
1060 fn clean_fn_decl_from_did_and_sig<'tcx>(
1061     cx: &mut DocContext<'tcx>,
1062     did: Option<DefId>,
1063     sig: ty::PolyFnSig<'tcx>,
1064 ) -> FnDecl {
1065     let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
1066
1067     // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
1068     // but shouldn't change any code meaning.
1069     let output = match clean_middle_ty(sig.skip_binder().output(), cx, None) {
1070         Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
1071         ty => Return(ty),
1072     };
1073
1074     FnDecl {
1075         output,
1076         c_variadic: sig.skip_binder().c_variadic,
1077         inputs: Arguments {
1078             values: sig
1079                 .skip_binder()
1080                 .inputs()
1081                 .iter()
1082                 .map(|t| Argument {
1083                     type_: clean_middle_ty(*t, cx, None),
1084                     name: names
1085                         .next()
1086                         .map(|i| i.name)
1087                         .filter(|i| !i.is_empty())
1088                         .unwrap_or(kw::Underscore),
1089                     is_const: false,
1090                 })
1091                 .collect(),
1092         },
1093     }
1094 }
1095
1096 fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1097     let path = clean_path(trait_ref.path, cx);
1098     register_res(cx, path.res);
1099     path
1100 }
1101
1102 fn clean_poly_trait_ref<'tcx>(
1103     poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1104     cx: &mut DocContext<'tcx>,
1105 ) -> PolyTrait {
1106     PolyTrait {
1107         trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1108         generic_params: poly_trait_ref
1109             .bound_generic_params
1110             .iter()
1111             .filter(|p| !is_elided_lifetime(p))
1112             .map(|x| clean_generic_param(cx, None, x))
1113             .collect(),
1114     }
1115 }
1116
1117 fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1118     let local_did = trait_item.owner_id.to_def_id();
1119     cx.with_param_env(local_did, |cx| {
1120         let inner = match trait_item.kind {
1121             hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1122                 clean_ty(ty, cx),
1123                 ConstantKind::Local { def_id: local_did, body: default },
1124             ),
1125             hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(clean_ty(ty, cx)),
1126             hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1127                 let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Body(body));
1128                 MethodItem(m, None)
1129             }
1130             hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1131                 let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Names(names));
1132                 TyMethodItem(m)
1133             }
1134             hir::TraitItemKind::Type(bounds, Some(default)) => {
1135                 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1136                 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1137                 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, default), cx, None);
1138                 AssocTypeItem(
1139                     Box::new(Typedef {
1140                         type_: clean_ty(default, cx),
1141                         generics,
1142                         item_type: Some(item_type),
1143                     }),
1144                     bounds,
1145                 )
1146             }
1147             hir::TraitItemKind::Type(bounds, None) => {
1148                 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1149                 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1150                 TyAssocTypeItem(generics, bounds)
1151             }
1152         };
1153         Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx)
1154     })
1155 }
1156
1157 pub(crate) fn clean_impl_item<'tcx>(
1158     impl_: &hir::ImplItem<'tcx>,
1159     cx: &mut DocContext<'tcx>,
1160 ) -> Item {
1161     let local_did = impl_.owner_id.to_def_id();
1162     cx.with_param_env(local_did, |cx| {
1163         let inner = match impl_.kind {
1164             hir::ImplItemKind::Const(ty, expr) => {
1165                 let default = ConstantKind::Local { def_id: local_did, body: expr };
1166                 AssocConstItem(clean_ty(ty, cx), default)
1167             }
1168             hir::ImplItemKind::Fn(ref sig, body) => {
1169                 let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body));
1170                 let defaultness = cx.tcx.impl_defaultness(impl_.owner_id);
1171                 MethodItem(m, Some(defaultness))
1172             }
1173             hir::ImplItemKind::Type(hir_ty) => {
1174                 let type_ = clean_ty(hir_ty, cx);
1175                 let generics = clean_generics(impl_.generics, cx);
1176                 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1177                 AssocTypeItem(
1178                     Box::new(Typedef { type_, generics, item_type: Some(item_type) }),
1179                     Vec::new(),
1180                 )
1181             }
1182         };
1183
1184         Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1185     })
1186 }
1187
1188 pub(crate) fn clean_middle_assoc_item<'tcx>(
1189     assoc_item: &ty::AssocItem,
1190     cx: &mut DocContext<'tcx>,
1191 ) -> Item {
1192     let tcx = cx.tcx;
1193     let kind = match assoc_item.kind {
1194         ty::AssocKind::Const => {
1195             let ty = clean_middle_ty(tcx.type_of(assoc_item.def_id), cx, Some(assoc_item.def_id));
1196
1197             let provided = match assoc_item.container {
1198                 ty::ImplContainer => true,
1199                 ty::TraitContainer => tcx.impl_defaultness(assoc_item.def_id).has_value(),
1200             };
1201             if provided {
1202                 AssocConstItem(ty, ConstantKind::Extern { def_id: assoc_item.def_id })
1203             } else {
1204                 TyAssocConstItem(ty)
1205             }
1206         }
1207         ty::AssocKind::Fn => {
1208             let sig = tcx.fn_sig(assoc_item.def_id);
1209
1210             let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var {
1211                 ty::BoundVariableKind::Region(ty::BrNamed(_, name))
1212                     if name != kw::UnderscoreLifetime =>
1213                 {
1214                     Some(GenericParamDef::lifetime(name))
1215                 }
1216                 _ => None,
1217             });
1218
1219             let mut generics = clean_ty_generics(
1220                 cx,
1221                 tcx.generics_of(assoc_item.def_id),
1222                 tcx.explicit_predicates_of(assoc_item.def_id),
1223             );
1224             // FIXME: This does not place parameters in source order (late-bound ones come last)
1225             generics.params.extend(late_bound_regions);
1226
1227             let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(assoc_item.def_id), sig);
1228
1229             if assoc_item.fn_has_self_parameter {
1230                 let self_ty = match assoc_item.container {
1231                     ty::ImplContainer => tcx.type_of(assoc_item.container_id(tcx)),
1232                     ty::TraitContainer => tcx.types.self_param,
1233                 };
1234                 let self_arg_ty = sig.input(0).skip_binder();
1235                 if self_arg_ty == self_ty {
1236                     decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1237                 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1238                     if ty == self_ty {
1239                         match decl.inputs.values[0].type_ {
1240                             BorrowedRef { ref mut type_, .. } => **type_ = Generic(kw::SelfUpper),
1241                             _ => unreachable!(),
1242                         }
1243                     }
1244                 }
1245             }
1246
1247             let provided = match assoc_item.container {
1248                 ty::ImplContainer => true,
1249                 ty::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1250             };
1251             if provided {
1252                 let defaultness = match assoc_item.container {
1253                     ty::ImplContainer => Some(assoc_item.defaultness(tcx)),
1254                     ty::TraitContainer => None,
1255                 };
1256                 MethodItem(Box::new(Function { generics, decl }), defaultness)
1257             } else {
1258                 TyMethodItem(Box::new(Function { generics, decl }))
1259             }
1260         }
1261         ty::AssocKind::Type => {
1262             let my_name = assoc_item.name;
1263
1264             fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1265                 match (&param.kind, arg) {
1266                     (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1267                         if *ty == param.name =>
1268                     {
1269                         true
1270                     }
1271                     (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1272                         if *lt == param.name =>
1273                     {
1274                         true
1275                     }
1276                     (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &c.kind {
1277                         ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1278                         _ => false,
1279                     },
1280                     _ => false,
1281                 }
1282             }
1283
1284             if let ty::TraitContainer = assoc_item.container {
1285                 let bounds = tcx.explicit_item_bounds(assoc_item.def_id);
1286                 let predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1287                 let predicates =
1288                     tcx.arena.alloc_from_iter(bounds.into_iter().chain(predicates).copied());
1289                 let mut generics = clean_ty_generics(
1290                     cx,
1291                     tcx.generics_of(assoc_item.def_id),
1292                     ty::GenericPredicates { parent: None, predicates },
1293                 );
1294                 // Filter out the bounds that are (likely?) directly attached to the associated type,
1295                 // as opposed to being located in the where clause.
1296                 let mut bounds: Vec<GenericBound> = Vec::new();
1297                 generics.where_predicates.retain_mut(|pred| match *pred {
1298                     WherePredicate::BoundPredicate {
1299                         ty: QPath(box QPathData { ref assoc, ref self_type, ref trait_, .. }),
1300                         bounds: ref mut pred_bounds,
1301                         ..
1302                     } => {
1303                         if assoc.name != my_name {
1304                             return true;
1305                         }
1306                         if trait_.def_id() != assoc_item.container_id(tcx) {
1307                             return true;
1308                         }
1309                         match *self_type {
1310                             Generic(ref s) if *s == kw::SelfUpper => {}
1311                             _ => return true,
1312                         }
1313                         match &assoc.args {
1314                             GenericArgs::AngleBracketed { args, bindings } => {
1315                                 if !bindings.is_empty()
1316                                     || generics
1317                                         .params
1318                                         .iter()
1319                                         .zip(args.iter())
1320                                         .any(|(param, arg)| !param_eq_arg(param, arg))
1321                                 {
1322                                     return true;
1323                                 }
1324                             }
1325                             GenericArgs::Parenthesized { .. } => {
1326                                 // The only time this happens is if we're inside the rustdoc for Fn(),
1327                                 // which only has one associated type, which is not a GAT, so whatever.
1328                             }
1329                         }
1330                         bounds.extend(mem::replace(pred_bounds, Vec::new()));
1331                         false
1332                     }
1333                     _ => true,
1334                 });
1335                 // Our Sized/?Sized bound didn't get handled when creating the generics
1336                 // because we didn't actually get our whole set of bounds until just now
1337                 // (some of them may have come from the trait). If we do have a sized
1338                 // bound, we remove it, and if we don't then we add the `?Sized` bound
1339                 // at the end.
1340                 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1341                     Some(i) => {
1342                         bounds.remove(i);
1343                     }
1344                     None => bounds.push(GenericBound::maybe_sized(cx)),
1345                 }
1346                 // Move bounds that are (likely) directly attached to the parameters of the
1347                 // (generic) associated type from the where clause to the respective parameter.
1348                 // There is no guarantee that this is what the user actually wrote but we have
1349                 // no way of knowing.
1350                 let mut where_predicates = ThinVec::new();
1351                 for mut pred in generics.where_predicates {
1352                     if let WherePredicate::BoundPredicate { ty: Generic(arg), bounds, .. } = &mut pred
1353                     && let Some(GenericParamDef {
1354                         kind: GenericParamDefKind::Type { bounds: param_bounds, .. },
1355                         ..
1356                     }) = generics.params.iter_mut().find(|param| &param.name == arg)
1357                     {
1358                         param_bounds.append(bounds);
1359                     } else if let WherePredicate::RegionPredicate { lifetime: Lifetime(arg), bounds } = &mut pred
1360                     && let Some(GenericParamDef {
1361                         kind: GenericParamDefKind::Lifetime { outlives: param_bounds },
1362                         ..
1363                     }) = generics.params.iter_mut().find(|param| &param.name == arg) {
1364                         param_bounds.extend(bounds.drain(..).map(|bound| match bound {
1365                             GenericBound::Outlives(lifetime) => lifetime,
1366                             _ => unreachable!(),
1367                         }));
1368                     } else {
1369                         where_predicates.push(pred);
1370                     }
1371                 }
1372                 generics.where_predicates = where_predicates;
1373
1374                 if tcx.impl_defaultness(assoc_item.def_id).has_value() {
1375                     AssocTypeItem(
1376                         Box::new(Typedef {
1377                             type_: clean_middle_ty(
1378                                 tcx.type_of(assoc_item.def_id),
1379                                 cx,
1380                                 Some(assoc_item.def_id),
1381                             ),
1382                             generics,
1383                             // FIXME: should we obtain the Type from HIR and pass it on here?
1384                             item_type: None,
1385                         }),
1386                         bounds,
1387                     )
1388                 } else {
1389                     TyAssocTypeItem(generics, bounds)
1390                 }
1391             } else {
1392                 // FIXME: when could this happen? Associated items in inherent impls?
1393                 AssocTypeItem(
1394                     Box::new(Typedef {
1395                         type_: clean_middle_ty(
1396                             tcx.type_of(assoc_item.def_id),
1397                             cx,
1398                             Some(assoc_item.def_id),
1399                         ),
1400                         generics: Generics {
1401                             params: ThinVec::new(),
1402                             where_predicates: ThinVec::new(),
1403                         },
1404                         item_type: None,
1405                     }),
1406                     Vec::new(),
1407                 )
1408             }
1409         }
1410     };
1411
1412     Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name), kind, cx)
1413 }
1414
1415 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1416     let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1417     let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1418
1419     match qpath {
1420         hir::QPath::Resolved(None, path) => {
1421             if let Res::Def(DefKind::TyParam, did) = path.res {
1422                 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1423                     return new_ty;
1424                 }
1425                 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1426                     return ImplTrait(bounds);
1427                 }
1428             }
1429
1430             if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1431                 expanded
1432             } else {
1433                 let path = clean_path(path, cx);
1434                 resolve_type(cx, path)
1435             }
1436         }
1437         hir::QPath::Resolved(Some(qself), p) => {
1438             // Try to normalize `<X as Y>::T` to a type
1439             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1440             if let Some(normalized_value) = normalize(cx, ty) {
1441                 return clean_middle_ty(normalized_value, cx, None);
1442             }
1443
1444             let trait_segments = &p.segments[..p.segments.len() - 1];
1445             let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1446             let trait_ = self::Path {
1447                 res: Res::Def(DefKind::Trait, trait_def),
1448                 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1449             };
1450             register_res(cx, trait_.res);
1451             let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1452             let self_type = clean_ty(qself, cx);
1453             let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1454             Type::QPath(Box::new(QPathData {
1455                 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1456                 should_show_cast,
1457                 self_type,
1458                 trait_,
1459             }))
1460         }
1461         hir::QPath::TypeRelative(qself, segment) => {
1462             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1463             let res = match ty.kind() {
1464                 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1465                 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1466                 ty::Error(_) => return Type::Infer,
1467                 // Otherwise, this is an inherent associated type.
1468                 _ => return clean_middle_ty(ty, cx, None),
1469             };
1470             let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1471             register_res(cx, trait_.res);
1472             let self_def_id = res.opt_def_id();
1473             let self_type = clean_ty(qself, cx);
1474             let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1475             Type::QPath(Box::new(QPathData {
1476                 assoc: clean_path_segment(segment, cx),
1477                 should_show_cast,
1478                 self_type,
1479                 trait_,
1480             }))
1481         }
1482         hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1483     }
1484 }
1485
1486 fn maybe_expand_private_type_alias<'tcx>(
1487     cx: &mut DocContext<'tcx>,
1488     path: &hir::Path<'tcx>,
1489 ) -> Option<Type> {
1490     let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1491     // Substitute private type aliases
1492     let def_id = def_id.as_local()?;
1493     let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id()) {
1494         &cx.tcx.hir().expect_item(def_id).kind
1495     } else {
1496         return None;
1497     };
1498     let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1499
1500     let provided_params = &path.segments.last().expect("segments were empty");
1501     let mut substs = FxHashMap::default();
1502     let generic_args = provided_params.args();
1503
1504     let mut indices: hir::GenericParamCount = Default::default();
1505     for param in generics.params.iter() {
1506         match param.kind {
1507             hir::GenericParamKind::Lifetime { .. } => {
1508                 let mut j = 0;
1509                 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1510                     hir::GenericArg::Lifetime(lt) => {
1511                         if indices.lifetimes == j {
1512                             return Some(lt);
1513                         }
1514                         j += 1;
1515                         None
1516                     }
1517                     _ => None,
1518                 });
1519                 if let Some(lt) = lifetime {
1520                     let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1521                     let cleaned = if !lt.is_anonymous() {
1522                         clean_lifetime(lt, cx)
1523                     } else {
1524                         Lifetime::elided()
1525                     };
1526                     substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1527                 }
1528                 indices.lifetimes += 1;
1529             }
1530             hir::GenericParamKind::Type { ref default, .. } => {
1531                 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1532                 let mut j = 0;
1533                 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1534                     hir::GenericArg::Type(ty) => {
1535                         if indices.types == j {
1536                             return Some(ty);
1537                         }
1538                         j += 1;
1539                         None
1540                     }
1541                     _ => None,
1542                 });
1543                 if let Some(ty) = type_ {
1544                     substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx)));
1545                 } else if let Some(default) = *default {
1546                     substs.insert(
1547                         ty_param_def_id.to_def_id(),
1548                         SubstParam::Type(clean_ty(default, cx)),
1549                     );
1550                 }
1551                 indices.types += 1;
1552             }
1553             hir::GenericParamKind::Const { .. } => {
1554                 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1555                 let mut j = 0;
1556                 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1557                     hir::GenericArg::Const(ct) => {
1558                         if indices.consts == j {
1559                             return Some(ct);
1560                         }
1561                         j += 1;
1562                         None
1563                     }
1564                     _ => None,
1565                 });
1566                 if let Some(ct) = const_ {
1567                     substs.insert(
1568                         const_param_def_id.to_def_id(),
1569                         SubstParam::Constant(clean_const(ct, cx)),
1570                     );
1571                 }
1572                 // FIXME(const_generics_defaults)
1573                 indices.consts += 1;
1574             }
1575         }
1576     }
1577
1578     Some(cx.enter_alias(substs, |cx| clean_ty(ty, cx)))
1579 }
1580
1581 pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1582     use rustc_hir::*;
1583
1584     match ty.kind {
1585         TyKind::Never => Primitive(PrimitiveType::Never),
1586         TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1587         TyKind::Rptr(ref l, ref m) => {
1588             let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(*l, cx)) };
1589             BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1590         }
1591         TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1592         TyKind::Array(ty, ref length) => {
1593             let length = match length {
1594                 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1595                 hir::ArrayLen::Body(anon_const) => {
1596                     let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1597                     // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1598                     // as we currently do not supply the parent generics to anonymous constants
1599                     // but do allow `ConstKind::Param`.
1600                     //
1601                     // `const_eval_poly` tries to first substitute generic parameters which
1602                     // results in an ICE while manually constructing the constant and using `eval`
1603                     // does nothing for `ConstKind::Param`.
1604                     let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1605                     let param_env = cx.tcx.param_env(def_id);
1606                     print_const(cx, ct.eval(cx.tcx, param_env))
1607                 }
1608             };
1609
1610             Array(Box::new(clean_ty(ty, cx)), length.into())
1611         }
1612         TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1613         TyKind::OpaqueDef(item_id, _, _) => {
1614             let item = cx.tcx.hir().item(item_id);
1615             if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1616                 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1617             } else {
1618                 unreachable!()
1619             }
1620         }
1621         TyKind::Path(_) => clean_qpath(ty, cx),
1622         TyKind::TraitObject(bounds, ref lifetime, _) => {
1623             let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1624             let lifetime =
1625                 if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None };
1626             DynTrait(bounds, lifetime)
1627         }
1628         TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1629         // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1630         TyKind::Infer | TyKind::Err | TyKind::Typeof(..) => Infer,
1631     }
1632 }
1633
1634 /// Returns `None` if the type could not be normalized
1635 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1636     // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1637     if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1638         return None;
1639     }
1640
1641     use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1642     use crate::rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1643     use rustc_middle::traits::ObligationCause;
1644
1645     // Try to normalize `<X as Y>::T` to a type
1646     let infcx = cx.tcx.infer_ctxt().build();
1647     let normalized = infcx
1648         .at(&ObligationCause::dummy(), cx.param_env)
1649         .query_normalize(ty)
1650         .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1651     match normalized {
1652         Ok(normalized_value) => {
1653             debug!("normalized {:?} to {:?}", ty, normalized_value);
1654             Some(normalized_value)
1655         }
1656         Err(err) => {
1657             debug!("failed to normalize {:?}: {:?}", ty, err);
1658             None
1659         }
1660     }
1661 }
1662
1663 pub(crate) fn clean_middle_ty<'tcx>(
1664     ty: Ty<'tcx>,
1665     cx: &mut DocContext<'tcx>,
1666     def_id: Option<DefId>,
1667 ) -> Type {
1668     trace!("cleaning type: {:?}", ty);
1669     let ty = normalize(cx, ty).unwrap_or(ty);
1670     match *ty.kind() {
1671         ty::Never => Primitive(PrimitiveType::Never),
1672         ty::Bool => Primitive(PrimitiveType::Bool),
1673         ty::Char => Primitive(PrimitiveType::Char),
1674         ty::Int(int_ty) => Primitive(int_ty.into()),
1675         ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1676         ty::Float(float_ty) => Primitive(float_ty.into()),
1677         ty::Str => Primitive(PrimitiveType::Str),
1678         ty::Slice(ty) => Slice(Box::new(clean_middle_ty(ty, cx, None))),
1679         ty::Array(ty, mut n) => {
1680             n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1681             let n = print_const(cx, n);
1682             Array(Box::new(clean_middle_ty(ty, cx, None)), n.into())
1683         }
1684         ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(clean_middle_ty(mt.ty, cx, None))),
1685         ty::Ref(r, ty, mutbl) => BorrowedRef {
1686             lifetime: clean_middle_region(r),
1687             mutability: mutbl,
1688             type_: Box::new(clean_middle_ty(ty, cx, None)),
1689         },
1690         ty::FnDef(..) | ty::FnPtr(_) => {
1691             let sig = ty.fn_sig(cx.tcx);
1692             let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1693             BareFunction(Box::new(BareFunctionDecl {
1694                 unsafety: sig.unsafety(),
1695                 generic_params: Vec::new(),
1696                 decl,
1697                 abi: sig.abi(),
1698             }))
1699         }
1700         ty::Adt(def, substs) => {
1701             let did = def.did();
1702             let kind = match def.adt_kind() {
1703                 AdtKind::Struct => ItemType::Struct,
1704                 AdtKind::Union => ItemType::Union,
1705                 AdtKind::Enum => ItemType::Enum,
1706             };
1707             inline::record_extern_fqn(cx, did, kind);
1708             let path = external_path(cx, did, false, ThinVec::new(), substs);
1709             Type::Path { path }
1710         }
1711         ty::Foreign(did) => {
1712             inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1713             let path = external_path(cx, did, false, ThinVec::new(), InternalSubsts::empty());
1714             Type::Path { path }
1715         }
1716         ty::Dynamic(obj, ref reg, _) => {
1717             // HACK: pick the first `did` as the `did` of the trait object. Someone
1718             // might want to implement "native" support for marker-trait-only
1719             // trait objects.
1720             let mut dids = obj.auto_traits();
1721             let did = obj
1722                 .principal_def_id()
1723                 .or_else(|| dids.next())
1724                 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", ty));
1725             let substs = match obj.principal() {
1726                 Some(principal) => principal.skip_binder().substs,
1727                 // marker traits have no substs.
1728                 _ => cx.tcx.intern_substs(&[]),
1729             };
1730
1731             inline::record_extern_fqn(cx, did, ItemType::Trait);
1732
1733             // FIXME(fmease): Hide the trait-object lifetime bound if it coincides with its default
1734             // to partially address #44306. Follow the rules outlined at
1735             // https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes
1736             let lifetime = clean_middle_region(*reg);
1737             let mut bounds = dids
1738                 .map(|did| {
1739                     let empty = cx.tcx.intern_substs(&[]);
1740                     let path = external_path(cx, did, false, ThinVec::new(), empty);
1741                     inline::record_extern_fqn(cx, did, ItemType::Trait);
1742                     PolyTrait { trait_: path, generic_params: Vec::new() }
1743                 })
1744                 .collect::<Vec<_>>();
1745
1746             let bindings = obj
1747                 .projection_bounds()
1748                 .map(|pb| TypeBinding {
1749                     assoc: projection_to_path_segment(
1750                         pb.skip_binder()
1751                             // HACK(compiler-errors): Doesn't actually matter what self
1752                             // type we put here, because we're only using the GAT's substs.
1753                             .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1754                             .projection_ty,
1755                         cx,
1756                     ),
1757                     kind: TypeBindingKind::Equality {
1758                         term: clean_middle_term(pb.skip_binder().term, cx),
1759                     },
1760                 })
1761                 .collect();
1762
1763             let late_bound_regions: FxIndexSet<_> = obj
1764                 .iter()
1765                 .flat_map(|pb| pb.bound_vars())
1766                 .filter_map(|br| match br {
1767                     ty::BoundVariableKind::Region(ty::BrNamed(_, name))
1768                         if name != kw::UnderscoreLifetime =>
1769                     {
1770                         Some(GenericParamDef::lifetime(name))
1771                     }
1772                     _ => None,
1773                 })
1774                 .collect();
1775             let late_bound_regions = late_bound_regions.into_iter().collect();
1776
1777             let path = external_path(cx, did, false, bindings, substs);
1778             bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
1779
1780             DynTrait(bounds, lifetime)
1781         }
1782         ty::Tuple(t) => Tuple(t.iter().map(|t| clean_middle_ty(t, cx, None)).collect()),
1783
1784         ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1785
1786         ty::Param(ref p) => {
1787             if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1788                 ImplTrait(bounds)
1789             } else {
1790                 Generic(p.name)
1791             }
1792         }
1793
1794         ty::Opaque(def_id, substs) => {
1795             // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1796             // by looking up the bounds associated with the def_id.
1797             let bounds = cx
1798                 .tcx
1799                 .explicit_item_bounds(def_id)
1800                 .iter()
1801                 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1802                 .collect::<Vec<_>>();
1803             clean_middle_opaque_bounds(cx, bounds)
1804         }
1805
1806         ty::Closure(..) => panic!("Closure"),
1807         ty::Generator(..) => panic!("Generator"),
1808         ty::Bound(..) => panic!("Bound"),
1809         ty::Placeholder(..) => panic!("Placeholder"),
1810         ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1811         ty::Infer(..) => panic!("Infer"),
1812         ty::Error(_) => panic!("Error"),
1813     }
1814 }
1815
1816 fn clean_middle_opaque_bounds<'tcx>(
1817     cx: &mut DocContext<'tcx>,
1818     bounds: Vec<ty::Predicate<'tcx>>,
1819 ) -> Type {
1820     let mut regions = vec![];
1821     let mut has_sized = false;
1822     let mut bounds = bounds
1823         .iter()
1824         .filter_map(|bound| {
1825             let bound_predicate = bound.kind();
1826             let trait_ref = match bound_predicate.skip_binder() {
1827                 ty::PredicateKind::Clause(ty::Clause::Trait(tr)) => {
1828                     bound_predicate.rebind(tr.trait_ref)
1829                 }
1830                 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
1831                     _ty,
1832                     reg,
1833                 ))) => {
1834                     if let Some(r) = clean_middle_region(reg) {
1835                         regions.push(GenericBound::Outlives(r));
1836                     }
1837                     return None;
1838                 }
1839                 _ => return None,
1840             };
1841
1842             if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1843                 if trait_ref.def_id() == sized {
1844                     has_sized = true;
1845                     return None;
1846                 }
1847             }
1848
1849             let bindings: ThinVec<_> = bounds
1850                 .iter()
1851                 .filter_map(|bound| {
1852                     if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) =
1853                         bound.kind().skip_binder()
1854                     {
1855                         if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1856                             Some(TypeBinding {
1857                                 assoc: projection_to_path_segment(proj.projection_ty, cx),
1858                                 kind: TypeBindingKind::Equality {
1859                                     term: clean_middle_term(proj.term, cx),
1860                                 },
1861                             })
1862                         } else {
1863                             None
1864                         }
1865                     } else {
1866                         None
1867                     }
1868                 })
1869                 .collect();
1870
1871             Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, bindings))
1872         })
1873         .collect::<Vec<_>>();
1874     bounds.extend(regions);
1875     if !has_sized && !bounds.is_empty() {
1876         bounds.insert(0, GenericBound::maybe_sized(cx));
1877     }
1878     ImplTrait(bounds)
1879 }
1880
1881 pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1882     let def_id = cx.tcx.hir().local_def_id(field.hir_id).to_def_id();
1883     clean_field_with_def_id(def_id, field.ident.name, clean_ty(field.ty, cx), cx)
1884 }
1885
1886 pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item {
1887     clean_field_with_def_id(
1888         field.did,
1889         field.name,
1890         clean_middle_ty(cx.tcx.type_of(field.did), cx, Some(field.did)),
1891         cx,
1892     )
1893 }
1894
1895 pub(crate) fn clean_field_with_def_id(
1896     def_id: DefId,
1897     name: Symbol,
1898     ty: Type,
1899     cx: &mut DocContext<'_>,
1900 ) -> Item {
1901     Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
1902 }
1903
1904 pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
1905     let kind = match variant.ctor_kind() {
1906         Some(CtorKind::Const) => Variant::CLike(match variant.discr {
1907             ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
1908             ty::VariantDiscr::Relative(_) => None,
1909         }),
1910         Some(CtorKind::Fn) => Variant::Tuple(
1911             variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1912         ),
1913         None => Variant::Struct(VariantStruct {
1914             ctor_kind: None,
1915             fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1916         }),
1917     };
1918     Item::from_def_id_and_parts(variant.def_id, Some(variant.name), VariantItem(kind), cx)
1919 }
1920
1921 fn clean_variant_data<'tcx>(
1922     variant: &hir::VariantData<'tcx>,
1923     disr_expr: &Option<hir::AnonConst>,
1924     cx: &mut DocContext<'tcx>,
1925 ) -> Variant {
1926     match variant {
1927         hir::VariantData::Struct(..) => Variant::Struct(VariantStruct {
1928             ctor_kind: None,
1929             fields: variant.fields().iter().map(|x| clean_field(x, cx)).collect(),
1930         }),
1931         hir::VariantData::Tuple(..) => {
1932             Variant::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
1933         }
1934         hir::VariantData::Unit(..) => Variant::CLike(disr_expr.map(|disr| Discriminant {
1935             expr: Some(disr.body),
1936             value: cx.tcx.hir().local_def_id(disr.hir_id).to_def_id(),
1937         })),
1938     }
1939 }
1940
1941 fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1942     Path {
1943         res: path.res,
1944         segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1945     }
1946 }
1947
1948 fn clean_generic_args<'tcx>(
1949     generic_args: &hir::GenericArgs<'tcx>,
1950     cx: &mut DocContext<'tcx>,
1951 ) -> GenericArgs {
1952     if generic_args.parenthesized {
1953         let output = clean_ty(generic_args.bindings[0].ty(), cx);
1954         let output = if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1955         let inputs =
1956             generic_args.inputs().iter().map(|x| clean_ty(x, cx)).collect::<Vec<_>>().into();
1957         GenericArgs::Parenthesized { inputs, output }
1958     } else {
1959         let args = generic_args
1960             .args
1961             .iter()
1962             .map(|arg| match arg {
1963                 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
1964                     GenericArg::Lifetime(clean_lifetime(*lt, cx))
1965                 }
1966                 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1967                 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)),
1968                 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(clean_const(ct, cx))),
1969                 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1970             })
1971             .collect::<Vec<_>>()
1972             .into();
1973         let bindings =
1974             generic_args.bindings.iter().map(|x| clean_type_binding(x, cx)).collect::<ThinVec<_>>();
1975         GenericArgs::AngleBracketed { args, bindings }
1976     }
1977 }
1978
1979 fn clean_path_segment<'tcx>(
1980     path: &hir::PathSegment<'tcx>,
1981     cx: &mut DocContext<'tcx>,
1982 ) -> PathSegment {
1983     PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
1984 }
1985
1986 fn clean_bare_fn_ty<'tcx>(
1987     bare_fn: &hir::BareFnTy<'tcx>,
1988     cx: &mut DocContext<'tcx>,
1989 ) -> BareFunctionDecl {
1990     let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1991         // NOTE: generics must be cleaned before args
1992         let generic_params = bare_fn
1993             .generic_params
1994             .iter()
1995             .filter(|p| !is_elided_lifetime(p))
1996             .map(|x| clean_generic_param(cx, None, x))
1997             .collect();
1998         let args = clean_args_from_types_and_names(cx, bare_fn.decl.inputs, bare_fn.param_names);
1999         let decl = clean_fn_decl_with_args(cx, bare_fn.decl, args);
2000         (generic_params, decl)
2001     });
2002     BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params }
2003 }
2004
2005 /// This visitor is used to go through only the "top level" of a item and not enter any sub
2006 /// item while looking for a given `Ident` which is stored into `item` if found.
2007 struct OneLevelVisitor<'hir> {
2008     map: rustc_middle::hir::map::Map<'hir>,
2009     item: Option<&'hir hir::Item<'hir>>,
2010     looking_for: Ident,
2011     target_hir_id: hir::HirId,
2012 }
2013
2014 impl<'hir> OneLevelVisitor<'hir> {
2015     fn new(map: rustc_middle::hir::map::Map<'hir>, target_hir_id: hir::HirId) -> Self {
2016         Self { map, item: None, looking_for: Ident::empty(), target_hir_id }
2017     }
2018
2019     fn reset(&mut self, looking_for: Ident) {
2020         self.looking_for = looking_for;
2021         self.item = None;
2022     }
2023 }
2024
2025 impl<'hir> hir::intravisit::Visitor<'hir> for OneLevelVisitor<'hir> {
2026     type NestedFilter = rustc_middle::hir::nested_filter::All;
2027
2028     fn nested_visit_map(&mut self) -> Self::Map {
2029         self.map
2030     }
2031
2032     fn visit_item(&mut self, item: &'hir hir::Item<'hir>) {
2033         if self.item.is_none()
2034             && item.ident == self.looking_for
2035             && matches!(item.kind, hir::ItemKind::Use(_, _))
2036             || item.hir_id() == self.target_hir_id
2037         {
2038             self.item = Some(item);
2039         }
2040     }
2041 }
2042
2043 /// Because a `Use` item directly links to the imported item, we need to manually go through each
2044 /// import one by one. To do so, we go to the parent item and look for the `Ident` into it. Then,
2045 /// if we found the "end item" (the imported one), we stop there because we don't need its
2046 /// documentation. Otherwise, we repeat the same operation until we find the "end item".
2047 fn get_all_import_attributes<'hir>(
2048     mut item: &hir::Item<'hir>,
2049     tcx: TyCtxt<'hir>,
2050     target_hir_id: hir::HirId,
2051     attributes: &mut Vec<ast::Attribute>,
2052 ) {
2053     let hir_map = tcx.hir();
2054     let mut visitor = OneLevelVisitor::new(hir_map, target_hir_id);
2055     // If the item is an import and has at least a path with two parts, we go into it.
2056     while let hir::ItemKind::Use(path, _) = item.kind &&
2057         path.segments.len() > 1 &&
2058         let hir::def::Res::Def(_, def_id) = path.segments[path.segments.len() - 2].res
2059     {
2060         if let Some(hir::Node::Item(parent_item)) = hir_map.get_if_local(def_id) {
2061             // We add the attributes from this import into the list.
2062             attributes.extend_from_slice(hir_map.attrs(item.hir_id()));
2063             // We get the `Ident` we will be looking for into `item`.
2064             let looking_for = path.segments[path.segments.len() - 1].ident;
2065             visitor.reset(looking_for);
2066             hir::intravisit::walk_item(&mut visitor, parent_item);
2067             if let Some(i) = visitor.item {
2068                 item = i;
2069             } else {
2070                 break;
2071             }
2072         } else {
2073             break;
2074         }
2075     }
2076 }
2077
2078 fn clean_maybe_renamed_item<'tcx>(
2079     cx: &mut DocContext<'tcx>,
2080     item: &hir::Item<'tcx>,
2081     renamed: Option<Symbol>,
2082     import_id: Option<hir::HirId>,
2083 ) -> Vec<Item> {
2084     use hir::ItemKind;
2085
2086     let def_id = item.owner_id.to_def_id();
2087     let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
2088     cx.with_param_env(def_id, |cx| {
2089         let kind = match item.kind {
2090             ItemKind::Static(ty, mutability, body_id) => {
2091                 StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) })
2092             }
2093             ItemKind::Const(ty, body_id) => ConstantItem(Constant {
2094                 type_: clean_ty(ty, cx),
2095                 kind: ConstantKind::Local { body: body_id, def_id },
2096             }),
2097             ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
2098                 bounds: ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2099                 generics: clean_generics(ty.generics, cx),
2100             }),
2101             ItemKind::TyAlias(hir_ty, generics) => {
2102                 let rustdoc_ty = clean_ty(hir_ty, cx);
2103                 let ty = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
2104                 TypedefItem(Box::new(Typedef {
2105                     type_: rustdoc_ty,
2106                     generics: clean_generics(generics, cx),
2107                     item_type: Some(ty),
2108                 }))
2109             }
2110             ItemKind::Enum(ref def, generics) => EnumItem(Enum {
2111                 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2112                 generics: clean_generics(generics, cx),
2113             }),
2114             ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
2115                 generics: clean_generics(generics, cx),
2116                 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2117             }),
2118             ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
2119                 generics: clean_generics(generics, cx),
2120                 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2121             }),
2122             ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
2123                 ctor_kind: variant_data.ctor_kind(),
2124                 generics: clean_generics(generics, cx),
2125                 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2126             }),
2127             ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
2128             // proc macros can have a name set by attributes
2129             ItemKind::Fn(ref sig, generics, body_id) => {
2130                 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2131             }
2132             ItemKind::Macro(ref macro_def, _) => {
2133                 let ty_vis = cx.tcx.visibility(def_id);
2134                 MacroItem(Macro {
2135                     source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
2136                 })
2137             }
2138             ItemKind::Trait(_, _, generics, bounds, item_ids) => {
2139                 let items = item_ids
2140                     .iter()
2141                     .map(|ti| clean_trait_item(cx.tcx.hir().trait_item(ti.id), cx))
2142                     .collect();
2143
2144                 TraitItem(Box::new(Trait {
2145                     def_id,
2146                     items,
2147                     generics: clean_generics(generics, cx),
2148                     bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2149                 }))
2150             }
2151             ItemKind::ExternCrate(orig_name) => {
2152                 return clean_extern_crate(item, name, orig_name, cx);
2153             }
2154             ItemKind::Use(path, kind) => {
2155                 return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default());
2156             }
2157             _ => unreachable!("not yet converted"),
2158         };
2159
2160         let mut extra_attrs = Vec::new();
2161         if let Some(hir::Node::Item(use_node)) =
2162             import_id.and_then(|hir_id| cx.tcx.hir().find(hir_id))
2163         {
2164             // We get all the various imports' attributes.
2165             get_all_import_attributes(use_node, cx.tcx, item.hir_id(), &mut extra_attrs);
2166         }
2167
2168         if !extra_attrs.is_empty() {
2169             extra_attrs.extend_from_slice(inline::load_attrs(cx, def_id));
2170             let attrs = Attributes::from_ast(&extra_attrs);
2171             let cfg = extra_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg);
2172
2173             vec![Item::from_def_id_and_attrs_and_parts(
2174                 def_id,
2175                 Some(name),
2176                 kind,
2177                 Box::new(attrs),
2178                 cfg,
2179             )]
2180         } else {
2181             vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2182         }
2183     })
2184 }
2185
2186 fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2187     let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2188     Item::from_hir_id_and_parts(variant.hir_id, Some(variant.ident.name), kind, cx)
2189 }
2190
2191 fn clean_impl<'tcx>(
2192     impl_: &hir::Impl<'tcx>,
2193     hir_id: hir::HirId,
2194     cx: &mut DocContext<'tcx>,
2195 ) -> Vec<Item> {
2196     let tcx = cx.tcx;
2197     let mut ret = Vec::new();
2198     let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
2199     let items = impl_
2200         .items
2201         .iter()
2202         .map(|ii| clean_impl_item(tcx.hir().impl_item(ii.id), cx))
2203         .collect::<Vec<_>>();
2204     let def_id = tcx.hir().local_def_id(hir_id);
2205
2206     // If this impl block is an implementation of the Deref trait, then we
2207     // need to try inlining the target's inherent impl blocks as well.
2208     if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2209         build_deref_target_impls(cx, &items, &mut ret);
2210     }
2211
2212     let for_ = clean_ty(impl_.self_ty, cx);
2213     let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2214         DefKind::TyAlias => Some(clean_middle_ty(tcx.type_of(did), cx, Some(did))),
2215         _ => None,
2216     });
2217     let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2218         let kind = ImplItem(Box::new(Impl {
2219             unsafety: impl_.unsafety,
2220             generics: clean_generics(impl_.generics, cx),
2221             trait_,
2222             for_,
2223             items,
2224             polarity: tcx.impl_polarity(def_id),
2225             kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2226                 ImplKind::FakeVaradic
2227             } else {
2228                 ImplKind::Normal
2229             },
2230         }));
2231         Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2232     };
2233     if let Some(type_alias) = type_alias {
2234         ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2235     }
2236     ret.push(make_item(trait_, for_, items));
2237     ret
2238 }
2239
2240 fn clean_extern_crate<'tcx>(
2241     krate: &hir::Item<'tcx>,
2242     name: Symbol,
2243     orig_name: Option<Symbol>,
2244     cx: &mut DocContext<'tcx>,
2245 ) -> Vec<Item> {
2246     // this is the ID of the `extern crate` statement
2247     let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2248     // this is the ID of the crate itself
2249     let crate_def_id = cnum.as_def_id();
2250     let attrs = cx.tcx.hir().attrs(krate.hir_id());
2251     let ty_vis = cx.tcx.visibility(krate.owner_id);
2252     let please_inline = ty_vis.is_public()
2253         && attrs.iter().any(|a| {
2254             a.has_name(sym::doc)
2255                 && match a.meta_item_list() {
2256                     Some(l) => attr::list_contains_name(&l, sym::inline),
2257                     None => false,
2258                 }
2259         });
2260
2261     let krate_owner_def_id = krate.owner_id.to_def_id();
2262     if please_inline {
2263         let mut visited = FxHashSet::default();
2264
2265         let res = Res::Def(DefKind::Mod, crate_def_id);
2266
2267         if let Some(items) = inline::try_inline(
2268             cx,
2269             cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2270             Some(krate_owner_def_id),
2271             res,
2272             name,
2273             Some(attrs),
2274             &mut visited,
2275         ) {
2276             return items;
2277         }
2278     }
2279
2280     // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2281     vec![Item {
2282         name: Some(name),
2283         attrs: Box::new(Attributes::from_ast(attrs)),
2284         item_id: crate_def_id.into(),
2285         kind: Box::new(ExternCrateItem { src: orig_name }),
2286         cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2287         inline_stmt_id: Some(krate_owner_def_id),
2288     }]
2289 }
2290
2291 fn clean_use_statement<'tcx>(
2292     import: &hir::Item<'tcx>,
2293     name: Symbol,
2294     path: &hir::UsePath<'tcx>,
2295     kind: hir::UseKind,
2296     cx: &mut DocContext<'tcx>,
2297     inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2298 ) -> Vec<Item> {
2299     let mut items = Vec::new();
2300     let hir::UsePath { segments, ref res, span } = *path;
2301     for &res in res {
2302         if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
2303             continue;
2304         }
2305         let path = hir::Path { segments, res, span };
2306         items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
2307     }
2308     items
2309 }
2310
2311 fn clean_use_statement_inner<'tcx>(
2312     import: &hir::Item<'tcx>,
2313     name: Symbol,
2314     path: &hir::Path<'tcx>,
2315     kind: hir::UseKind,
2316     cx: &mut DocContext<'tcx>,
2317     inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2318 ) -> Vec<Item> {
2319     // We need this comparison because some imports (for std types for example)
2320     // are "inserted" as well but directly by the compiler and they should not be
2321     // taken into account.
2322     if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2323         return Vec::new();
2324     }
2325
2326     let visibility = cx.tcx.visibility(import.owner_id);
2327     let attrs = cx.tcx.hir().attrs(import.hir_id());
2328     let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2329     let pub_underscore = visibility.is_public() && name == kw::Underscore;
2330     let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
2331
2332     // The parent of the module in which this import resides. This
2333     // is the same as `current_mod` if that's already the top
2334     // level module.
2335     let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2336
2337     // This checks if the import can be seen from a higher level module.
2338     // In other words, it checks if the visibility is the equivalent of
2339     // `pub(super)` or higher. If the current module is the top level
2340     // module, there isn't really a parent module, which makes the results
2341     // meaningless. In this case, we make sure the answer is `false`.
2342     let is_visible_from_parent_mod =
2343         visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
2344
2345     if pub_underscore {
2346         if let Some(ref inline) = inline_attr {
2347             rustc_errors::struct_span_err!(
2348                 cx.tcx.sess,
2349                 inline.span(),
2350                 E0780,
2351                 "anonymous imports cannot be inlined"
2352             )
2353             .span_label(import.span, "anonymous import")
2354             .emit();
2355         }
2356     }
2357
2358     // We consider inlining the documentation of `pub use` statements, but we
2359     // forcefully don't inline if this is not public or if the
2360     // #[doc(no_inline)] attribute is present.
2361     // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2362     let mut denied = cx.output_format.is_json()
2363         || !(visibility.is_public()
2364             || (cx.render_options.document_private && is_visible_from_parent_mod))
2365         || pub_underscore
2366         || attrs.iter().any(|a| {
2367             a.has_name(sym::doc)
2368                 && match a.meta_item_list() {
2369                     Some(l) => {
2370                         attr::list_contains_name(&l, sym::no_inline)
2371                             || attr::list_contains_name(&l, sym::hidden)
2372                     }
2373                     None => false,
2374                 }
2375         });
2376
2377     // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2378     // crate in Rust 2018+
2379     let path = clean_path(path, cx);
2380     let inner = if kind == hir::UseKind::Glob {
2381         if !denied {
2382             let mut visited = FxHashSet::default();
2383             if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited, inlined_names)
2384             {
2385                 return items;
2386             }
2387         }
2388         Import::new_glob(resolve_use_source(cx, path), true)
2389     } else {
2390         if inline_attr.is_none() {
2391             if let Res::Def(DefKind::Mod, did) = path.res {
2392                 if !did.is_local() && did.is_crate_root() {
2393                     // if we're `pub use`ing an extern crate root, don't inline it unless we
2394                     // were specifically asked for it
2395                     denied = true;
2396                 }
2397             }
2398         }
2399         if !denied {
2400             let mut visited = FxHashSet::default();
2401             let import_def_id = import.owner_id.to_def_id();
2402
2403             if let Some(mut items) = inline::try_inline(
2404                 cx,
2405                 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2406                 Some(import_def_id),
2407                 path.res,
2408                 name,
2409                 Some(attrs),
2410                 &mut visited,
2411             ) {
2412                 items.push(Item::from_def_id_and_parts(
2413                     import_def_id,
2414                     None,
2415                     ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2416                     cx,
2417                 ));
2418                 return items;
2419             }
2420         }
2421         Import::new_simple(name, resolve_use_source(cx, path), true)
2422     };
2423
2424     vec![Item::from_def_id_and_parts(import.owner_id.to_def_id(), None, ImportItem(inner), cx)]
2425 }
2426
2427 fn clean_maybe_renamed_foreign_item<'tcx>(
2428     cx: &mut DocContext<'tcx>,
2429     item: &hir::ForeignItem<'tcx>,
2430     renamed: Option<Symbol>,
2431 ) -> Item {
2432     let def_id = item.owner_id.to_def_id();
2433     cx.with_param_env(def_id, |cx| {
2434         let kind = match item.kind {
2435             hir::ForeignItemKind::Fn(decl, names, generics) => {
2436                 let (generics, decl) = enter_impl_trait(cx, |cx| {
2437                     // NOTE: generics must be cleaned before args
2438                     let generics = clean_generics(generics, cx);
2439                     let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2440                     let decl = clean_fn_decl_with_args(cx, decl, args);
2441                     (generics, decl)
2442                 });
2443                 ForeignFunctionItem(Box::new(Function { decl, generics }))
2444             }
2445             hir::ForeignItemKind::Static(ty, mutability) => {
2446                 ForeignStaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: None })
2447             }
2448             hir::ForeignItemKind::Type => ForeignTypeItem,
2449         };
2450
2451         Item::from_hir_id_and_parts(
2452             item.hir_id(),
2453             Some(renamed.unwrap_or(item.ident.name)),
2454             kind,
2455             cx,
2456         )
2457     })
2458 }
2459
2460 fn clean_type_binding<'tcx>(
2461     type_binding: &hir::TypeBinding<'tcx>,
2462     cx: &mut DocContext<'tcx>,
2463 ) -> TypeBinding {
2464     TypeBinding {
2465         assoc: PathSegment {
2466             name: type_binding.ident.name,
2467             args: clean_generic_args(type_binding.gen_args, cx),
2468         },
2469         kind: match type_binding.kind {
2470             hir::TypeBindingKind::Equality { ref term } => {
2471                 TypeBindingKind::Equality { term: clean_hir_term(term, cx) }
2472             }
2473             hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2474                 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
2475             },
2476         },
2477     }
2478 }