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