1 use crate::clean::auto_trait::AutoTraitFinder;
2 use crate::clean::blanket_impl::BlanketImplFinder;
4 inline, Clean, Crate, ExternalCrate, FnDecl, FnRetTy, Generic, GenericArg, GenericArgs,
5 GenericBound, Generics, GetDefId, ImportSource, Item, ItemKind, Lifetime, MacroKind, Path,
6 PathSegment, Primitive, PrimitiveType, ResolvedPath, Type, TypeBinding, TypeKind,
9 use crate::core::DocContext;
11 use rustc_data_structures::fx::FxHashSet;
13 use rustc_hir::def::{DefKind, Res};
14 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
15 use rustc_middle::mir::interpret::ConstValue;
16 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
17 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt};
18 use rustc_span::symbol::{kw, sym, Symbol};
21 crate fn krate(mut cx: &mut DocContext<'_>) -> Crate {
22 use crate::visit_lib::LibEmbargoVisitor;
24 let krate = cx.tcx.hir().krate();
25 let module = crate::visit_ast::RustdocVisitor::new(&mut cx).visit(krate);
27 let mut r = cx.renderinfo.get_mut();
28 r.deref_trait_did = cx.tcx.lang_items().deref_trait();
29 r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
30 r.owned_box_did = cx.tcx.lang_items().owned_box();
32 let mut externs = Vec::new();
33 for &cnum in cx.tcx.crates().iter() {
34 externs.push((cnum, cnum.clean(cx)));
35 // Analyze doc-reachability for extern items
36 LibEmbargoVisitor::new(&mut cx).visit_lib(cnum);
38 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
40 // Clean the crate, translating the entire librustc_ast AST to one that is
41 // understood by rustdoc.
42 let mut module = module.clean(cx);
43 let mut masked_crates = FxHashSet::default();
46 ItemKind::ModuleItem(ref module) => {
47 for it in &module.items {
48 // `compiler_builtins` should be masked too, but we can't apply
49 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
50 if it.is_extern_crate()
51 && (it.attrs.has_doc_flag(sym::masked)
52 || cx.tcx.is_compiler_builtins(it.def_id.krate))
54 masked_crates.insert(it.def_id.krate);
61 let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx);
63 let m = match *module.kind {
64 ItemKind::ModuleItem(ref mut m) => m,
67 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
68 Item::from_def_id_and_parts(
71 ItemKind::PrimitiveItem(prim),
75 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
76 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
87 external_traits: cx.external_traits.clone(),
93 fn external_generic_args(
95 trait_did: Option<DefId>,
97 bindings: Vec<TypeBinding>,
98 substs: SubstsRef<'_>,
100 let mut skip_self = has_self;
101 let mut ty_kind = None;
102 let args: Vec<_> = substs
104 .filter_map(|kind| match kind.unpack() {
105 GenericArgKind::Lifetime(lt) => match lt {
106 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_) }) => {
107 Some(GenericArg::Lifetime(Lifetime::elided()))
109 _ => lt.clean(cx).map(GenericArg::Lifetime),
111 GenericArgKind::Type(_) if skip_self => {
115 GenericArgKind::Type(ty) => {
116 ty_kind = Some(ty.kind());
117 Some(GenericArg::Type(ty.clean(cx)))
119 GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
124 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
125 Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => {
126 assert!(ty_kind.is_some());
127 let inputs = match ty_kind {
128 Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
129 _ => return GenericArgs::AngleBracketed { args, bindings },
132 // FIXME(#20299) return type comes from a projection now
133 // match types[1].kind {
134 // ty::Tuple(ref v) if v.is_empty() => None, // -> ()
135 // _ => Some(types[1].clean(cx))
137 GenericArgs::Parenthesized { inputs, output }
139 _ => GenericArgs::AngleBracketed { args, bindings },
143 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
144 // from Fn<(A, B,), C> to Fn(A, B) -> C
145 pub(super) fn external_path(
148 trait_did: Option<DefId>,
150 bindings: Vec<TypeBinding>,
151 substs: SubstsRef<'_>,
156 segments: vec![PathSegment {
158 args: external_generic_args(cx, trait_did, has_self, bindings, substs),
163 /// The point of this function is to replace bounds with types.
165 /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return
166 /// `[Display, Option]` (we just returns the list of the types, we don't care about the
167 /// wrapped types in here).
168 crate fn get_real_types(
173 ) -> FxHashSet<(Type, TypeKind)> {
174 fn insert(res: &mut FxHashSet<(Type, TypeKind)>, cx: &DocContext<'_>, ty: Type) {
175 if let Some(kind) = ty.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
176 res.insert((ty, kind));
177 } else if ty.is_primitive() {
178 // This is a primitive, let's store it as such.
179 res.insert((ty, TypeKind::Primitive));
182 let mut res = FxHashSet::default();
184 // FIXME: remove this whole recurse thing when the recursion bug is fixed
188 if arg.is_full_generic() {
189 let arg_s = Symbol::intern(&arg.print(&cx.cache).to_string());
190 if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g {
191 WherePredicate::BoundPredicate { ty, .. } => ty.def_id() == arg.def_id(),
194 let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]);
195 for bound in bounds.iter() {
196 if let GenericBound::TraitBound(poly_trait, _) = bound {
197 for x in poly_trait.generic_params.iter() {
201 if let Some(ty) = x.get_type() {
202 let adds = get_real_types(generics, &ty, cx, recurse + 1);
203 if !adds.is_empty() {
205 } else if !ty.is_full_generic() {
206 insert(&mut res, cx, ty);
213 if let Some(bound) = generics.params.iter().find(|g| g.is_type() && g.name == arg_s) {
214 for bound in bound.get_bounds().unwrap_or_else(|| &[]) {
215 if let Some(ty) = bound.get_trait_type() {
216 let adds = get_real_types(generics, &ty, cx, recurse + 1);
217 if !adds.is_empty() {
219 } else if !ty.is_full_generic() {
220 insert(&mut res, cx, ty);
226 insert(&mut res, cx, arg.clone());
227 if let Some(gens) = arg.generics() {
228 for gen in gens.iter() {
229 if gen.is_full_generic() {
230 let adds = get_real_types(generics, gen, cx, recurse + 1);
231 if !adds.is_empty() {
235 insert(&mut res, cx, gen.clone());
243 /// Return the full list of types when bounds have been resolved.
245 /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
246 /// `[u32, Display, Option]`.
247 crate fn get_all_types(
251 ) -> (Vec<(Type, TypeKind)>, Vec<(Type, TypeKind)>) {
252 let mut all_types = FxHashSet::default();
253 for arg in decl.inputs.values.iter() {
254 if arg.type_.is_self_type() {
257 let args = get_real_types(generics, &arg.type_, cx, 0);
258 if !args.is_empty() {
259 all_types.extend(args);
261 if let Some(kind) = arg.type_.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
262 all_types.insert((arg.type_.clone(), kind));
267 let ret_types = match decl.output {
268 FnRetTy::Return(ref return_type) => {
269 let mut ret = get_real_types(generics, &return_type, cx, 0);
271 if let Some(kind) = return_type.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
272 ret.insert((return_type.clone(), kind));
275 ret.into_iter().collect()
279 (all_types.into_iter().collect(), ret_types)
282 crate fn strip_type(ty: Type) -> Type {
284 Type::ResolvedPath { path, param_names, did, is_generic } => {
285 Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
287 Type::Tuple(inner_tys) => {
288 Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
290 Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
291 Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
292 Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
293 Type::BorrowedRef { lifetime, mutability, type_ } => {
294 Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
296 Type::QPath { name, self_type, trait_ } => Type::QPath {
298 self_type: Box::new(strip_type(*self_type)),
299 trait_: Box::new(strip_type(*trait_)),
305 crate fn strip_path(path: &Path) -> Path {
309 .map(|s| PathSegment {
311 args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
315 Path { global: path.global, res: path.res, segments }
318 crate fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
322 let target = match *item.kind {
323 ItemKind::TypedefItem(ref t, true) => &t.type_,
326 let primitive = match *target {
327 ResolvedPath { did, .. } if did.is_local() => continue,
328 ResolvedPath { did, .. } => {
329 ret.extend(inline::build_impls(cx, None, did, None));
332 _ => match target.primitive_type() {
337 for &did in primitive.impls(tcx) {
339 inline::build_impl(cx, None, did, None, ret);
345 crate trait ToSource {
346 fn to_src(&self, cx: &DocContext<'_>) -> String;
349 impl ToSource for rustc_span::Span {
350 fn to_src(&self, cx: &DocContext<'_>) -> String {
351 debug!("converting span {:?} to snippet", self.clean(cx));
352 let sn = match cx.sess().source_map().span_to_snippet(*self) {
354 Err(_) => String::new(),
356 debug!("got snippet {}", sn);
361 crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
363 ty::ConstKind::Unevaluated(def, _, promoted) => {
364 let mut s = if let Some(def) = def.as_local() {
365 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
366 print_const_expr(cx, cx.tcx.hir().body_owned_by(hir_id))
368 inline::print_inlined_const(cx, def.did)
370 if let Some(promoted) = promoted {
371 s.push_str(&format!("::{:?}", promoted))
376 let mut s = n.to_string();
377 // array lengths are obviously usize
378 if s.ends_with("_usize") {
379 let n = s.len() - "_usize".len();
381 if s.ends_with(": ") {
382 let n = s.len() - ": ".len();
391 crate fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> {
392 cx.tcx.const_eval_poly(def_id).ok().and_then(|val| {
393 let ty = cx.tcx.type_of(def_id);
394 match (val, ty.kind()) {
395 (_, &ty::Ref(..)) => None,
396 (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
397 (ConstValue::Scalar(_), _) => {
398 let const_ = ty::Const::from_value(cx.tcx, val, ty);
399 Some(print_const_with_custom_print_scalar(cx, const_))
406 fn format_integer_with_underscore_sep(num: &str) -> String {
407 let num_chars: Vec<_> = num.chars().collect();
408 let num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
410 num_chars[..num_start_index]
412 .chain(num_chars[num_start_index..].rchunks(3).rev().intersperse(&['_']).flatten())
416 fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
417 // Use a slightly different format for integer types which always shows the actual value.
418 // For all other types, fallback to the original `pretty_print_const`.
419 match (ct.val, ct.ty.kind()) {
420 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
421 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
423 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
424 let ty = cx.tcx.lift(ct.ty).unwrap();
425 let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
426 let data = int.assert_bits(size);
427 let sign_extended_data = size.sign_extend(data) as i128;
431 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
439 crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
440 if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) {
441 if let hir::ExprKind::Lit(_) = &expr.kind {
445 if let hir::ExprKind::Unary(hir::UnOp::UnNeg, expr) = &expr.kind {
446 if let hir::ExprKind::Lit(_) = &expr.kind {
455 crate fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
456 let value = &cx.tcx.hir().body(body).value;
458 let snippet = if !value.span.from_expansion() {
459 cx.sess().source_map().span_to_snippet(value.span).ok()
464 snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&cx.tcx.hir(), body.hir_id))
467 /// Given a type Path, resolve it to a Type using the TyCtxt
468 crate fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
469 debug!("resolve_type({:?},{:?})", path, id);
471 let is_generic = match path.res {
472 Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)),
473 Res::SelfTy(..) if path.segments.len() == 1 => {
474 return Generic(kw::SelfUpper);
476 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
477 return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache))));
479 Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
482 let did = register_res(&*cx, path.res);
483 ResolvedPath { path, param_names: None, did, is_generic }
486 crate fn get_auto_trait_and_blanket_impls(
487 cx: &DocContext<'tcx>,
489 param_env_def_id: DefId,
490 ) -> impl Iterator<Item = Item> {
491 let auto_impls = cx.sess().time("get_auto_trait_impls", || {
492 AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id)
494 let blanket_impls = cx.sess().time("get_blanket_impls", || {
495 BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id)
497 auto_impls.into_iter().chain(blanket_impls)
500 crate fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
501 debug!("register_res({:?})", res);
503 let (did, kind) = match res {
504 Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
505 Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
506 Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
507 Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
508 Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
509 (cx.tcx.parent(i).unwrap(), TypeKind::Trait)
511 Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct),
512 Res::Def(DefKind::Union, i) => (i, TypeKind::Union),
513 Res::Def(DefKind::Mod, i) => (i, TypeKind::Module),
514 Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign),
515 Res::Def(DefKind::Const, i) => (i, TypeKind::Const),
516 Res::Def(DefKind::Static, i) => (i, TypeKind::Static),
517 Res::Def(DefKind::Variant, i) => {
518 (cx.tcx.parent(i).expect("cannot get parent def id"), TypeKind::Enum)
520 Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
521 MacroKind::Bang => (i, TypeKind::Macro),
522 MacroKind::Attr => (i, TypeKind::Attr),
523 MacroKind::Derive => (i, TypeKind::Derive),
525 Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias),
526 Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
527 Res::SelfTy(_, Some((impl_def_id, _))) => return impl_def_id,
528 _ => return res.def_id(),
533 inline::record_extern_fqn(cx, did, kind);
534 if let TypeKind::Trait = kind {
535 inline::record_extern_trait(cx, did);
540 crate fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource {
542 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
547 crate fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R
551 let old_bounds = mem::take(&mut *cx.impl_trait_bounds.borrow_mut());
553 assert!(cx.impl_trait_bounds.borrow().is_empty());
554 *cx.impl_trait_bounds.borrow_mut() = old_bounds;
558 /// Find the nearest parent module of a [`DefId`].
560 /// **Panics if the item it belongs to [is fake][Item::is_fake].**
561 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
562 if def_id.is_top_level_module() {
563 // The crate root has no parent. Use it as the root instead.
566 let mut current = def_id;
567 // The immediate parent might not always be a module.
568 // Find the first parent which is.
569 while let Some(parent) = tcx.parent(current) {
570 if tcx.def_kind(parent) == DefKind::Mod {