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