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