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