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