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