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