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