1 use crate::clean::auto_trait::AutoTraitFinder;
2 use crate::clean::blanket_impl::BlanketImplFinder;
4 inline, Clean, Crate, ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item,
5 ItemKind, Lifetime, MacroKind, Path, PathSegment, Primitive, PrimitiveType, ResolvedPath, Type,
8 use crate::core::DocContext;
10 use rustc_data_structures::fx::FxHashSet;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc_middle::mir::interpret::ConstValue;
15 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
16 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt};
17 use rustc_span::symbol::{kw, sym, Symbol};
20 crate fn krate(mut cx: &mut DocContext<'_>) -> Crate {
21 use crate::visit_lib::LibEmbargoVisitor;
23 let krate = cx.tcx.hir().krate();
24 let module = crate::visit_ast::RustdocVisitor::new(&mut cx).visit(krate);
26 cx.renderinfo.deref_trait_did = cx.tcx.lang_items().deref_trait();
27 cx.renderinfo.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
28 cx.renderinfo.owned_box_did = cx.tcx.lang_items().owned_box();
30 let mut externs = Vec::new();
31 for &cnum in cx.tcx.crates().iter() {
32 externs.push((cnum, cnum.clean(cx)));
33 // Analyze doc-reachability for extern items
34 LibEmbargoVisitor::new(&mut cx).visit_lib(cnum);
36 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
38 // Clean the crate, translating the entire librustc_ast AST to one that is
39 // understood by rustdoc.
40 let mut module = module.clean(cx);
41 let mut masked_crates = FxHashSet::default();
44 ItemKind::ModuleItem(ref module) => {
45 for it in &module.items {
46 // `compiler_builtins` should be masked too, but we can't apply
47 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
48 if it.is_extern_crate()
49 && (it.attrs.has_doc_flag(sym::masked)
50 || cx.tcx.is_compiler_builtins(it.def_id.krate))
52 masked_crates.insert(it.def_id.krate);
59 let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx);
61 let m = match *module.kind {
62 ItemKind::ModuleItem(ref mut m) => m,
65 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
66 Item::from_def_id_and_parts(
69 ItemKind::PrimitiveItem(prim),
73 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
74 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
85 external_traits: cx.external_traits.clone(),
91 fn external_generic_args(
92 cx: &mut DocContext<'_>,
93 trait_did: Option<DefId>,
95 bindings: Vec<TypeBinding>,
96 substs: SubstsRef<'_>,
98 let mut skip_self = has_self;
99 let mut ty_kind = None;
100 let args: Vec<_> = substs
102 .filter_map(|kind| match kind.unpack() {
103 GenericArgKind::Lifetime(lt) => match lt {
104 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_) }) => {
105 Some(GenericArg::Lifetime(Lifetime::elided()))
107 _ => lt.clean(cx).map(GenericArg::Lifetime),
109 GenericArgKind::Type(_) if skip_self => {
113 GenericArgKind::Type(ty) => {
114 ty_kind = Some(ty.kind());
115 Some(GenericArg::Type(ty.clean(cx)))
117 GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
122 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
123 Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => {
124 assert!(ty_kind.is_some());
125 let inputs = match ty_kind {
126 Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
127 _ => return GenericArgs::AngleBracketed { args, bindings },
130 // FIXME(#20299) return type comes from a projection now
131 // match types[1].kind {
132 // ty::Tuple(ref v) if v.is_empty() => None, // -> ()
133 // _ => Some(types[1].clean(cx))
135 GenericArgs::Parenthesized { inputs, output }
137 _ => GenericArgs::AngleBracketed { args, bindings },
141 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
142 // from Fn<(A, B,), C> to Fn(A, B) -> C
143 pub(super) fn external_path(
144 cx: &mut DocContext<'_>,
146 trait_did: Option<DefId>,
148 bindings: Vec<TypeBinding>,
149 substs: SubstsRef<'_>,
154 segments: vec![PathSegment {
156 args: external_generic_args(cx, trait_did, has_self, bindings, substs),
161 crate fn strip_type(ty: Type) -> Type {
163 Type::ResolvedPath { path, param_names, did, is_generic } => {
164 Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
166 Type::Tuple(inner_tys) => {
167 Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
169 Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
170 Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
171 Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
172 Type::BorrowedRef { lifetime, mutability, type_ } => {
173 Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
175 Type::QPath { name, self_type, trait_ } => Type::QPath {
177 self_type: Box::new(strip_type(*self_type)),
178 trait_: Box::new(strip_type(*trait_)),
184 crate fn strip_path(path: &Path) -> Path {
188 .map(|s| PathSegment {
190 args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
194 Path { global: path.global, res: path.res, segments }
197 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
198 let segments = match *p {
199 hir::QPath::Resolved(_, ref path) => &path.segments,
200 hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
201 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
204 let mut s = String::new();
205 for (i, seg) in segments.iter().enumerate() {
209 if seg.ident.name != kw::PathRoot {
210 s.push_str(&seg.ident.as_str());
216 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
220 let target = match *item.kind {
221 ItemKind::TypedefItem(ref t, true) => &t.type_,
225 if let Some(prim) = target.primitive_type() {
226 for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
227 inline::build_impl(cx, None, did, None, ret);
229 } else if let ResolvedPath { did, .. } = *target {
231 inline::build_impls(cx, None, did, None, ret);
237 crate trait ToSource {
238 fn to_src(&self, cx: &DocContext<'_>) -> String;
241 impl ToSource for rustc_span::Span {
242 fn to_src(&self, cx: &DocContext<'_>) -> String {
243 debug!("converting span {:?} to snippet", self);
244 let sn = match cx.sess().source_map().span_to_snippet(*self) {
246 Err(_) => String::new(),
248 debug!("got snippet {}", sn);
253 crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
255 debug!("trying to get a name from pattern: {:?}", p);
257 Symbol::intern(&match p.kind {
258 PatKind::Wild => return kw::Underscore,
259 PatKind::Binding(_, _, ident, _) => return ident.name,
260 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
261 PatKind::Struct(ref name, ref fields, etc) => format!(
263 qpath_to_string(name),
266 .map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat)))
267 .collect::<Vec<String>>()
269 if etc { ", .." } else { "" }
271 PatKind::Or(ref pats) => pats
273 .map(|p| name_from_pat(&**p).to_string())
274 .collect::<Vec<String>>()
276 PatKind::Tuple(ref elts, _) => format!(
279 .map(|p| name_from_pat(&**p).to_string())
280 .collect::<Vec<String>>()
283 PatKind::Box(ref p) => return name_from_pat(&**p),
284 PatKind::Ref(ref p, _) => return name_from_pat(&**p),
285 PatKind::Lit(..) => {
287 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
289 return Symbol::intern("()");
291 PatKind::Range(..) => return kw::Underscore,
292 PatKind::Slice(ref begin, ref mid, ref end) => {
293 let begin = begin.iter().map(|p| name_from_pat(&**p).to_string());
294 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
295 let end = end.iter().map(|p| name_from_pat(&**p).to_string());
296 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
301 crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
303 ty::ConstKind::Unevaluated(def, _, promoted) => {
304 let mut s = if let Some(def) = def.as_local() {
305 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
306 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
308 inline::print_inlined_const(cx, def.did)
310 if let Some(promoted) = promoted {
311 s.push_str(&format!("::{:?}", promoted))
316 let mut s = n.to_string();
317 // array lengths are obviously usize
318 if s.ends_with("_usize") {
319 let n = s.len() - "_usize".len();
321 if s.ends_with(": ") {
322 let n = s.len() - ": ".len();
331 crate fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> {
332 cx.tcx.const_eval_poly(def_id).ok().and_then(|val| {
333 let ty = cx.tcx.type_of(def_id);
334 match (val, ty.kind()) {
335 (_, &ty::Ref(..)) => None,
336 (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
337 (ConstValue::Scalar(_), _) => {
338 let const_ = ty::Const::from_value(cx.tcx, val, ty);
339 Some(print_const_with_custom_print_scalar(cx, const_))
346 fn format_integer_with_underscore_sep(num: &str) -> String {
347 let num_chars: Vec<_> = num.chars().collect();
348 let num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
350 num_chars[..num_start_index]
352 .chain(num_chars[num_start_index..].rchunks(3).rev().intersperse(&['_']).flatten())
356 fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
357 // Use a slightly different format for integer types which always shows the actual value.
358 // For all other types, fallback to the original `pretty_print_const`.
359 match (ct.val, ct.ty.kind()) {
360 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
361 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
363 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
364 let ty = cx.tcx.lift(ct.ty).unwrap();
365 let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
366 let data = int.assert_bits(size);
367 let sign_extended_data = size.sign_extend(data) as i128;
371 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
379 crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
380 if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) {
381 if let hir::ExprKind::Lit(_) = &expr.kind {
385 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
386 if let hir::ExprKind::Lit(_) = &expr.kind {
395 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
397 let value = &hir.body(body).value;
399 let snippet = if !value.span.from_expansion() {
400 tcx.sess.source_map().span_to_snippet(value.span).ok()
405 snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
408 /// Given a type Path, resolve it to a Type using the TyCtxt
409 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Type {
410 debug!("resolve_type({:?},{:?})", path, id);
412 let is_generic = match path.res {
413 Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)),
414 Res::SelfTy(..) if path.segments.len() == 1 => {
415 return Generic(kw::SelfUpper);
417 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
418 return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache))));
420 Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
423 let did = register_res(cx, path.res);
424 ResolvedPath { path, param_names: None, did, is_generic }
427 crate fn get_auto_trait_and_blanket_impls(
428 cx: &mut DocContext<'tcx>,
430 param_env_def_id: DefId,
431 ) -> impl Iterator<Item = Item> {
435 .generic_activity("get_auto_trait_impls")
436 .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id));
437 let blanket_impls = cx
440 .generic_activity("get_blanket_impls")
441 .run(|| BlanketImplFinder { cx }.get_blanket_impls(ty, param_env_def_id));
442 auto_impls.into_iter().chain(blanket_impls)
445 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
446 debug!("register_res({:?})", res);
448 let (did, kind) = match res {
449 Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
450 Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
451 Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
452 Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
453 Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
454 (cx.tcx.parent(i).unwrap(), TypeKind::Trait)
456 Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct),
457 Res::Def(DefKind::Union, i) => (i, TypeKind::Union),
458 Res::Def(DefKind::Mod, i) => (i, TypeKind::Module),
459 Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign),
460 Res::Def(DefKind::Const, i) => (i, TypeKind::Const),
461 Res::Def(DefKind::Static, i) => (i, TypeKind::Static),
462 Res::Def(DefKind::Variant, i) => {
463 (cx.tcx.parent(i).expect("cannot get parent def id"), TypeKind::Enum)
465 Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
466 MacroKind::Bang => (i, TypeKind::Macro),
467 MacroKind::Attr => (i, TypeKind::Attr),
468 MacroKind::Derive => (i, TypeKind::Derive),
470 Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias),
471 Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
472 Res::SelfTy(_, Some((impl_def_id, _))) => return impl_def_id,
473 _ => return res.def_id(),
478 inline::record_extern_fqn(cx, did, kind);
479 if let TypeKind::Trait = kind {
480 inline::record_extern_trait(cx, did);
485 crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
487 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
492 crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R
494 F: FnOnce(&mut DocContext<'_>) -> R,
496 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
498 assert!(cx.impl_trait_bounds.is_empty());
499 cx.impl_trait_bounds = old_bounds;
503 /// Find the nearest parent module of a [`DefId`].
505 /// **Panics if the item it belongs to [is fake][Item::is_fake].**
506 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
507 if def_id.is_top_level_module() {
508 // The crate root has no parent. Use it as the root instead.
511 let mut current = def_id;
512 // The immediate parent might not always be a module.
513 // Find the first parent which is.
514 while let Some(parent) = tcx.parent(current) {
515 if tcx.def_kind(parent) == DefKind::Mod {
524 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
531 /// This function exists because it runs on `hir::Attributes` whereas the other is a
532 /// `clean::Attributes` method.
533 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
534 attrs.iter().any(|attr| {
535 attr.has_name(sym::doc)
536 && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))