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