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