]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/clean/mod.rs
New upstream version 1.48.0~beta.8+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;
dfeec247
XL
6pub mod cfg;
7pub mod inline;
60c5eb7d
XL
8mod simplify;
9pub mod types;
dfeec247 10pub mod utils;
1a4d82fc 11
3dfed10e 12use rustc_ast as ast;
74b04a01 13use rustc_attr as attr;
dfeec247
XL
14use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15use rustc_hir as hir;
16use rustc_hir::def::{CtorKind, DefKind, Res};
17use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
18use rustc_index::vec::{Idx, IndexVec};
74b04a01 19use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
3dfed10e 20use rustc_middle::bug;
ba9703b0
XL
21use rustc_middle::middle::resolve_lifetime as rl;
22use rustc_middle::middle::stability;
23use rustc_middle::ty::fold::TypeFolder;
24use rustc_middle::ty::subst::InternalSubsts;
25use rustc_middle::ty::{self, AdtKind, Lift, Ty, TyCtxt};
1b1a35ee 26use rustc_mir::const_eval::{is_const_fn, is_min_const_fn, is_unstable_const_fn};
dfeec247 27use rustc_span::hygiene::MacroKind;
f9f354fc 28use rustc_span::symbol::{kw, sym, Ident, Symbol};
dfeec247
XL
29use rustc_span::{self, Pos};
30use rustc_typeck::hir_ty_to_ty;
94b46f34 31
0531ce1d 32use std::collections::hash_map::Entry;
ff7c6d11 33use std::default::Default;
dfeec247 34use std::hash::Hash;
1a4d82fc 35use std::rc::Rc;
dfeec247 36use std::{mem, vec};
1a4d82fc 37
e1599b0c 38use crate::core::{self, DocContext, ImplTraitParam};
9fa01778 39use crate::doctree;
9fa01778 40
60c5eb7d 41use utils::*;
1a4d82fc 42
60c5eb7d 43pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
0531ce1d 44
74b04a01 45pub use self::types::FnRetTy::*;
60c5eb7d
XL
46pub use self::types::ItemEnum::*;
47pub use self::types::SelfTy::*;
dfeec247
XL
48pub use self::types::Type::*;
49pub use self::types::Visibility::{Inherited, Public};
50pub use self::types::*;
0531ce1d 51
74b04a01 52const FN_OUTPUT_NAME: &str = "Output";
3b2f2976 53
1a4d82fc 54pub trait Clean<T> {
532ac7d7 55 fn clean(&self, cx: &DocContext<'_>) -> T;
1a4d82fc
JJ
56}
57
c34b1796 58impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
532ac7d7 59 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
1a4d82fc
JJ
60 self.iter().map(|x| x.clean(cx)).collect()
61 }
62}
63
a1dfa0c6 64impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
532ac7d7 65 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
a1dfa0c6
XL
66 self.iter().map(|x| x.clean(cx)).collect()
67 }
68}
69
dfeec247 70impl<T: Clean<U>, U> Clean<U> for &T {
532ac7d7 71 fn clean(&self, cx: &DocContext<'_>) -> U {
1a4d82fc
JJ
72 (**self).clean(cx)
73 }
74}
75
76impl<T: Clean<U>, U> Clean<U> for Rc<T> {
532ac7d7 77 fn clean(&self, cx: &DocContext<'_>) -> U {
1a4d82fc
JJ
78 (**self).clean(cx)
79 }
80}
81
82impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
532ac7d7 83 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
54a0048b 84 self.as_ref().map(|v| v.clean(cx))
1a4d82fc
JJ
85 }
86}
87
92a42be0 88impl Clean<ExternalCrate> for CrateNum {
532ac7d7 89 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
476ff2be
SL
90 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
91 let krate_span = cx.tcx.def_span(root);
b7449926 92 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
476ff2be
SL
93
94 // Collect all inner modules which are tagged as implementations of
95 // primitives.
96 //
97 // Note that this loop only searches the top-level items of the crate,
98 // and this is intentional. If we were to search the entire crate for an
99 // item tagged with `#[doc(primitive)]` then we would also have to
100 // search the entirety of external modules for items tagged
101 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
102 // all that metadata unconditionally).
103 //
104 // In order to keep the metadata load under control, the
105 // `#[doc(primitive)]` feature is explicitly designed to only allow the
106 // primitive tags to show up as the top level items in a crate.
107 //
108 // Also note that this does not attempt to deal with modules tagged
109 // duplicately for the same primitive. This is handled later on when
110 // rendering by delegating everything to a hash map.
48663c56
XL
111 let as_primitive = |res: Res| {
112 if let Res::Def(DefKind::Mod, def_id) = res {
476ff2be
SL
113 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
114 let mut prim = None;
48663c56 115 for attr in attrs.lists(sym::doc) {
476ff2be 116 if let Some(v) = attr.value_str() {
3dfed10e
XL
117 if attr.has_name(sym::primitive) {
118 prim = PrimitiveType::from_symbol(v);
476ff2be
SL
119 if prim.is_some() {
120 break;
121 }
abe05a73 122 // FIXME: should warn on unknown primitives?
476ff2be
SL
123 }
124 }
125 }
126 return prim.map(|p| (def_id, p, attrs));
92a42be0 127 }
476ff2be
SL
128 None
129 };
130 let primitives = if root.is_local() {
dfeec247
XL
131 cx.tcx
132 .hir()
133 .krate()
ba9703b0 134 .item
dfeec247
XL
135 .module
136 .item_ids
137 .iter()
138 .filter_map(|&id| {
139 let item = cx.tcx.hir().expect_item(id.id);
140 match item.kind {
f9f354fc
XL
141 hir::ItemKind::Mod(_) => as_primitive(Res::Def(
142 DefKind::Mod,
143 cx.tcx.hir().local_def_id(id.id).to_def_id(),
144 )),
dfeec247
XL
145 hir::ItemKind::Use(ref path, hir::UseKind::Single)
146 if item.vis.node.is_pub() =>
147 {
148 as_primitive(path.res).map(|(_, prim, attrs)| {
149 // Pretend the primitive is local.
f9f354fc 150 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
dfeec247
XL
151 })
152 }
153 _ => None,
476ff2be 154 }
dfeec247
XL
155 })
156 .collect()
476ff2be 157 } else {
dfeec247
XL
158 cx.tcx
159 .item_children(root)
160 .iter()
161 .map(|item| item.res)
162 .filter_map(as_primitive)
163 .collect()
476ff2be
SL
164 };
165
48663c56
XL
166 let as_keyword = |res: Res| {
167 if let Res::Def(DefKind::Mod, def_id) = res {
94b46f34
XL
168 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
169 let mut keyword = None;
48663c56 170 for attr in attrs.lists(sym::doc) {
94b46f34 171 if let Some(v) = attr.value_str() {
3dfed10e 172 if attr.has_name(sym::keyword) {
dc9dc135
XL
173 if v.is_doc_keyword() {
174 keyword = Some(v.to_string());
175 break;
94b46f34
XL
176 }
177 // FIXME: should warn on unknown keywords?
178 }
179 }
180 }
181 return keyword.map(|p| (def_id, p, attrs));
182 }
183 None
184 };
185 let keywords = if root.is_local() {
dfeec247
XL
186 cx.tcx
187 .hir()
188 .krate()
ba9703b0 189 .item
dfeec247
XL
190 .module
191 .item_ids
192 .iter()
193 .filter_map(|&id| {
194 let item = cx.tcx.hir().expect_item(id.id);
195 match item.kind {
f9f354fc
XL
196 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
197 DefKind::Mod,
198 cx.tcx.hir().local_def_id(id.id).to_def_id(),
199 )),
dfeec247
XL
200 hir::ItemKind::Use(ref path, hir::UseKind::Single)
201 if item.vis.node.is_pub() =>
202 {
203 as_keyword(path.res).map(|(_, prim, attrs)| {
f9f354fc 204 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
dfeec247
XL
205 })
206 }
207 _ => None,
94b46f34 208 }
dfeec247
XL
209 })
210 .collect()
94b46f34 211 } else {
dfeec247 212 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
94b46f34
XL
213 };
214
1a4d82fc 215 ExternalCrate {
476ff2be 216 name: cx.tcx.crate_name(*self).to_string(),
ff7c6d11 217 src: krate_src,
476ff2be 218 attrs: cx.tcx.get_attrs(root).clean(cx),
3b2f2976 219 primitives,
94b46f34 220 keywords,
1a4d82fc
JJ
221 }
222 }
223}
224
dc9dc135 225impl Clean<Item> for doctree::Module<'_> {
532ac7d7 226 fn clean(&self, cx: &DocContext<'_>) -> Item {
1a4d82fc 227 let name = if self.name.is_some() {
b7449926 228 self.name.expect("No name provided").clean(cx)
1a4d82fc 229 } else {
b7449926 230 String::new()
1a4d82fc 231 };
85aaf69f 232
2c00a5a8
XL
233 // maintain a stack of mod ids, for doc comment path resolution
234 // but we also need to resolve the module's own docs based on whether its docs were written
235 // inside or outside the module, so check for that
b7449926 236 let attrs = self.attrs.clean(cx);
2c00a5a8 237
85aaf69f 238 let mut items: Vec<Item> = vec![];
0731742a 239 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
62682a34 240 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
0bf4aa26
XL
241 items.extend(self.structs.iter().map(|x| x.clean(cx)));
242 items.extend(self.unions.iter().map(|x| x.clean(cx)));
243 items.extend(self.enums.iter().map(|x| x.clean(cx)));
85aaf69f 244 items.extend(self.fns.iter().map(|x| x.clean(cx)));
dc9dc135 245 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
85aaf69f
SL
246 items.extend(self.mods.iter().map(|x| x.clean(cx)));
247 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
416331ca 248 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
85aaf69f
SL
249 items.extend(self.statics.iter().map(|x| x.clean(cx)));
250 items.extend(self.constants.iter().map(|x| x.clean(cx)));
251 items.extend(self.traits.iter().map(|x| x.clean(cx)));
62682a34 252 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
85aaf69f 253 items.extend(self.macros.iter().map(|x| x.clean(cx)));
0bf4aa26 254 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
9fa01778 255 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
2c00a5a8 256
1a4d82fc
JJ
257 // determine if we should display the inner contents or
258 // the outer `mod` item for the source code.
1b1a35ee 259 let span = {
74b04a01
XL
260 let sm = cx.sess().source_map();
261 let outer = sm.lookup_char_pos(self.where_outer.lo());
262 let inner = sm.lookup_char_pos(self.where_inner.lo());
1a4d82fc
JJ
263 if outer.file.start_pos == inner.file.start_pos {
264 // mod foo { ... }
265 self.where_outer
266 } else {
b7449926 267 // mod foo; (and a separate SourceFile for the contents)
1a4d82fc
JJ
268 self.where_inner
269 }
270 };
271
272 Item {
273 name: Some(name),
2c00a5a8 274 attrs,
1b1a35ee 275 source: span.clean(cx),
1a4d82fc 276 visibility: self.vis.clean(cx),
416331ca
XL
277 stability: cx.stability(self.id).clean(cx),
278 deprecation: cx.deprecation(self.id).clean(cx),
f9f354fc 279 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
dfeec247 280 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
1a4d82fc
JJ
281 }
282 }
283}
284
476ff2be 285impl Clean<Attributes> for [ast::Attribute] {
532ac7d7 286 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
b7449926 287 Attributes::from_ast(cx.sess().diagnostic(), self)
1a4d82fc
JJ
288 }
289}
290
dfeec247 291impl Clean<GenericBound> for hir::GenericBound<'_> {
532ac7d7 292 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
1a4d82fc 293 match *self {
8faf50e0 294 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
3dfed10e
XL
295 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
296 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
297
298 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
299
300 let generic_args = generic_args.clean(cx);
301 let bindings = match generic_args {
302 GenericArgs::AngleBracketed { bindings, .. } => bindings,
303 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
304 };
305
306 GenericBound::TraitBound(
307 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
308 hir::TraitBoundModifier::None,
309 )
310 }
8faf50e0
XL
311 hir::GenericBound::Trait(ref t, modifier) => {
312 GenericBound::TraitBound(t.clean(cx), modifier)
313 }
1a4d82fc
JJ
314 }
315 }
316}
317
ba9703b0
XL
318impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
319 fn clean(&self, cx: &DocContext<'_>) -> Type {
320 let (trait_ref, bounds) = *self;
0531ce1d 321 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
dfeec247
XL
322 let path = external_path(
323 cx,
324 cx.tcx.item_name(trait_ref.def_id),
325 Some(trait_ref.def_id),
326 true,
ba9703b0 327 bounds.to_vec(),
dfeec247
XL
328 trait_ref.substs,
329 );
1a4d82fc 330
0531ce1d 331 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
1a4d82fc 332
ba9703b0
XL
333 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
334 }
335}
336
337impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
338 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
339 GenericBound::TraitBound(
340 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
341 hir::TraitBoundModifier::None,
342 )
343 }
344}
345
346impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
347 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
348 let (poly_trait_ref, bounds) = *self;
349 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
350
1a4d82fc 351 // collect any late bound regions
ba9703b0
XL
352 let late_bound_regions: Vec<_> = cx
353 .tcx
354 .collect_referenced_late_bound_regions(&poly_trait_ref)
355 .into_iter()
356 .filter_map(|br| match br {
357 ty::BrNamed(_, name) => Some(GenericParamDef {
358 name: name.to_string(),
359 kind: GenericParamDefKind::Lifetime,
360 }),
361 _ => None,
362 })
363 .collect();
1a4d82fc 364
8faf50e0 365 GenericBound::TraitBound(
54a0048b 366 PolyTrait {
f035d41b 367 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
ba9703b0 368 generic_params: late_bound_regions,
62682a34 369 },
dfeec247 370 hir::TraitBoundModifier::None,
54a0048b 371 )
1a4d82fc
JJ
372 }
373}
374
ba9703b0 375impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
532ac7d7 376 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
ba9703b0 377 (*self, &[][..]).clean(cx)
0531ce1d
XL
378 }
379}
380
532ac7d7
XL
381impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
382 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
1a4d82fc 383 let mut v = Vec::new();
8faf50e0 384 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
dfeec247
XL
385 v.extend(self.types().map(|t| {
386 GenericBound::TraitBound(
387 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
388 hir::TraitBoundModifier::None,
389 )
390 }));
391 if !v.is_empty() { Some(v) } else { None }
1a4d82fc
JJ
392 }
393}
394
e9174d1e 395impl Clean<Lifetime> for hir::Lifetime {
532ac7d7 396 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
ba9703b0
XL
397 let def = cx.tcx.named_region(self.hir_id);
398 match def {
399 Some(
400 rl::Region::EarlyBound(_, node_id, _)
401 | rl::Region::LateBound(_, node_id, _)
402 | rl::Region::Free(_, node_id),
403 ) => {
404 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
405 return lt;
9e0c209e 406 }
9e0c209e 407 }
ba9703b0 408 _ => {}
9e0c209e 409 }
8faf50e0 410 Lifetime(self.name.ident().to_string())
1a4d82fc
JJ
411 }
412}
413
dfeec247 414impl Clean<Lifetime> for hir::GenericParam<'_> {
532ac7d7 415 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
8faf50e0
XL
416 match self.kind {
417 hir::GenericParamKind::Lifetime { .. } => {
74b04a01 418 if !self.bounds.is_empty() {
8faf50e0
XL
419 let mut bounds = self.bounds.iter().map(|bound| match bound {
420 hir::GenericBound::Outlives(lt) => lt,
421 _ => panic!(),
422 });
b7449926 423 let name = bounds.next().expect("no more bounds").name.ident();
8faf50e0
XL
424 let mut s = format!("{}: {}", self.name.ident(), name);
425 for bound in bounds {
426 s.push_str(&format!(" + {}", bound.name.ident()));
427 }
428 Lifetime(s)
429 } else {
430 Lifetime(self.name.ident().to_string())
431 }
a7813a04 432 }
8faf50e0 433 _ => panic!(),
a7813a04 434 }
1a4d82fc
JJ
435 }
436}
437
9fa01778 438impl Clean<Constant> for hir::ConstArg {
532ac7d7 439 fn clean(&self, cx: &DocContext<'_>) -> Constant {
9fa01778 440 Constant {
ba9703b0
XL
441 type_: cx
442 .tcx
443 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
444 .clean(cx),
9fa01778 445 expr: print_const_expr(cx, self.value.body),
dfeec247
XL
446 value: None,
447 is_literal: is_literal_expr(cx, self.value.body.hir_id),
9fa01778
XL
448 }
449 }
450}
451
dc9dc135 452impl Clean<Lifetime> for ty::GenericParamDef {
532ac7d7 453 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
c1a9b12d 454 Lifetime(self.name.to_string())
1a4d82fc
JJ
455 }
456}
457
7cac9316 458impl Clean<Option<Lifetime>> for ty::RegionKind {
532ac7d7 459 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
1a4d82fc
JJ
460 match *self {
461 ty::ReStatic => Some(Lifetime::statik()),
8bb4bdeb 462 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
9346a6ac 463 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
1a4d82fc 464
dfeec247
XL
465 ty::ReLateBound(..)
466 | ty::ReFree(..)
dfeec247
XL
467 | ty::ReVar(..)
468 | ty::RePlaceholder(..)
74b04a01 469 | ty::ReEmpty(_)
dfeec247 470 | ty::ReErased => {
416331ca 471 debug!("cannot clean region {:?}", self);
9fa01778
XL
472 None
473 }
1a4d82fc
JJ
474 }
475 }
476}
477
dfeec247 478impl Clean<WherePredicate> for hir::WherePredicate<'_> {
532ac7d7 479 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
1a4d82fc 480 match *self {
dfeec247
XL
481 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
482 ty: wbp.bounded_ty.clean(cx),
483 bounds: wbp.bounds.clean(cx),
484 },
1a4d82fc 485
dfeec247
XL
486 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
487 lifetime: wrp.lifetime.clean(cx),
488 bounds: wrp.bounds.clean(cx),
489 },
1a4d82fc 490
32a655c1 491 hir::WherePredicate::EqPredicate(ref wrp) => {
dfeec247 492 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
1a4d82fc
JJ
493 }
494 }
495 }
496}
497
9fa01778 498impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
532ac7d7 499 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
3dfed10e
XL
500 match self.skip_binders() {
501 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
502 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
503 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
504 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
505
506 ty::PredicateAtom::Subtype(..)
507 | ty::PredicateAtom::WellFormed(..)
508 | ty::PredicateAtom::ObjectSafe(..)
509 | ty::PredicateAtom::ClosureKind(..)
510 | ty::PredicateAtom::ConstEvaluatable(..)
1b1a35ee
XL
511 | ty::PredicateAtom::ConstEquate(..)
512 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
85aaf69f
SL
513 }
514 }
515}
516
ba9703b0 517impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
532ac7d7 518 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
ba9703b0 519 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
85aaf69f 520 WherePredicate::BoundPredicate {
f035d41b 521 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
ba9703b0 522 bounds: vec![poly_trait_ref.clean(cx)],
85aaf69f
SL
523 }
524 }
525}
526
dfeec247 527impl<'tcx> Clean<Option<WherePredicate>>
3dfed10e 528 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
dfeec247 529{
532ac7d7 530 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
3dfed10e 531 let ty::OutlivesPredicate(a, b) = self;
9fa01778 532
ba9703b0
XL
533 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
534 return None;
9fa01778
XL
535 }
536
537 Some(WherePredicate::RegionPredicate {
b7449926 538 lifetime: a.clean(cx).expect("failed to clean lifetime"),
dfeec247 539 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
9fa01778 540 })
85aaf69f
SL
541 }
542}
543
3dfed10e 544impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
532ac7d7 545 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
3dfed10e 546 let ty::OutlivesPredicate(ty, lt) = self;
85aaf69f 547
ba9703b0
XL
548 if let ty::ReEmpty(_) = lt {
549 return None;
9fa01778
XL
550 }
551
552 Some(WherePredicate::BoundPredicate {
85aaf69f 553 ty: ty.clean(cx),
dfeec247 554 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
9fa01778 555 })
85aaf69f
SL
556 }
557}
558
3dfed10e 559impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
532ac7d7 560 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
3dfed10e 561 let ty::ProjectionPredicate { projection_ty, ty } = self;
ba9703b0 562 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
85aaf69f
SL
563 }
564}
565
566impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
532ac7d7 567 fn clean(&self, cx: &DocContext<'_>) -> Type {
dfeec247
XL
568 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
569 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
8faf50e0
XL
570 GenericBound::TraitBound(t, _) => t.trait_,
571 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
85aaf69f
SL
572 };
573 Type::QPath {
8faf50e0 574 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
041b39d2 575 self_type: box self.self_ty().clean(cx),
dfeec247 576 trait_: box trait_,
85aaf69f
SL
577 }
578 }
579}
580
532ac7d7
XL
581impl Clean<GenericParamDef> for ty::GenericParamDef {
582 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
8faf50e0
XL
583 let (name, kind) = match self.kind {
584 ty::GenericParamDefKind::Lifetime => {
585 (self.name.to_string(), GenericParamDefKind::Lifetime)
586 }
e1599b0c 587 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
dfeec247
XL
588 let default =
589 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
590 (
591 self.name.clean(cx),
592 GenericParamDefKind::Type {
593 did: self.def_id,
594 bounds: vec![], // These are filled in from the where-clauses.
595 default,
596 synthetic,
597 },
598 )
8faf50e0 599 }
dfeec247
XL
600 ty::GenericParamDefKind::Const { .. } => (
601 self.name.clean(cx),
602 GenericParamDefKind::Const {
532ac7d7
XL
603 did: self.def_id,
604 ty: cx.tcx.type_of(self.def_id).clean(cx),
dfeec247
XL
605 },
606 ),
8faf50e0
XL
607 };
608
dfeec247 609 GenericParamDef { name, kind }
0531ce1d
XL
610 }
611}
612
dfeec247 613impl Clean<GenericParamDef> for hir::GenericParam<'_> {
532ac7d7 614 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
8faf50e0
XL
615 let (name, kind) = match self.kind {
616 hir::GenericParamKind::Lifetime { .. } => {
74b04a01 617 let name = if !self.bounds.is_empty() {
8faf50e0
XL
618 let mut bounds = self.bounds.iter().map(|bound| match bound {
619 hir::GenericBound::Outlives(lt) => lt,
620 _ => panic!(),
621 });
b7449926 622 let name = bounds.next().expect("no more bounds").name.ident();
8faf50e0
XL
623 let mut s = format!("{}: {}", self.name.ident(), name);
624 for bound in bounds {
625 s.push_str(&format!(" + {}", bound.name.ident()));
626 }
627 s
628 } else {
629 self.name.ident().to_string()
630 };
631 (name, GenericParamDefKind::Lifetime)
632 }
dfeec247
XL
633 hir::GenericParamKind::Type { ref default, synthetic } => (
634 self.name.ident().name.clean(cx),
635 GenericParamDefKind::Type {
f9f354fc 636 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
8faf50e0
XL
637 bounds: self.bounds.clean(cx),
638 default: default.clean(cx),
e74abb32 639 synthetic,
dfeec247
XL
640 },
641 ),
642 hir::GenericParamKind::Const { ref ty } => (
643 self.name.ident().name.clean(cx),
644 GenericParamDefKind::Const {
f9f354fc 645 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
9fa01778 646 ty: ty.clean(cx),
dfeec247
XL
647 },
648 ),
8faf50e0
XL
649 };
650
dfeec247 651 GenericParamDef { name, kind }
ff7c6d11
XL
652 }
653}
654
dfeec247 655impl Clean<Generics> for hir::Generics<'_> {
532ac7d7 656 fn clean(&self, cx: &DocContext<'_>) -> Generics {
94b46f34
XL
657 // Synthetic type-parameters are inserted after normal ones.
658 // In order for normal parameters to be able to refer to synthetic ones,
659 // scans them first.
dfeec247 660 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
8faf50e0
XL
661 match param.kind {
662 hir::GenericParamKind::Type { synthetic, .. } => {
663 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
664 }
665 _ => false,
94b46f34
XL
666 }
667 }
dfeec247
XL
668 let impl_trait_params = self
669 .params
94b46f34 670 .iter()
8faf50e0
XL
671 .filter(|param| is_impl_trait(param))
672 .map(|param| {
673 let param: GenericParamDef = param.clean(cx);
674 match param.kind {
675 GenericParamDefKind::Lifetime => unreachable!(),
676 GenericParamDefKind::Type { did, ref bounds, .. } => {
e1599b0c 677 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
8faf50e0 678 }
9fa01778 679 GenericParamDefKind::Const { .. } => unreachable!(),
94b46f34 680 }
8faf50e0 681 param
94b46f34
XL
682 })
683 .collect::<Vec<_>>();
684
0531ce1d 685 let mut params = Vec::with_capacity(self.params.len());
94b46f34 686 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
0531ce1d 687 let p = p.clean(cx);
0531ce1d
XL
688 params.push(p);
689 }
94b46f34
XL
690 params.extend(impl_trait_params);
691
dfeec247
XL
692 let mut generics =
693 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
ff7c6d11
XL
694
695 // Some duplicates are generated for ?Sized bounds between type params and where
696 // predicates. The point in here is to move the bounds definitions from type params
697 // to where predicates when such cases occur.
8faf50e0 698 for where_pred in &mut generics.where_predicates {
ff7c6d11
XL
699 match *where_pred {
700 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
701 if bounds.is_empty() {
8faf50e0
XL
702 for param in &mut generics.params {
703 match param.kind {
704 GenericParamDefKind::Lifetime => {}
705 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
706 if &param.name == name {
707 mem::swap(bounds, ty_bounds);
dfeec247 708 break;
8faf50e0 709 }
ff7c6d11 710 }
9fa01778 711 GenericParamDefKind::Const { .. } => {}
ff7c6d11
XL
712 }
713 }
714 }
715 }
716 _ => continue,
717 }
1a4d82fc 718 }
8faf50e0 719 generics
1a4d82fc
JJ
720 }
721}
722
e74abb32 723impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
532ac7d7 724 fn clean(&self, cx: &DocContext<'_>) -> Generics {
85aaf69f 725 use self::WherePredicate as WP;
e1599b0c 726 use std::collections::BTreeMap;
85aaf69f 727
9e0c209e 728 let (gens, preds) = *self;
85aaf69f 729
e1599b0c
XL
730 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
731 // since `Clean for ty::Predicate` would consume them.
732 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
733
9346a6ac
AL
734 // Bounds in the type_params and lifetimes fields are repeated in the
735 // predicates field (see rustc_typeck::collect::ty_generics), so remove
736 // them.
3dfed10e 737 let stripped_params = gens
dfeec247
XL
738 .params
739 .iter()
e1599b0c 740 .filter_map(|param| match param.kind {
3dfed10e 741 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
e1599b0c 742 ty::GenericParamDefKind::Type { synthetic, .. } => {
e74abb32 743 if param.name == kw::SelfUpper {
e1599b0c
XL
744 assert_eq!(param.index, 0);
745 return None;
746 }
747 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
748 impl_trait.insert(param.index.into(), vec![]);
749 return None;
750 }
751 Some(param.clean(cx))
752 }
3dfed10e 753 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
dfeec247
XL
754 })
755 .collect::<Vec<GenericParamDef>>();
e1599b0c
XL
756
757 // param index -> [(DefId of trait, associated type name, type)]
dfeec247 758 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
e1599b0c 759
dfeec247
XL
760 let where_predicates = preds
761 .predicates
762 .iter()
e1599b0c
XL
763 .flat_map(|(p, _)| {
764 let mut projection = None;
765 let param_idx = (|| {
3dfed10e
XL
766 match p.skip_binders() {
767 ty::PredicateAtom::Trait(pred, _constness) => {
1b1a35ee 768 if let ty::Param(param) = pred.self_ty().kind() {
3dfed10e
XL
769 return Some(param.index);
770 }
e1599b0c 771 }
3dfed10e 772 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
1b1a35ee 773 if let ty::Param(param) = ty.kind() {
3dfed10e
XL
774 return Some(param.index);
775 }
e1599b0c 776 }
3dfed10e 777 ty::PredicateAtom::Projection(p) => {
1b1a35ee 778 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
3dfed10e
XL
779 projection = Some(ty::Binder::bind(p));
780 return Some(param.index);
781 }
e1599b0c 782 }
3dfed10e 783 _ => (),
e1599b0c
XL
784 }
785
786 None
787 })();
788
789 if let Some(param_idx) = param_idx {
790 if let Some(b) = impl_trait.get_mut(&param_idx.into()) {
791 let p = p.clean(cx)?;
792
793 b.extend(
794 p.get_bounds()
795 .into_iter()
796 .flatten()
797 .cloned()
dfeec247 798 .filter(|b| !b.is_sized_bound(cx)),
e1599b0c
XL
799 );
800
801 let proj = projection
802 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
803 if let Some(((_, trait_did, name), rhs)) =
804 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
805 {
dfeec247
XL
806 impl_trait_proj.entry(param_idx).or_default().push((
807 trait_did,
808 name.to_string(),
809 rhs,
810 ));
e1599b0c
XL
811 }
812
813 return None;
814 }
815 }
816
817 Some(p)
818 })
819 .collect::<Vec<_>>();
820
821 for (param, mut bounds) in impl_trait {
822 // Move trait bounds to the front.
dfeec247 823 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
e1599b0c
XL
824
825 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
826 if let Some(proj) = impl_trait_proj.remove(&idx) {
827 for (trait_did, name, rhs) in proj {
dfeec247 828 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
e1599b0c 829 }
94b46f34 830 }
e1599b0c
XL
831 } else {
832 unreachable!();
9e0c209e 833 }
85aaf69f 834
e1599b0c
XL
835 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
836 }
837
838 // Now that `cx.impl_trait_bounds` is populated, we can process
839 // remaining predicates which could contain `impl Trait`.
dfeec247
XL
840 let mut where_predicates =
841 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
85aaf69f 842
1b1a35ee 843 // Type parameters have a Sized bound by default unless removed with
ff7c6d11 844 // ?Sized. Scan through the predicates and mark any type parameter with
9346a6ac
AL
845 // a Sized bound, removing the bounds as we find them.
846 //
847 // Note that associated types also have a sized bound by default, but we
d9579d0f 848 // don't actually know the set of associated types right here so that's
9346a6ac 849 // handled in cleaning associated types
0bf4aa26 850 let mut sized_params = FxHashSet::default();
dfeec247
XL
851 where_predicates.retain(|pred| match *pred {
852 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
853 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
854 sized_params.insert(g.clone());
855 false
856 } else {
857 true
85aaf69f
SL
858 }
859 }
dfeec247 860 _ => true,
9346a6ac 861 });
85aaf69f 862
9346a6ac
AL
863 // Run through the type parameters again and insert a ?Sized
864 // unbound for any we didn't find to be Sized.
3dfed10e
XL
865 for tp in &stripped_params {
866 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
867 && !sized_params.contains(&tp.name)
868 {
85aaf69f
SL
869 where_predicates.push(WP::BoundPredicate {
870 ty: Type::Generic(tp.name.clone()),
8faf50e0 871 bounds: vec![GenericBound::maybe_sized(cx)],
85aaf69f
SL
872 })
873 }
874 }
875
876 // It would be nice to collect all of the bounds on a type and recombine
0731742a 877 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
85aaf69f
SL
878 // and instead see `where T: Foo + Bar + Sized + 'a`
879
1a4d82fc 880 Generics {
3dfed10e 881 params: stripped_params,
9346a6ac 882 where_predicates: simplify::where_clauses(cx, where_predicates),
1a4d82fc
JJ
883 }
884 }
885}
886
dfeec247
XL
887impl<'a> Clean<Method>
888 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
889{
532ac7d7 890 fn clean(&self, cx: &DocContext<'_>) -> Method {
dfeec247
XL
891 let (generics, decl) =
892 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
532ac7d7 893 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
dfeec247 894 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
1a4d82fc
JJ
895 }
896}
897
dc9dc135 898impl Clean<Item> for doctree::Function<'_> {
532ac7d7 899 fn clean(&self, cx: &DocContext<'_>) -> Item {
dfeec247
XL
900 let (generics, decl) =
901 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
8faf50e0 902
416331ca 903 let did = cx.tcx.hir().local_def_id(self.id);
1b1a35ee
XL
904 let constness = if is_const_fn(cx.tcx, did.to_def_id())
905 && !is_unstable_const_fn(cx.tcx, did.to_def_id()).is_some()
906 {
0731742a
XL
907 hir::Constness::Const
908 } else {
909 hir::Constness::NotConst
910 };
532ac7d7 911 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1a4d82fc
JJ
912 Item {
913 name: Some(self.name.clean(cx)),
914 attrs: self.attrs.clean(cx),
1b1a35ee 915 source: self.span.clean(cx),
1a4d82fc 916 visibility: self.vis.clean(cx),
416331ca
XL
917 stability: cx.stability(self.id).clean(cx),
918 deprecation: cx.deprecation(self.id).clean(cx),
f9f354fc 919 def_id: did.to_def_id(),
1a4d82fc 920 inner: FunctionItem(Function {
0531ce1d
XL
921 decl,
922 generics,
0731742a 923 header: hir::FnHeader { constness, ..self.header },
532ac7d7
XL
924 all_types,
925 ret_types,
1a4d82fc
JJ
926 }),
927 }
60c5eb7d 928 }
1a4d82fc
JJ
929}
930
f9f354fc 931impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
532ac7d7 932 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
32a655c1 933 Arguments {
dfeec247
XL
934 values: self
935 .0
936 .iter()
937 .enumerate()
938 .map(|(i, ty)| {
939 let mut name =
940 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
941 if name.is_empty() {
942 name = "_".to_string();
943 }
944 Argument { name, type_: ty.clean(cx) }
945 })
946 .collect(),
32a655c1
SL
947 }
948 }
949}
950
dfeec247 951impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
532ac7d7 952 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
0731742a 953 let body = cx.tcx.hir().body(self.1);
32a655c1
SL
954
955 Arguments {
dfeec247
XL
956 values: self
957 .0
958 .iter()
959 .enumerate()
960 .map(|(i, ty)| Argument {
e1599b0c 961 name: name_from_pat(&body.params[i].pat),
32a655c1 962 type_: ty.clean(cx),
dfeec247
XL
963 })
964 .collect(),
32a655c1
SL
965 }
966 }
967}
968
dfeec247
XL
969impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
970where
971 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
32a655c1 972{
532ac7d7 973 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
1a4d82fc 974 FnDecl {
32a655c1
SL
975 inputs: (&self.0.inputs[..], self.1).clean(cx),
976 output: self.0.output.clean(cx),
e74abb32 977 c_variadic: self.0.c_variadic,
532ac7d7 978 attrs: Attributes::default(),
1a4d82fc
JJ
979 }
980 }
981}
982
dc9dc135 983impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
532ac7d7 984 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
1a4d82fc 985 let (did, sig) = *self;
f9f354fc 986 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
0531ce1d 987
1a4d82fc 988 FnDecl {
476ff2be
SL
989 output: Return(sig.skip_binder().output().clean(cx)),
990 attrs: Attributes::default(),
e74abb32 991 c_variadic: sig.skip_binder().c_variadic,
1a4d82fc 992 inputs: Arguments {
dfeec247
XL
993 values: sig
994 .skip_binder()
995 .inputs()
996 .iter()
997 .map(|t| Argument {
1a4d82fc 998 type_: t.clean(cx),
b7449926 999 name: names.next().map_or(String::new(), |name| name.to_string()),
dfeec247
XL
1000 })
1001 .collect(),
1a4d82fc
JJ
1002 },
1003 }
1004 }
1005}
1006
74b04a01
XL
1007impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1008 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1a4d82fc 1009 match *self {
dfeec247
XL
1010 Self::Return(ref typ) => Return(typ.clean(cx)),
1011 Self::DefaultReturn(..) => DefaultReturn,
1a4d82fc
JJ
1012 }
1013 }
1014}
1015
dc9dc135 1016impl Clean<Item> for doctree::Trait<'_> {
532ac7d7 1017 fn clean(&self, cx: &DocContext<'_>) -> Item {
ff7c6d11 1018 let attrs = self.attrs.clean(cx);
3dfed10e 1019 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1a4d82fc
JJ
1020 Item {
1021 name: Some(self.name.clean(cx)),
e74abb32 1022 attrs,
1b1a35ee 1023 source: self.span.clean(cx),
f9f354fc 1024 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1a4d82fc 1025 visibility: self.vis.clean(cx),
416331ca
XL
1026 stability: cx.stability(self.id).clean(cx),
1027 deprecation: cx.deprecation(self.id).clean(cx),
1a4d82fc 1028 inner: TraitItem(Trait {
0531ce1d 1029 auto: self.is_auto.clean(cx),
1a4d82fc 1030 unsafety: self.unsafety,
dc9dc135 1031 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1a4d82fc
JJ
1032 generics: self.generics.clean(cx),
1033 bounds: self.bounds.clean(cx),
3dfed10e 1034 is_spotlight,
2c00a5a8 1035 is_auto: self.is_auto.clean(cx),
1a4d82fc
JJ
1036 }),
1037 }
1038 }
1039}
1040
dc9dc135 1041impl Clean<Item> for doctree::TraitAlias<'_> {
532ac7d7 1042 fn clean(&self, cx: &DocContext<'_>) -> Item {
9fa01778
XL
1043 let attrs = self.attrs.clean(cx);
1044 Item {
1045 name: Some(self.name.clean(cx)),
1046 attrs,
1b1a35ee 1047 source: self.span.clean(cx),
f9f354fc 1048 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
9fa01778 1049 visibility: self.vis.clean(cx),
416331ca
XL
1050 stability: cx.stability(self.id).clean(cx),
1051 deprecation: cx.deprecation(self.id).clean(cx),
9fa01778
XL
1052 inner: TraitAliasItem(TraitAlias {
1053 generics: self.generics.clean(cx),
1054 bounds: self.bounds.clean(cx),
1055 }),
1056 }
1057 }
1058}
1059
2c00a5a8 1060impl Clean<bool> for hir::IsAuto {
532ac7d7 1061 fn clean(&self, _: &DocContext<'_>) -> bool {
2c00a5a8
XL
1062 match *self {
1063 hir::IsAuto::Yes => true,
1064 hir::IsAuto::No => false,
1065 }
1066 }
1067}
1068
dfeec247 1069impl Clean<Type> for hir::TraitRef<'_> {
532ac7d7
XL
1070 fn clean(&self, cx: &DocContext<'_>) -> Type {
1071 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1a4d82fc
JJ
1072 }
1073}
1074
dfeec247 1075impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
532ac7d7 1076 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1a4d82fc
JJ
1077 PolyTrait {
1078 trait_: self.trait_ref.clean(cx),
dfeec247 1079 generic_params: self.bound_generic_params.clean(cx),
1a4d82fc
JJ
1080 }
1081 }
1082}
1083
ba9703b0
XL
1084impl Clean<TypeKind> for hir::def::DefKind {
1085 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1086 match *self {
1087 hir::def::DefKind::Mod => TypeKind::Module,
1088 hir::def::DefKind::Struct => TypeKind::Struct,
1089 hir::def::DefKind::Union => TypeKind::Union,
1090 hir::def::DefKind::Enum => TypeKind::Enum,
1091 hir::def::DefKind::Trait => TypeKind::Trait,
1092 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1093 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1094 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1095 hir::def::DefKind::Fn => TypeKind::Function,
1096 hir::def::DefKind::Const => TypeKind::Const,
1097 hir::def::DefKind::Static => TypeKind::Static,
1098 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1099 _ => TypeKind::Foreign,
1100 }
1101 }
1102}
1103
dfeec247 1104impl Clean<Item> for hir::TraitItem<'_> {
532ac7d7 1105 fn clean(&self, cx: &DocContext<'_>) -> Item {
3dfed10e 1106 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
e74abb32 1107 let inner = match self.kind {
32a655c1 1108 hir::TraitItemKind::Const(ref ty, default) => {
dfeec247 1109 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
d9579d0f 1110 }
ba9703b0 1111 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
3dfed10e
XL
1112 let mut m = (sig, &self.generics, body, None).clean(cx);
1113 if m.header.constness == hir::Constness::Const
1b1a35ee 1114 && is_unstable_const_fn(cx.tcx, local_did.to_def_id()).is_some()
3dfed10e
XL
1115 {
1116 m.header.constness = hir::Constness::NotConst;
1117 }
1118 MethodItem(m)
c34b1796 1119 }
ba9703b0 1120 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
0531ce1d
XL
1121 let (generics, decl) = enter_impl_trait(cx, || {
1122 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1123 });
532ac7d7 1124 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
3dfed10e
XL
1125 let mut t = TyMethod { header: sig.header, decl, generics, all_types, ret_types };
1126 if t.header.constness == hir::Constness::Const
1b1a35ee 1127 && is_unstable_const_fn(cx.tcx, local_did.to_def_id()).is_some()
3dfed10e
XL
1128 {
1129 t.header.constness = hir::Constness::NotConst;
1130 }
1131 TyMethodItem(t)
c34b1796 1132 }
32a655c1 1133 hir::TraitItemKind::Type(ref bounds, ref default) => {
dc9dc135 1134 AssocTypeItem(bounds.clean(cx), default.clean(cx))
c34b1796
AL
1135 }
1136 };
1137 Item {
8faf50e0 1138 name: Some(self.ident.name.clean(cx)),
c34b1796
AL
1139 attrs: self.attrs.clean(cx),
1140 source: self.span.clean(cx),
f9f354fc 1141 def_id: local_did.to_def_id(),
e74abb32 1142 visibility: Visibility::Inherited,
f9f354fc
XL
1143 stability: get_stability(cx, local_did.to_def_id()),
1144 deprecation: get_deprecation(cx, local_did.to_def_id()),
3b2f2976 1145 inner,
1a4d82fc
JJ
1146 }
1147 }
1148}
1149
dfeec247 1150impl Clean<Item> for hir::ImplItem<'_> {
532ac7d7 1151 fn clean(&self, cx: &DocContext<'_>) -> Item {
3dfed10e 1152 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
e74abb32 1153 let inner = match self.kind {
32a655c1 1154 hir::ImplItemKind::Const(ref ty, expr) => {
dfeec247 1155 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
d9579d0f 1156 }
ba9703b0 1157 hir::ImplItemKind::Fn(ref sig, body) => {
3dfed10e
XL
1158 let mut m = (sig, &self.generics, body, Some(self.defaultness)).clean(cx);
1159 if m.header.constness == hir::Constness::Const
1b1a35ee 1160 && is_unstable_const_fn(cx.tcx, local_did.to_def_id()).is_some()
3dfed10e
XL
1161 {
1162 m.header.constness = hir::Constness::NotConst;
1163 }
1164 MethodItem(m)
c34b1796 1165 }
dfeec247
XL
1166 hir::ImplItemKind::TyAlias(ref ty) => {
1167 let type_ = ty.clean(cx);
1168 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1169 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1170 }
c34b1796
AL
1171 };
1172 Item {
8faf50e0 1173 name: Some(self.ident.name.clean(cx)),
c34b1796
AL
1174 source: self.span.clean(cx),
1175 attrs: self.attrs.clean(cx),
f9f354fc 1176 def_id: local_did.to_def_id(),
c34b1796 1177 visibility: self.vis.clean(cx),
f9f354fc
XL
1178 stability: get_stability(cx, local_did.to_def_id()),
1179 deprecation: get_deprecation(cx, local_did.to_def_id()),
3b2f2976 1180 inner,
1a4d82fc
JJ
1181 }
1182 }
1183}
1184
dc9dc135 1185impl Clean<Item> for ty::AssocItem {
532ac7d7 1186 fn clean(&self, cx: &DocContext<'_>) -> Item {
476ff2be 1187 let inner = match self.kind {
dc9dc135 1188 ty::AssocKind::Const => {
7cac9316 1189 let ty = cx.tcx.type_of(self.def_id);
ff7c6d11
XL
1190 let default = if self.defaultness.has_value() {
1191 Some(inline::print_inlined_const(cx, self.def_id))
1192 } else {
1193 None
1194 };
dc9dc135 1195 AssocConstItem(ty.clean(cx), default)
a7813a04 1196 }
ba9703b0 1197 ty::AssocKind::Fn => {
dfeec247
XL
1198 let generics =
1199 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1200 .clean(cx);
041b39d2 1201 let sig = cx.tcx.fn_sig(self.def_id);
8bb4bdeb 1202 let mut decl = (self.def_id, sig).clean(cx);
476ff2be 1203
ba9703b0 1204 if self.fn_has_self_parameter {
476ff2be 1205 let self_ty = match self.container {
dfeec247 1206 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
e1599b0c 1207 ty::TraitContainer(_) => cx.tcx.types.self_param,
476ff2be 1208 };
f035d41b 1209 let self_arg_ty = sig.input(0).skip_binder();
476ff2be 1210 if self_arg_ty == self_ty {
32a655c1 1211 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1b1a35ee 1212 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
94b46f34 1213 if ty == self_ty {
476ff2be 1214 match decl.inputs.values[0].type_ {
dfeec247 1215 BorrowedRef { ref mut type_, .. } => {
32a655c1
SL
1216 **type_ = Generic(String::from("Self"))
1217 }
476ff2be
SL
1218 _ => unreachable!(),
1219 }
1220 }
1221 }
1222 }
1223
1224 let provided = match self.container {
ff7c6d11 1225 ty::ImplContainer(_) => true,
dfeec247 1226 ty::TraitContainer(_) => self.defaultness.has_value(),
476ff2be 1227 };
532ac7d7 1228 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
476ff2be 1229 if provided {
dfeec247 1230 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
ff7c6d11
XL
1231 hir::Constness::Const
1232 } else {
1233 hir::Constness::NotConst
1234 };
e1599b0c 1235 let asyncness = cx.tcx.asyncness(self.def_id);
532ac7d7
XL
1236 let defaultness = match self.container {
1237 ty::ImplContainer(_) => Some(self.defaultness),
1238 ty::TraitContainer(_) => None,
1239 };
476ff2be 1240 MethodItem(Method {
3b2f2976
XL
1241 generics,
1242 decl,
8faf50e0
XL
1243 header: hir::FnHeader {
1244 unsafety: sig.unsafety(),
1245 abi: sig.abi(),
1246 constness,
e1599b0c 1247 asyncness,
532ac7d7
XL
1248 },
1249 defaultness,
1250 all_types,
1251 ret_types,
476ff2be
SL
1252 })
1253 } else {
1254 TyMethodItem(TyMethod {
3b2f2976
XL
1255 generics,
1256 decl,
8faf50e0
XL
1257 header: hir::FnHeader {
1258 unsafety: sig.unsafety(),
1259 abi: sig.abi(),
1260 constness: hir::Constness::NotConst,
1261 asyncness: hir::IsAsync::NotAsync,
532ac7d7
XL
1262 },
1263 all_types,
1264 ret_types,
476ff2be 1265 })
a7813a04
XL
1266 }
1267 }
dc9dc135 1268 ty::AssocKind::Type => {
8faf50e0 1269 let my_name = self.ident.name.clean(cx);
476ff2be 1270
ff7c6d11 1271 if let ty::TraitContainer(did) = self.container {
476ff2be
SL
1272 // When loading a cross-crate associated type, the bounds for this type
1273 // are actually located on the trait/impl itself, so we need to load
1274 // all of the generics from there and then look for bounds that are
1275 // applied to this associated type in question.
532ac7d7 1276 let predicates = cx.tcx.explicit_predicates_of(did);
e74abb32 1277 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
dfeec247
XL
1278 let mut bounds = generics
1279 .where_predicates
1280 .iter()
1281 .filter_map(|pred| {
1282 let (name, self_type, trait_, bounds) = match *pred {
1283 WherePredicate::BoundPredicate {
1284 ty: QPath { ref name, ref self_type, ref trait_ },
1285 ref bounds,
1286 } => (name, self_type, trait_, bounds),
1287 _ => return None,
1288 };
1289 if *name != my_name {
1290 return None;
1291 }
1292 match **trait_ {
1293 ResolvedPath { did, .. } if did == self.container.id() => {}
1294 _ => return None,
1295 }
1296 match **self_type {
1297 Generic(ref s) if *s == "Self" => {}
1298 _ => return None,
1299 }
1300 Some(bounds)
1301 })
1302 .flat_map(|i| i.iter().cloned())
1303 .collect::<Vec<_>>();
ff7c6d11
XL
1304 // Our Sized/?Sized bound didn't get handled when creating the generics
1305 // because we didn't actually get our whole set of bounds until just now
1306 // (some of them may have come from the trait). If we do have a sized
1307 // bound, we remove it, and if we don't then we add the `?Sized` bound
1308 // at the end.
1309 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
dfeec247
XL
1310 Some(i) => {
1311 bounds.remove(i);
1312 }
8faf50e0 1313 None => bounds.push(GenericBound::maybe_sized(cx)),
ff7c6d11 1314 }
476ff2be 1315
ff7c6d11
XL
1316 let ty = if self.defaultness.has_value() {
1317 Some(cx.tcx.type_of(self.def_id))
1318 } else {
1319 None
1320 };
476ff2be 1321
dc9dc135 1322 AssocTypeItem(bounds, ty.clean(cx))
476ff2be 1323 } else {
dfeec247
XL
1324 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1325 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1326 TypedefItem(
1327 Typedef {
1328 type_,
1329 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1330 item_type,
ff7c6d11 1331 },
dfeec247
XL
1332 true,
1333 )
ff7c6d11 1334 }
9346a6ac
AL
1335 }
1336 };
9346a6ac 1337
ff7c6d11
XL
1338 let visibility = match self.container {
1339 ty::ImplContainer(_) => self.vis.clean(cx),
e74abb32 1340 ty::TraitContainer(_) => Inherited,
ff7c6d11
XL
1341 };
1342
1a4d82fc 1343 Item {
8faf50e0 1344 name: Some(self.ident.name.clean(cx)),
ff7c6d11 1345 visibility,
1a4d82fc 1346 stability: get_stability(cx, self.def_id),
9cc50fc6 1347 deprecation: get_deprecation(cx, self.def_id),
1a4d82fc 1348 def_id: self.def_id,
416331ca 1349 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
476ff2be 1350 source: cx.tcx.def_span(self.def_id).clean(cx),
3b2f2976 1351 inner,
1a4d82fc
JJ
1352 }
1353 }
1354}
1355
dfeec247 1356impl Clean<Type> for hir::Ty<'_> {
532ac7d7 1357 fn clean(&self, cx: &DocContext<'_>) -> Type {
dfeec247 1358 use rustc_hir::*;
b7449926 1359
e74abb32 1360 match self.kind {
8faf50e0 1361 TyKind::Never => Never,
dfeec247 1362 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
8faf50e0 1363 TyKind::Rptr(ref l, ref m) => {
dfeec247
XL
1364 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1365 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
32a655c1 1366 }
8faf50e0
XL
1367 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1368 TyKind::Array(ref ty, ref length) => {
416331ca 1369 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1b1a35ee
XL
1370 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1371 // as we currently do not supply the parent generics to anonymous constants
1372 // but do allow `ConstKind::Param`.
1373 //
1374 // `const_eval_poly` tries to to first substitute generic parameters which
1375 // results in an ICE while manually constructing the constant and using `eval`
1376 // does nothing for `ConstKind::Param`.
1377 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1378 let param_env = cx.tcx.param_env(def_id);
1379 let length = print_const(cx, ct.eval(cx.tcx, param_env));
94b46f34 1380 Array(box ty.clean(cx), length)
dfeec247 1381 }
8faf50e0 1382 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
f035d41b 1383 TyKind::OpaqueDef(item_id, _) => {
dc9dc135 1384 let item = cx.tcx.hir().expect_item(item_id.id);
e74abb32 1385 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
0bf4aa26
XL
1386 ImplTrait(ty.bounds.clean(cx))
1387 } else {
1388 unreachable!()
1389 }
1390 }
8faf50e0 1391 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
48663c56
XL
1392 if let Res::Def(DefKind::TyParam, did) = path.res {
1393 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1394 return new_ty;
1395 }
e1599b0c 1396 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
0531ce1d
XL
1397 return ImplTrait(bounds);
1398 }
1399 }
1400
476ff2be 1401 let mut alias = None;
48663c56 1402 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
476ff2be 1403 // Substitute private type aliases
f9f354fc 1404 if let Some(def_id) = def_id.as_local() {
3dfed10e 1405 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
f9f354fc 1406 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
e74abb32 1407 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
476ff2be 1408 }
9e0c209e 1409 }
476ff2be
SL
1410 };
1411
416331ca 1412 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
b7449926 1413 let provided_params = &path.segments.last().expect("segments were empty");
0bf4aa26
XL
1414 let mut ty_substs = FxHashMap::default();
1415 let mut lt_substs = FxHashMap::default();
48663c56 1416 let mut ct_substs = FxHashMap::default();
dc9dc135
XL
1417 let generic_args = provided_params.generic_args();
1418 {
b7449926 1419 let mut indices: GenericParamCount = Default::default();
94b46f34 1420 for param in generics.params.iter() {
8faf50e0
XL
1421 match param.kind {
1422 hir::GenericParamKind::Lifetime { .. } => {
1423 let mut j = 0;
dfeec247
XL
1424 let lifetime =
1425 generic_args.args.iter().find_map(|arg| match arg {
9fa01778 1426 hir::GenericArg::Lifetime(lt) => {
8faf50e0
XL
1427 if indices.lifetimes == j {
1428 return Some(lt);
1429 }
1430 j += 1;
1431 None
1432 }
1433 _ => None,
dfeec247 1434 });
8faf50e0 1435 if let Some(lt) = lifetime.cloned() {
3dfed10e
XL
1436 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1437 let cleaned = if !lt.is_elided() {
1438 lt.clean(cx)
1439 } else {
1440 self::types::Lifetime::elided()
1441 };
1442 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
94b46f34
XL
1443 }
1444 indices.lifetimes += 1;
1445 }
8faf50e0 1446 hir::GenericParamKind::Type { ref default, .. } => {
dfeec247 1447 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
8faf50e0 1448 let mut j = 0;
dfeec247
XL
1449 let type_ =
1450 generic_args.args.iter().find_map(|arg| match arg {
9fa01778 1451 hir::GenericArg::Type(ty) => {
8faf50e0
XL
1452 if indices.types == j {
1453 return Some(ty);
1454 }
1455 j += 1;
1456 None
1457 }
1458 _ => None,
dfeec247 1459 });
dc9dc135 1460 if let Some(ty) = type_ {
f9f354fc 1461 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
dfeec247 1462 } else if let Some(default) = *default {
f9f354fc
XL
1463 ty_substs
1464 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
94b46f34
XL
1465 }
1466 indices.types += 1;
ea8adc8c 1467 }
9fa01778 1468 hir::GenericParamKind::Const { .. } => {
48663c56 1469 let const_param_def_id =
416331ca 1470 cx.tcx.hir().local_def_id(param.hir_id);
9fa01778 1471 let mut j = 0;
dfeec247
XL
1472 let const_ =
1473 generic_args.args.iter().find_map(|arg| match arg {
9fa01778
XL
1474 hir::GenericArg::Const(ct) => {
1475 if indices.consts == j {
1476 return Some(ct);
1477 }
1478 j += 1;
1479 None
1480 }
1481 _ => None,
dfeec247 1482 });
dc9dc135 1483 if let Some(ct) = const_ {
f9f354fc
XL
1484 ct_substs
1485 .insert(const_param_def_id.to_def_id(), ct.clean(cx));
9fa01778
XL
1486 }
1487 // FIXME(const_generics:defaults)
1488 indices.consts += 1;
1489 }
32a655c1 1490 }
9e0c209e 1491 }
dc9dc135 1492 }
48663c56 1493 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
5bcae85e 1494 }
532ac7d7 1495 resolve_type(cx, path.clean(cx), self.hir_id)
c34b1796 1496 }
8faf50e0 1497 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
dc9dc135
XL
1498 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1499 let trait_segments = &segments[..segments.len() - 1];
1500 let trait_path = self::Path {
1501 global: p.is_global(),
48663c56
XL
1502 res: Res::Def(
1503 DefKind::Trait,
1504 cx.tcx.associated_item(p.res.def_id()).container.id(),
1505 ),
dc9dc135 1506 segments: trait_segments.clean(cx),
9cc50fc6 1507 };
c34b1796 1508 Type::QPath {
b7449926 1509 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
476ff2be 1510 self_type: box qself.clean(cx),
dfeec247 1511 trait_: box resolve_type(cx, trait_path, self.hir_id),
476ff2be
SL
1512 }
1513 }
8faf50e0 1514 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
48663c56 1515 let mut res = Res::Err;
7cac9316 1516 let ty = hir_ty_to_ty(cx.tcx, self);
1b1a35ee 1517 if let ty::Projection(proj) = ty.kind() {
48663c56 1518 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
476ff2be 1519 }
dfeec247 1520 let trait_path = hir::Path { span: self.span, res, segments: &[] };
476ff2be 1521 Type::QPath {
8faf50e0 1522 name: segment.ident.name.clean(cx),
476ff2be 1523 self_type: box qself.clean(cx),
dfeec247 1524 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
c34b1796 1525 }
1a4d82fc 1526 }
3dfed10e
XL
1527 TyKind::Path(hir::QPath::LangItem(..)) => {
1528 bug!("clean: requiring documentation of lang item")
1529 }
8faf50e0 1530 TyKind::TraitObject(ref bounds, ref lifetime) => {
32a655c1 1531 match bounds[0].clean(cx).trait_ {
532ac7d7 1532 ResolvedPath { path, param_names: None, did, is_generic } => {
dfeec247
XL
1533 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1534 .iter()
1535 .map(|bound| {
1536 self::GenericBound::TraitBound(
1537 bound.clean(cx),
1538 hir::TraitBoundModifier::None,
1539 )
1540 })
1541 .collect();
32a655c1 1542 if !lifetime.is_elided() {
8faf50e0 1543 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
62682a34 1544 }
dfeec247 1545 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1a4d82fc 1546 }
dc9dc135 1547 _ => Infer, // shouldn't happen
1a4d82fc
JJ
1548 }
1549 }
8faf50e0
XL
1550 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1551 TyKind::Infer | TyKind::Err => Infer,
e74abb32 1552 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1a4d82fc
JJ
1553 }
1554 }
1555}
1556
ea8adc8c 1557impl<'tcx> Clean<Type> for Ty<'tcx> {
532ac7d7 1558 fn clean(&self, cx: &DocContext<'_>) -> Type {
48663c56 1559 debug!("cleaning type: {:?}", self);
1b1a35ee 1560 match *self.kind() {
b7449926
XL
1561 ty::Never => Never,
1562 ty::Bool => Primitive(PrimitiveType::Bool),
1563 ty::Char => Primitive(PrimitiveType::Char),
1564 ty::Int(int_ty) => Primitive(int_ty.into()),
1565 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1566 ty::Float(float_ty) => Primitive(float_ty.into()),
1567 ty::Str => Primitive(PrimitiveType::Str),
1568 ty::Slice(ty) => Slice(box ty.clean(cx)),
1569 ty::Array(ty, n) => {
dc9dc135 1570 let mut n = cx.tcx.lift(&n).expect("array lift failed");
dfeec247 1571 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
0531ce1d 1572 let n = print_const(cx, n);
ea8adc8c
XL
1573 Array(box ty.clean(cx), n)
1574 }
dfeec247
XL
1575 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1576 ty::Ref(r, ty, mutbl) => {
1577 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1578 }
1579 ty::FnDef(..) | ty::FnPtr(_) => {
b7449926 1580 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
041b39d2 1581 let sig = ty.fn_sig(cx.tcx);
f9f354fc 1582 let def_id = DefId::local(CRATE_DEF_INDEX);
041b39d2
XL
1583 BareFunction(box BareFunctionDecl {
1584 unsafety: sig.unsafety(),
ff7c6d11 1585 generic_params: Vec::new(),
f9f354fc 1586 decl: (def_id, sig).clean(cx),
041b39d2
XL
1587 abi: sig.abi(),
1588 })
1589 }
b7449926 1590 ty::Adt(def, substs) => {
e9174d1e 1591 let did = def.did;
9e0c209e 1592 let kind = match def.adt_kind() {
c30ab7b3
SL
1593 AdtKind::Struct => TypeKind::Struct,
1594 AdtKind::Union => TypeKind::Union,
1595 AdtKind::Enum => TypeKind::Enum,
1a4d82fc 1596 };
92a42be0 1597 inline::record_extern_fqn(cx, did, kind);
e1599b0c 1598 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
dfeec247 1599 ResolvedPath { path, param_names: None, did, is_generic: false }
1a4d82fc 1600 }
b7449926 1601 ty::Foreign(did) => {
abe05a73 1602 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
dfeec247
XL
1603 let path = external_path(
1604 cx,
1605 cx.tcx.item_name(did),
1606 None,
1607 false,
1608 vec![],
1609 InternalSubsts::empty(),
1610 );
1611 ResolvedPath { path, param_names: None, did, is_generic: false }
abe05a73 1612 }
b7449926 1613 ty::Dynamic(ref obj, ref reg) => {
0731742a
XL
1614 // HACK: pick the first `did` as the `did` of the trait object. Someone
1615 // might want to implement "native" support for marker-trait-only
1616 // trait objects.
1617 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
dfeec247
XL
1618 let did = dids
1619 .next()
1620 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
0731742a
XL
1621 let substs = match obj.principal() {
1622 Some(principal) => principal.skip_binder().substs,
1623 // marker traits have no substs.
dfeec247 1624 _ => cx.tcx.intern_substs(&[]),
0731742a
XL
1625 };
1626
0bf4aa26
XL
1627 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1628
532ac7d7 1629 let mut param_names = vec![];
f9f354fc
XL
1630 if let Some(b) = reg.clean(cx) {
1631 param_names.push(GenericBound::Outlives(b));
1632 }
0731742a 1633 for did in dids {
0bf4aa26 1634 let empty = cx.tcx.intern_substs(&[]);
dfeec247
XL
1635 let path =
1636 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
476ff2be 1637 inline::record_extern_fqn(cx, did, TypeKind::Trait);
dfeec247
XL
1638 let bound = GenericBound::TraitBound(
1639 PolyTrait {
1640 trait_: ResolvedPath {
1641 path,
1642 param_names: None,
1643 did,
1644 is_generic: false,
1645 },
1646 generic_params: Vec::new(),
0bf4aa26 1647 },
dfeec247
XL
1648 hir::TraitBoundModifier::None,
1649 );
532ac7d7 1650 param_names.push(bound);
0bf4aa26 1651 }
476ff2be 1652
0bf4aa26
XL
1653 let mut bindings = vec![];
1654 for pb in obj.projection_bounds() {
1655 bindings.push(TypeBinding {
1656 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
dfeec247 1657 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
0bf4aa26
XL
1658 });
1659 }
9e0c209e 1660
dfeec247
XL
1661 let path =
1662 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1663 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1a4d82fc 1664 }
48663c56
XL
1665 ty::Tuple(ref t) => {
1666 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1667 }
1a4d82fc 1668
b7449926 1669 ty::Projection(ref data) => data.clean(cx),
1a4d82fc 1670
e1599b0c
XL
1671 ty::Param(ref p) => {
1672 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1673 ImplTrait(bounds)
1674 } else {
1675 Generic(p.name.to_string())
1676 }
1677 }
1a4d82fc 1678
b7449926 1679 ty::Opaque(def_id, substs) => {
5bcae85e
SL
1680 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1681 // by looking up the projections associated with the def_id.
532ac7d7 1682 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
b7449926 1683 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
7cac9316 1684 let bounds = predicates_of.instantiate(cx.tcx, substs);
0531ce1d
XL
1685 let mut regions = vec![];
1686 let mut has_sized = false;
dfeec247
XL
1687 let mut bounds = bounds
1688 .predicates
1689 .iter()
1690 .filter_map(|predicate| {
3dfed10e
XL
1691 // Note: The substs of opaque types can contain unbound variables,
1692 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1693 let trait_ref = match predicate.bound_atom(cx.tcx).skip_binder() {
1694 ty::PredicateAtom::Trait(tr, _constness) => {
1695 ty::Binder::bind(tr.trait_ref)
1696 }
1697 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1698 if let Some(r) = reg.clean(cx) {
1699 regions.push(GenericBound::Outlives(r));
1700 }
1701 return None;
f9f354fc 1702 }
3dfed10e 1703 _ => return None,
dfeec247 1704 };
0531ce1d 1705
dfeec247
XL
1706 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1707 if trait_ref.def_id() == sized {
1708 has_sized = true;
1709 return None;
0531ce1d 1710 }
0531ce1d 1711 }
0531ce1d 1712
ba9703b0 1713 let bounds: Vec<_> = bounds
dfeec247
XL
1714 .predicates
1715 .iter()
1716 .filter_map(|pred| {
3dfed10e
XL
1717 if let ty::PredicateAtom::Projection(proj) =
1718 pred.bound_atom(cx.tcx).skip_binder()
1719 {
dfeec247 1720 if proj.projection_ty.trait_ref(cx.tcx)
f035d41b 1721 == trait_ref.skip_binder()
dfeec247
XL
1722 {
1723 Some(TypeBinding {
1724 name: cx
1725 .tcx
1726 .associated_item(proj.projection_ty.item_def_id)
1727 .ident
1728 .name
1729 .clean(cx),
1730 kind: TypeBindingKind::Equality {
1731 ty: proj.ty.clean(cx),
1732 },
1733 })
1734 } else {
1735 None
1736 }
1737 } else {
1738 None
1739 }
1740 })
1741 .collect();
1742
ba9703b0 1743 Some((trait_ref, &bounds[..]).clean(cx))
dfeec247
XL
1744 })
1745 .collect::<Vec<_>>();
0531ce1d
XL
1746 bounds.extend(regions);
1747 if !has_sized && !bounds.is_empty() {
8faf50e0 1748 bounds.insert(0, GenericBound::maybe_sized(cx));
0531ce1d
XL
1749 }
1750 ImplTrait(bounds)
5bcae85e
SL
1751 }
1752
b7449926 1753 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1a4d82fc 1754
a1dfa0c6
XL
1755 ty::Bound(..) => panic!("Bound"),
1756 ty::Placeholder(..) => panic!("Placeholder"),
b7449926
XL
1757 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1758 ty::Infer(..) => panic!("Infer"),
f035d41b 1759 ty::Error(_) => panic!("Error"),
1a4d82fc
JJ
1760 }
1761 }
1762}
1763
532ac7d7
XL
1764impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1765 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1766 Constant {
1767 type_: self.ty.clean(cx),
dc9dc135 1768 expr: format!("{}", self),
dfeec247
XL
1769 value: None,
1770 is_literal: false,
532ac7d7
XL
1771 }
1772 }
1773}
1774
dfeec247 1775impl Clean<Item> for hir::StructField<'_> {
532ac7d7 1776 fn clean(&self, cx: &DocContext<'_>) -> Item {
416331ca 1777 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
532ac7d7 1778
1a4d82fc 1779 Item {
94b46f34 1780 name: Some(self.ident.name).clean(cx),
54a0048b 1781 attrs: self.attrs.clean(cx),
1a4d82fc 1782 source: self.span.clean(cx),
54a0048b 1783 visibility: self.vis.clean(cx),
f9f354fc
XL
1784 stability: get_stability(cx, local_did.to_def_id()),
1785 deprecation: get_deprecation(cx, local_did.to_def_id()),
1786 def_id: local_did.to_def_id(),
54a0048b 1787 inner: StructFieldItem(self.ty.clean(cx)),
1a4d82fc
JJ
1788 }
1789 }
1790}
1791
dc9dc135 1792impl Clean<Item> for ty::FieldDef {
532ac7d7 1793 fn clean(&self, cx: &DocContext<'_>) -> Item {
1a4d82fc 1794 Item {
94b46f34 1795 name: Some(self.ident.name).clean(cx),
476ff2be
SL
1796 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1797 source: cx.tcx.def_span(self.did).clean(cx),
54a0048b 1798 visibility: self.vis.clean(cx),
e9174d1e 1799 stability: get_stability(cx, self.did),
9cc50fc6 1800 deprecation: get_deprecation(cx, self.did),
e9174d1e 1801 def_id: self.did,
7cac9316 1802 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1a4d82fc
JJ
1803 }
1804 }
1805}
1806
dfeec247 1807impl Clean<Visibility> for hir::Visibility<'_> {
e74abb32
XL
1808 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1809 match self.node {
8faf50e0
XL
1810 hir::VisibilityKind::Public => Visibility::Public,
1811 hir::VisibilityKind::Inherited => Visibility::Inherited,
1812 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1813 hir::VisibilityKind::Restricted { ref path, .. } => {
94b46f34 1814 let path = path.clean(cx);
48663c56 1815 let did = register_res(cx, path.res);
94b46f34
XL
1816 Visibility::Restricted(did, path)
1817 }
e74abb32 1818 }
54a0048b
SL
1819 }
1820}
1821
e74abb32
XL
1822impl Clean<Visibility> for ty::Visibility {
1823 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1824 if *self == ty::Visibility::Public { Public } else { Inherited }
1a4d82fc
JJ
1825 }
1826}
1827
dc9dc135 1828impl Clean<Item> for doctree::Struct<'_> {
532ac7d7 1829 fn clean(&self, cx: &DocContext<'_>) -> Item {
0bf4aa26
XL
1830 Item {
1831 name: Some(self.name.clean(cx)),
1a4d82fc 1832 attrs: self.attrs.clean(cx),
1b1a35ee 1833 source: self.span.clean(cx),
f9f354fc 1834 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1a4d82fc 1835 visibility: self.vis.clean(cx),
416331ca
XL
1836 stability: cx.stability(self.id).clean(cx),
1837 deprecation: cx.deprecation(self.id).clean(cx),
1a4d82fc
JJ
1838 inner: StructItem(Struct {
1839 struct_type: self.struct_type,
1840 generics: self.generics.clean(cx),
1841 fields: self.fields.clean(cx),
1842 fields_stripped: false,
1843 }),
0bf4aa26 1844 }
1a4d82fc
JJ
1845 }
1846}
1847
dc9dc135 1848impl Clean<Item> for doctree::Union<'_> {
532ac7d7 1849 fn clean(&self, cx: &DocContext<'_>) -> Item {
0bf4aa26
XL
1850 Item {
1851 name: Some(self.name.clean(cx)),
9e0c209e 1852 attrs: self.attrs.clean(cx),
1b1a35ee 1853 source: self.span.clean(cx),
f9f354fc 1854 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
9e0c209e 1855 visibility: self.vis.clean(cx),
416331ca
XL
1856 stability: cx.stability(self.id).clean(cx),
1857 deprecation: cx.deprecation(self.id).clean(cx),
9e0c209e
SL
1858 inner: UnionItem(Union {
1859 struct_type: self.struct_type,
1860 generics: self.generics.clean(cx),
1861 fields: self.fields.clean(cx),
1862 fields_stripped: false,
1863 }),
0bf4aa26 1864 }
9e0c209e
SL
1865 }
1866}
1867
dfeec247 1868impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
532ac7d7 1869 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1a4d82fc
JJ
1870 VariantStruct {
1871 struct_type: doctree::struct_type_from_def(self),
b039eaaf 1872 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1a4d82fc
JJ
1873 fields_stripped: false,
1874 }
1875 }
1876}
1877
dc9dc135 1878impl Clean<Item> for doctree::Enum<'_> {
532ac7d7 1879 fn clean(&self, cx: &DocContext<'_>) -> Item {
0bf4aa26
XL
1880 Item {
1881 name: Some(self.name.clean(cx)),
1a4d82fc 1882 attrs: self.attrs.clean(cx),
1b1a35ee 1883 source: self.span.clean(cx),
f9f354fc 1884 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1a4d82fc 1885 visibility: self.vis.clean(cx),
416331ca
XL
1886 stability: cx.stability(self.id).clean(cx),
1887 deprecation: cx.deprecation(self.id).clean(cx),
1a4d82fc 1888 inner: EnumItem(Enum {
a1dfa0c6 1889 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1a4d82fc
JJ
1890 generics: self.generics.clean(cx),
1891 variants_stripped: false,
1892 }),
0bf4aa26 1893 }
1a4d82fc
JJ
1894 }
1895}
1896
dc9dc135 1897impl Clean<Item> for doctree::Variant<'_> {
532ac7d7 1898 fn clean(&self, cx: &DocContext<'_>) -> Item {
1a4d82fc
JJ
1899 Item {
1900 name: Some(self.name.clean(cx)),
1901 attrs: self.attrs.clean(cx),
1b1a35ee 1902 source: self.span.clean(cx),
e74abb32 1903 visibility: Inherited,
416331ca
XL
1904 stability: cx.stability(self.id).clean(cx),
1905 deprecation: cx.deprecation(self.id).clean(cx),
f9f354fc 1906 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
dfeec247 1907 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1a4d82fc
JJ
1908 }
1909 }
1910}
1911
dc9dc135 1912impl Clean<Item> for ty::VariantDef {
532ac7d7 1913 fn clean(&self, cx: &DocContext<'_>) -> Item {
c30ab7b3
SL
1914 let kind = match self.ctor_kind {
1915 CtorKind::Const => VariantKind::CLike,
dfeec247
XL
1916 CtorKind::Fn => VariantKind::Tuple(
1917 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1918 ),
1919 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1920 struct_type: doctree::Plain,
1921 fields_stripped: false,
1922 fields: self
1923 .fields
1924 .iter()
1925 .map(|field| Item {
1926 source: cx.tcx.def_span(field.did).clean(cx),
1927 name: Some(field.ident.name.clean(cx)),
1928 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1929 visibility: field.vis.clean(cx),
1930 def_id: field.did,
1931 stability: get_stability(cx, field.did),
1932 deprecation: get_deprecation(cx, field.did),
1933 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1934 })
1935 .collect(),
1936 }),
1a4d82fc
JJ
1937 };
1938 Item {
0731742a 1939 name: Some(self.ident.clean(cx)),
416331ca 1940 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
532ac7d7 1941 source: cx.tcx.def_span(self.def_id).clean(cx),
e74abb32 1942 visibility: Inherited,
532ac7d7 1943 def_id: self.def_id,
a1dfa0c6 1944 inner: VariantItem(Variant { kind }),
532ac7d7
XL
1945 stability: get_stability(cx, self.def_id),
1946 deprecation: get_deprecation(cx, self.def_id),
1a4d82fc
JJ
1947 }
1948 }
1949}
1950
dfeec247 1951impl Clean<VariantKind> for hir::VariantData<'_> {
532ac7d7
XL
1952 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1953 match self {
1954 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
dfeec247
XL
1955 hir::VariantData::Tuple(..) => {
1956 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1957 }
532ac7d7 1958 hir::VariantData::Unit(..) => VariantKind::CLike,
c30ab7b3 1959 }
1a4d82fc
JJ
1960 }
1961}
1962
dfeec247 1963impl Clean<Span> for rustc_span::Span {
532ac7d7 1964 fn clean(&self, cx: &DocContext<'_>) -> Span {
8faf50e0 1965 if self.is_dummy() {
c1a9b12d
SL
1966 return Span::empty();
1967 }
1968
74b04a01
XL
1969 let sm = cx.sess().source_map();
1970 let filename = sm.span_to_filename(*self);
1971 let lo = sm.lookup_char_pos(self.lo());
1972 let hi = sm.lookup_char_pos(self.hi());
1a4d82fc 1973 Span {
ff7c6d11 1974 filename,
ba9703b0 1975 cnum: lo.file.cnum,
1a4d82fc 1976 loline: lo.line,
85aaf69f 1977 locol: lo.col.to_usize(),
1a4d82fc 1978 hiline: hi.line,
85aaf69f 1979 hicol: hi.col.to_usize(),
48663c56 1980 original: *self,
1a4d82fc
JJ
1981 }
1982 }
1983}
1984
dfeec247 1985impl Clean<Path> for hir::Path<'_> {
532ac7d7 1986 fn clean(&self, cx: &DocContext<'_>) -> Path {
1a4d82fc 1987 Path {
32a655c1 1988 global: self.is_global(),
48663c56 1989 res: self.res,
32a655c1 1990 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1a4d82fc
JJ
1991 }
1992 }
1993}
1994
dfeec247 1995impl Clean<GenericArgs> for hir::GenericArgs<'_> {
532ac7d7 1996 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
3b2f2976 1997 if self.parenthesized {
dc9dc135 1998 let output = self.bindings[0].ty().clean(cx);
8faf50e0 1999 GenericArgs::Parenthesized {
3b2f2976 2000 inputs: self.inputs().clean(cx),
dfeec247 2001 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1a4d82fc 2002 }
3b2f2976 2003 } else {
8faf50e0 2004 GenericArgs::AngleBracketed {
dfeec247
XL
2005 args: self
2006 .args
2007 .iter()
3dfed10e
XL
2008 .map(|arg| match arg {
2009 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
2010 GenericArg::Lifetime(lt.clean(cx))
dfeec247 2011 }
3dfed10e
XL
2012 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2013 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
2014 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
dfeec247
XL
2015 })
2016 .collect(),
3b2f2976 2017 bindings: self.bindings.clean(cx),
1a4d82fc
JJ
2018 }
2019 }
2020 }
2021}
2022
dfeec247 2023impl Clean<PathSegment> for hir::PathSegment<'_> {
532ac7d7 2024 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
dfeec247 2025 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1a4d82fc
JJ
2026 }
2027}
2028
0731742a
XL
2029impl Clean<String> for Ident {
2030 #[inline]
532ac7d7 2031 fn clean(&self, cx: &DocContext<'_>) -> String {
0731742a
XL
2032 self.name.clean(cx)
2033 }
2034}
2035
f9f354fc 2036impl Clean<String> for Symbol {
0731742a 2037 #[inline]
532ac7d7 2038 fn clean(&self, _: &DocContext<'_>) -> String {
c1a9b12d 2039 self.to_string()
1a4d82fc
JJ
2040 }
2041}
2042
dc9dc135 2043impl Clean<Item> for doctree::Typedef<'_> {
532ac7d7 2044 fn clean(&self, cx: &DocContext<'_>) -> Item {
dfeec247
XL
2045 let type_ = self.ty.clean(cx);
2046 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1a4d82fc
JJ
2047 Item {
2048 name: Some(self.name.clean(cx)),
2049 attrs: self.attrs.clean(cx),
1b1a35ee 2050 source: self.span.clean(cx),
f9f354fc 2051 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1a4d82fc 2052 visibility: self.vis.clean(cx),
416331ca
XL
2053 stability: cx.stability(self.id).clean(cx),
2054 deprecation: cx.deprecation(self.id).clean(cx),
dfeec247 2055 inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
1a4d82fc
JJ
2056 }
2057 }
2058}
2059
416331ca 2060impl Clean<Item> for doctree::OpaqueTy<'_> {
532ac7d7 2061 fn clean(&self, cx: &DocContext<'_>) -> Item {
8faf50e0
XL
2062 Item {
2063 name: Some(self.name.clean(cx)),
2064 attrs: self.attrs.clean(cx),
1b1a35ee 2065 source: self.span.clean(cx),
f9f354fc 2066 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
8faf50e0 2067 visibility: self.vis.clean(cx),
416331ca
XL
2068 stability: cx.stability(self.id).clean(cx),
2069 deprecation: cx.deprecation(self.id).clean(cx),
dfeec247
XL
2070 inner: OpaqueTyItem(
2071 OpaqueTy {
2072 bounds: self.opaque_ty.bounds.clean(cx),
2073 generics: self.opaque_ty.generics.clean(cx),
2074 },
2075 false,
2076 ),
8faf50e0
XL
2077 }
2078 }
2079}
2080
dfeec247 2081impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
532ac7d7 2082 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
0531ce1d 2083 let (generic_params, decl) = enter_impl_trait(cx, || {
e1599b0c 2084 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
0531ce1d 2085 });
dfeec247 2086 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1a4d82fc
JJ
2087 }
2088}
2089
dc9dc135 2090impl Clean<Item> for doctree::Static<'_> {
532ac7d7 2091 fn clean(&self, cx: &DocContext<'_>) -> Item {
1a4d82fc
JJ
2092 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2093 Item {
2094 name: Some(self.name.clean(cx)),
2095 attrs: self.attrs.clean(cx),
1b1a35ee 2096 source: self.span.clean(cx),
f9f354fc 2097 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1a4d82fc 2098 visibility: self.vis.clean(cx),
416331ca
XL
2099 stability: cx.stability(self.id).clean(cx),
2100 deprecation: cx.deprecation(self.id).clean(cx),
1a4d82fc
JJ
2101 inner: StaticItem(Static {
2102 type_: self.type_.clean(cx),
dfeec247 2103 mutability: self.mutability,
32a655c1 2104 expr: print_const_expr(cx, self.expr),
1a4d82fc
JJ
2105 }),
2106 }
2107 }
2108}
2109
dc9dc135 2110impl Clean<Item> for doctree::Constant<'_> {
532ac7d7 2111 fn clean(&self, cx: &DocContext<'_>) -> Item {
dfeec247
XL
2112 let def_id = cx.tcx.hir().local_def_id(self.id);
2113
1a4d82fc
JJ
2114 Item {
2115 name: Some(self.name.clean(cx)),
2116 attrs: self.attrs.clean(cx),
1b1a35ee 2117 source: self.span.clean(cx),
f9f354fc 2118 def_id: def_id.to_def_id(),
1a4d82fc 2119 visibility: self.vis.clean(cx),
416331ca
XL
2120 stability: cx.stability(self.id).clean(cx),
2121 deprecation: cx.deprecation(self.id).clean(cx),
1a4d82fc
JJ
2122 inner: ConstantItem(Constant {
2123 type_: self.type_.clean(cx),
32a655c1 2124 expr: print_const_expr(cx, self.expr),
f9f354fc 2125 value: print_evaluated_const(cx, def_id.to_def_id()),
dfeec247 2126 is_literal: is_literal_expr(cx, self.expr.hir_id),
1a4d82fc
JJ
2127 }),
2128 }
2129 }
2130}
2131
e74abb32 2132impl Clean<ImplPolarity> for ty::ImplPolarity {
532ac7d7 2133 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
85aaf69f 2134 match self {
e74abb32
XL
2135 &ty::ImplPolarity::Positive |
2136 // FIXME: do we want to do something else here?
2137 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2138 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
85aaf69f
SL
2139 }
2140 }
2141}
2142
dc9dc135 2143impl Clean<Vec<Item>> for doctree::Impl<'_> {
532ac7d7 2144 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
d9579d0f
AL
2145 let mut ret = Vec::new();
2146 let trait_ = self.trait_.clean(cx);
dc9dc135 2147 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
e74abb32 2148 let def_id = cx.tcx.hir().local_def_id(self.id);
d9579d0f
AL
2149
2150 // If this impl block is an implementation of the Deref trait, then we
2151 // need to try inlining the target's inherent impl blocks as well.
ea8adc8c 2152 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
54a0048b 2153 build_deref_target_impls(cx, &items, &mut ret);
d9579d0f
AL
2154 }
2155
dfeec247
XL
2156 let provided: FxHashSet<String> = trait_
2157 .def_id()
2158 .map(|did| {
74b04a01 2159 cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect()
dfeec247
XL
2160 })
2161 .unwrap_or_default();
54a0048b 2162
dfeec247
XL
2163 let for_ = self.for_.clean(cx);
2164 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
f9f354fc 2165 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
dfeec247
XL
2166 _ => None,
2167 });
2168 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
1a4d82fc
JJ
2169 name: None,
2170 attrs: self.attrs.clean(cx),
1b1a35ee 2171 source: self.span.clean(cx),
f9f354fc 2172 def_id: def_id.to_def_id(),
1a4d82fc 2173 visibility: self.vis.clean(cx),
416331ca
XL
2174 stability: cx.stability(self.id).clean(cx),
2175 deprecation: cx.deprecation(self.id).clean(cx),
1a4d82fc 2176 inner: ImplItem(Impl {
c34b1796 2177 unsafety: self.unsafety,
1a4d82fc 2178 generics: self.generics.clean(cx),
dfeec247 2179 provided_trait_methods: provided.clone(),
3b2f2976 2180 trait_,
dfeec247 2181 for_,
3b2f2976 2182 items,
e74abb32 2183 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
0531ce1d 2184 synthetic: false,
8faf50e0 2185 blanket_impl: None,
dfeec247
XL
2186 }),
2187 };
2188 if let Some(type_alias) = type_alias {
2189 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2190 }
2191 ret.push(make_item(trait_, for_, items));
54a0048b 2192 ret
d9579d0f
AL
2193 }
2194}
2195
dc9dc135 2196impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
532ac7d7 2197 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
dfeec247
XL
2198 let please_inline = self.vis.node.is_pub()
2199 && self.attrs.iter().any(|a| {
3dfed10e 2200 a.has_name(sym::doc)
dfeec247
XL
2201 && match a.meta_item_list() {
2202 Some(l) => attr::list_contains_name(&l, sym::inline),
2203 None => false,
2204 }
2205 });
0731742a
XL
2206
2207 if please_inline {
2208 let mut visited = FxHashSet::default();
2209
dfeec247 2210 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
0731742a 2211
ba9703b0
XL
2212 if let Some(items) =
2213 inline::try_inline(cx, res, self.name, Some(self.attrs), &mut visited)
2214 {
0731742a
XL
2215 return items;
2216 }
2217 }
2218
2219 vec![Item {
85aaf69f
SL
2220 name: None,
2221 attrs: self.attrs.clean(cx),
1b1a35ee 2222 source: self.span.clean(cx),
a7813a04 2223 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
85aaf69f
SL
2224 visibility: self.vis.clean(cx),
2225 stability: None,
9cc50fc6 2226 deprecation: None,
dfeec247 2227 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
0731742a 2228 }]
85aaf69f 2229 }
1a4d82fc
JJ
2230}
2231
dc9dc135 2232impl Clean<Vec<Item>> for doctree::Import<'_> {
532ac7d7 2233 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1a4d82fc
JJ
2234 // We consider inlining the documentation of `pub use` statements, but we
2235 // forcefully don't inline if this is not public or if the
2236 // #[doc(no_inline)] attribute is present.
3157f602 2237 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
dfeec247
XL
2238 let mut denied = !self.vis.node.is_pub()
2239 || self.attrs.iter().any(|a| {
3dfed10e 2240 a.has_name(sym::doc)
dfeec247
XL
2241 && match a.meta_item_list() {
2242 Some(l) => {
2243 attr::list_contains_name(&l, sym::no_inline)
2244 || attr::list_contains_name(&l, sym::hidden)
2245 }
2246 None => false,
2247 }
2248 });
13cf67c4
XL
2249 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2250 // crate in Rust 2018+
48663c56 2251 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
476ff2be
SL
2252 let path = self.path.clean(cx);
2253 let inner = if self.glob {
94b46f34 2254 if !denied {
0bf4aa26 2255 let mut visited = FxHashSet::default();
48663c56 2256 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
94b46f34
XL
2257 return items;
2258 }
2259 }
2260
476ff2be
SL
2261 Import::Glob(resolve_use_source(cx, path))
2262 } else {
2263 let name = self.name;
13cf67c4 2264 if !please_inline {
ba9703b0
XL
2265 if let Res::Def(DefKind::Mod, did) = path.res {
2266 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2267 // if we're `pub use`ing an extern crate root, don't inline it unless we
2268 // were specifically asked for it
2269 denied = true;
13cf67c4 2270 }
13cf67c4
XL
2271 }
2272 }
476ff2be 2273 if !denied {
0bf4aa26 2274 let mut visited = FxHashSet::default();
ba9703b0
XL
2275 if let Some(items) =
2276 inline::try_inline(cx, path.res, name, Some(self.attrs), &mut visited)
2277 {
476ff2be 2278 return items;
85aaf69f 2279 }
1a4d82fc 2280 }
476ff2be 2281 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
85aaf69f 2282 };
8faf50e0 2283
476ff2be 2284 vec![Item {
85aaf69f
SL
2285 name: None,
2286 attrs: self.attrs.clean(cx),
1b1a35ee 2287 source: self.span.clean(cx),
f9f354fc 2288 def_id: DefId::local(CRATE_DEF_INDEX),
85aaf69f
SL
2289 visibility: self.vis.clean(cx),
2290 stability: None,
9cc50fc6 2291 deprecation: None,
dfeec247 2292 inner: ImportItem(inner),
476ff2be 2293 }]
1a4d82fc
JJ
2294 }
2295}
2296
dc9dc135 2297impl Clean<Item> for doctree::ForeignItem<'_> {
532ac7d7 2298 fn clean(&self, cx: &DocContext<'_>) -> Item {
dc9dc135 2299 let inner = match self.kind {
8faf50e0 2300 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
dc9dc135 2301 let abi = cx.tcx.hir().get_foreign_abi(self.id);
dfeec247
XL
2302 let (generics, decl) =
2303 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
532ac7d7 2304 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1a4d82fc 2305 ForeignFunctionItem(Function {
0531ce1d
XL
2306 decl,
2307 generics,
8faf50e0
XL
2308 header: hir::FnHeader {
2309 unsafety: hir::Unsafety::Unsafe,
dc9dc135 2310 abi,
8faf50e0
XL
2311 constness: hir::Constness::NotConst,
2312 asyncness: hir::IsAsync::NotAsync,
2313 },
532ac7d7
XL
2314 all_types,
2315 ret_types,
1a4d82fc
JJ
2316 })
2317 }
dfeec247
XL
2318 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2319 type_: ty.clean(cx),
2320 mutability: *mutbl,
2321 expr: String::new(),
2322 }),
2323 hir::ForeignItemKind::Type => ForeignTypeItem,
1a4d82fc 2324 };
8faf50e0 2325
1a4d82fc 2326 Item {
dc9dc135 2327 name: Some(self.name.clean(cx)),
1a4d82fc 2328 attrs: self.attrs.clean(cx),
1b1a35ee 2329 source: self.span.clean(cx),
f9f354fc 2330 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1a4d82fc 2331 visibility: self.vis.clean(cx),
416331ca
XL
2332 stability: cx.stability(self.id).clean(cx),
2333 deprecation: cx.deprecation(self.id).clean(cx),
3b2f2976 2334 inner,
1a4d82fc
JJ
2335 }
2336 }
2337}
2338
dc9dc135 2339impl Clean<Item> for doctree::Macro<'_> {
532ac7d7 2340 fn clean(&self, cx: &DocContext<'_>) -> Item {
9e0c209e 2341 let name = self.name.clean(cx);
1a4d82fc 2342 Item {
92a42be0 2343 name: Some(name.clone()),
1a4d82fc 2344 attrs: self.attrs.clean(cx),
1b1a35ee 2345 source: self.span.clean(cx),
e74abb32 2346 visibility: Public,
416331ca
XL
2347 stability: cx.stability(self.hid).clean(cx),
2348 deprecation: cx.deprecation(self.hid).clean(cx),
32a655c1 2349 def_id: self.def_id,
1a4d82fc 2350 inner: MacroItem(Macro {
dfeec247
XL
2351 source: format!(
2352 "macro_rules! {} {{\n{}}}",
2353 name,
2354 self.matchers
2355 .iter()
2356 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2357 .collect::<String>()
2358 ),
d9579d0f 2359 imported_from: self.imported_from.clean(cx),
1a4d82fc
JJ
2360 }),
2361 }
2362 }
2363}
2364
dc9dc135 2365impl Clean<Item> for doctree::ProcMacro<'_> {
532ac7d7 2366 fn clean(&self, cx: &DocContext<'_>) -> Item {
0bf4aa26
XL
2367 Item {
2368 name: Some(self.name.clean(cx)),
2369 attrs: self.attrs.clean(cx),
1b1a35ee 2370 source: self.span.clean(cx),
e74abb32 2371 visibility: Public,
416331ca
XL
2372 stability: cx.stability(self.id).clean(cx),
2373 deprecation: cx.deprecation(self.id).clean(cx),
f9f354fc 2374 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
dfeec247 2375 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
0bf4aa26
XL
2376 }
2377 }
2378}
2379
1a4d82fc 2380impl Clean<Stability> for attr::Stability {
532ac7d7 2381 fn clean(&self, _: &DocContext<'_>) -> Stability {
1a4d82fc 2382 Stability {
b039eaaf 2383 level: stability::StabilityLevel::from_attr_level(&self.level),
3dfed10e 2384 feature: self.feature.to_string(),
b039eaaf 2385 since: match self.level {
dfeec247 2386 attr::Stable { ref since } => since.to_string(),
b7449926 2387 _ => String::new(),
b039eaaf 2388 },
476ff2be 2389 unstable_reason: match self.level {
0731742a
XL
2390 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2391 _ => None,
b039eaaf
SL
2392 },
2393 issue: match self.level {
dfeec247 2394 attr::Unstable { issue, .. } => issue,
b039eaaf 2395 _ => None,
dfeec247 2396 },
1a4d82fc
JJ
2397 }
2398 }
2399}
2400
9cc50fc6 2401impl Clean<Deprecation> for attr::Deprecation {
532ac7d7 2402 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
9cc50fc6 2403 Deprecation {
0731742a
XL
2404 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2405 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
3dfed10e 2406 is_since_rustc_version: self.is_since_rustc_version,
9cc50fc6
SL
2407 }
2408 }
2409}
2410
dfeec247 2411impl Clean<TypeBinding> for hir::TypeBinding<'_> {
532ac7d7 2412 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
dfeec247 2413 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
dc9dc135
XL
2414 }
2415}
2416
dfeec247 2417impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
dc9dc135
XL
2418 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2419 match *self {
dfeec247
XL
2420 hir::TypeBindingKind::Equality { ref ty } => {
2421 TypeBindingKind::Equality { ty: ty.clean(cx) }
2422 }
74b04a01
XL
2423 hir::TypeBindingKind::Constraint { ref bounds } => {
2424 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2425 }
1a4d82fc
JJ
2426 }
2427 }
2428}
0531ce1d 2429
0531ce1d 2430enum SimpleBound {
8faf50e0
XL
2431 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2432 Outlives(Lifetime),
0531ce1d
XL
2433}
2434
8faf50e0
XL
2435impl From<GenericBound> for SimpleBound {
2436 fn from(bound: GenericBound) -> Self {
0531ce1d 2437 match bound.clone() {
8faf50e0
XL
2438 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2439 GenericBound::TraitBound(t, mod_) => match t.trait_ {
dfeec247
XL
2440 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2441 path.segments,
ba9703b0
XL
2442 param_names.map_or_else(Vec::new, |v| {
2443 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2444 }),
dfeec247
XL
2445 t.generic_params,
2446 mod_,
2447 ),
0531ce1d 2448 _ => panic!("Unexpected bound {:?}", bound),
dfeec247 2449 },
0531ce1d
XL
2450 }
2451 }
2452}