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