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, Path, PathSegment, PolyTrait, Primitive, PrimitiveType, ResolvedPath, Type,
6 TypeBinding, Visibility,
8 use crate::core::DocContext;
9 use crate::formats::item_type::ItemType;
12 use rustc_ast::tokenstream::TokenTree;
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc_middle::mir::interpret::ConstValue;
17 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
18 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
19 use rustc_span::symbol::{kw, sym, Symbol};
20 use std::fmt::Write as _;
26 crate fn krate(cx: &mut DocContext<'_>) -> Crate {
27 use crate::visit_lib::LibEmbargoVisitor;
29 let krate = cx.tcx.hir().krate();
30 let module = crate::visit_ast::RustdocVisitor::new(cx).visit(krate);
32 let mut externs = Vec::new();
33 for &cnum in cx.tcx.crates(()).iter() {
34 externs.push(ExternalCrate { crate_num: cnum });
35 // Analyze doc-reachability for extern items
36 LibEmbargoVisitor::new(cx).visit_lib(cnum);
38 externs.sort_unstable_by_key(|e| e.crate_num);
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);
45 ItemKind::ModuleItem(ref module) => {
46 for it in &module.items {
47 // `compiler_builtins` should be masked too, but we can't apply
48 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
49 if it.is_extern_crate()
50 && (it.attrs.has_doc_flag(sym::masked)
51 || cx.tcx.is_compiler_builtins(it.def_id.krate()))
53 cx.cache.masked_crates.insert(it.def_id.krate());
60 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
61 let src = local_crate.src(cx.tcx);
62 let name = local_crate.name(cx.tcx);
63 let primitives = local_crate.primitives(cx.tcx);
64 let keywords = local_crate.keywords(cx.tcx);
66 let m = match *module.kind {
67 ItemKind::ModuleItem(ref mut m) => m,
70 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
71 Item::from_def_id_and_parts(
74 ItemKind::PrimitiveItem(prim),
78 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
79 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
89 external_traits: cx.external_traits.clone(),
94 fn external_generic_args(
95 cx: &mut DocContext<'_>,
98 bindings: Vec<TypeBinding>,
99 substs: SubstsRef<'_>,
101 let mut skip_self = has_self;
102 let mut ty_kind = None;
103 let args: Vec<_> = substs
105 .filter_map(|kind| match kind.unpack() {
106 GenericArgKind::Lifetime(lt) => match lt {
107 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_), .. }) => {
108 Some(GenericArg::Lifetime(Lifetime::elided()))
110 _ => lt.clean(cx).map(GenericArg::Lifetime),
112 GenericArgKind::Type(_) if skip_self => {
116 GenericArgKind::Type(ty) => {
117 ty_kind = Some(ty.kind());
118 Some(GenericArg::Type(ty.clean(cx)))
120 GenericArgKind::Const(ct) => Some(GenericArg::Const(Box::new(ct.clean(cx)))),
124 if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() {
125 let inputs = match ty_kind.unwrap() {
126 ty::Tuple(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 pub(super) fn external_path(
142 cx: &mut DocContext<'_>,
145 bindings: Vec<TypeBinding>,
146 substs: SubstsRef<'_>,
148 let def_kind = cx.tcx.def_kind(did);
149 let name = cx.tcx.item_name(did);
152 res: Res::Def(def_kind, did),
153 segments: vec![PathSegment {
155 args: external_generic_args(cx, did, has_self, bindings, substs),
160 crate fn strip_type(ty: Type) -> Type {
162 Type::ResolvedPath { path, did } => Type::ResolvedPath { path: strip_path(&path), did },
163 Type::DynTrait(mut bounds, lt) => {
164 let first = bounds.remove(0);
165 let stripped_trait = strip_type(first.trait_);
169 PolyTrait { trait_: stripped_trait, generic_params: first.generic_params },
171 Type::DynTrait(bounds, lt)
173 Type::Tuple(inner_tys) => {
174 Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
176 Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
177 Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
178 Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
179 Type::BorrowedRef { lifetime, mutability, type_ } => {
180 Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
182 Type::QPath { name, self_type, trait_, self_def_id } => Type::QPath {
185 self_type: Box::new(strip_type(*self_type)),
186 trait_: Box::new(strip_type(*trait_)),
192 crate fn strip_path(path: &Path) -> Path {
196 .map(|s| PathSegment {
198 args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
202 Path { global: path.global, res: path.res, segments }
205 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
206 let segments = match *p {
207 hir::QPath::Resolved(_, ref path) => &path.segments,
208 hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
209 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
212 let mut s = String::new();
213 for (i, seg) in segments.iter().enumerate() {
217 if seg.ident.name != kw::PathRoot {
218 s.push_str(&seg.ident.as_str());
224 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
228 let target = match *item.kind {
229 ItemKind::TypedefItem(ref t, true) => &t.type_,
233 if let Some(prim) = target.primitive_type() {
234 for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
235 inline::build_impl(cx, None, did, None, ret);
237 } else if let ResolvedPath { did, .. } = *target {
239 inline::build_impls(cx, None, did, None, ret);
245 crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
247 debug!("trying to get a name from pattern: {:?}", p);
249 Symbol::intern(&match p.kind {
250 PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
251 PatKind::Binding(_, _, ident, _) => return ident.name,
252 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
253 PatKind::Or(ref pats) => {
254 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
256 PatKind::Tuple(ref elts, _) => format!(
258 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
260 PatKind::Box(ref p) => return name_from_pat(&**p),
261 PatKind::Ref(ref p, _) => return name_from_pat(&**p),
262 PatKind::Lit(..) => {
264 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
266 return Symbol::intern("()");
268 PatKind::Range(..) => return kw::Underscore,
269 PatKind::Slice(ref begin, ref mid, ref end) => {
270 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
271 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
272 let end = end.iter().map(|p| name_from_pat(p).to_string());
273 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
278 crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
280 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs_: _, promoted }) => {
281 let mut s = if let Some(def) = def.as_local() {
282 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
283 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
285 inline::print_inlined_const(cx.tcx, def.did)
287 if let Some(promoted) = promoted {
288 s.push_str(&format!("::{:?}", promoted))
293 let mut s = n.to_string();
294 // array lengths are obviously usize
295 if s.ends_with("_usize") {
296 let n = s.len() - "_usize".len();
298 if s.ends_with(": ") {
299 let n = s.len() - ": ".len();
308 crate fn print_evaluated_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
309 tcx.const_eval_poly(def_id).ok().and_then(|val| {
310 let ty = tcx.type_of(def_id);
311 match (val, ty.kind()) {
312 (_, &ty::Ref(..)) => None,
313 (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
314 (ConstValue::Scalar(_), _) => {
315 let const_ = ty::Const::from_value(tcx, val, ty);
316 Some(print_const_with_custom_print_scalar(tcx, const_))
323 fn format_integer_with_underscore_sep(num: &str) -> String {
324 let num_chars: Vec<_> = num.chars().collect();
325 let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
326 let chunk_size = match num[num_start_index..].as_bytes() {
327 [b'0', b'b' | b'x', ..] => {
328 num_start_index += 2;
331 [b'0', b'o', ..] => {
332 num_start_index += 2;
333 let remaining_chars = num_chars.len() - num_start_index;
334 if remaining_chars <= 6 {
335 // don't add underscores to Unix permissions like 0755 or 100755
336 return num.to_string();
343 num_chars[..num_start_index]
345 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
349 fn print_const_with_custom_print_scalar(tcx: TyCtxt<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
350 // Use a slightly different format for integer types which always shows the actual value.
351 // For all other types, fallback to the original `pretty_print_const`.
352 match (ct.val, ct.ty.kind()) {
353 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
354 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
356 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
357 let ty = tcx.lift(ct.ty).unwrap();
358 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
359 let data = int.assert_bits(size);
360 let sign_extended_data = size.sign_extend(data) as i128;
364 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
372 crate fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
373 if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
374 if let hir::ExprKind::Lit(_) = &expr.kind {
378 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
379 if let hir::ExprKind::Lit(_) = &expr.kind {
388 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
390 let value = &hir.body(body).value;
392 let snippet = if !value.span.from_expansion() {
393 tcx.sess.source_map().span_to_snippet(value.span).ok()
398 snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
401 /// Given a type Path, resolve it to a Type using the TyCtxt
402 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
403 debug!("resolve_type({:?})", path);
406 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
407 Res::SelfTy(..) if path.segments.len() == 1 => Generic(kw::SelfUpper),
408 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
410 let did = register_res(cx, path.res);
411 ResolvedPath { path, did }
416 crate fn get_auto_trait_and_blanket_impls(
417 cx: &mut DocContext<'tcx>,
419 ) -> impl Iterator<Item = Item> {
423 .generic_activity("get_auto_trait_impls")
424 .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
425 let blanket_impls = cx
428 .generic_activity("get_blanket_impls")
429 .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
430 auto_impls.into_iter().chain(blanket_impls)
433 /// If `res` has a documentation page associated, store it in the cache.
435 /// This is later used by [`href()`] to determine the HTML link for the item.
437 /// [`href()`]: crate::html::format::href
438 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
440 debug!("register_res({:?})", res);
442 let (did, kind) = match res {
443 Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
444 // associated items are documented, but on the page of their parent
445 (cx.tcx.parent(i).unwrap(), ItemType::Trait)
447 Res::Def(DefKind::Variant, i) => {
448 // variant items are documented, but on the page of their parent
449 (cx.tcx.parent(i).expect("cannot get parent def id"), ItemType::Enum)
451 // Each of these have their own page.
455 (Fn | TyAlias | Enum | Trait | Struct | Union | Mod | ForeignTy | Const | Static
456 | Macro(..) | TraitAlias),
458 ) => (i, kind.into()),
459 // This is part of a trait definition; document the trait.
460 Res::SelfTy(Some(trait_def_id), _) => (trait_def_id, ItemType::Trait),
461 // This is an inherent impl; it doesn't have its own page.
462 Res::SelfTy(None, Some((impl_def_id, _))) => return impl_def_id,
463 Res::SelfTy(None, None)
468 | Res::NonMacroAttr(_)
469 | Res::Err => return res.def_id(),
471 TyParam | ConstParam | Ctor(..) | ExternCrate | Use | ForeignMod | AnonConst | OpaqueTy
472 | Field | LifetimeParam | GlobalAsm | Impl | Closure | Generator,
479 inline::record_extern_fqn(cx, did, kind);
480 if let ItemType::Trait = kind {
481 inline::record_extern_trait(cx, did);
486 crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
488 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
493 crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R
495 F: FnOnce(&mut DocContext<'_>) -> R,
497 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
499 assert!(cx.impl_trait_bounds.is_empty());
500 cx.impl_trait_bounds = old_bounds;
504 /// Find the nearest parent module of a [`DefId`].
505 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
506 if def_id.is_top_level_module() {
507 // The crate root has no parent. Use it as the root instead.
510 let mut current = def_id;
511 // The immediate parent might not always be a module.
512 // Find the first parent which is.
513 while let Some(parent) = tcx.parent(current) {
514 if tcx.def_kind(parent) == DefKind::Mod {
523 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
530 /// This function exists because it runs on `hir::Attributes` whereas the other is a
531 /// `clean::Attributes` method.
532 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
533 attrs.iter().any(|attr| {
534 attr.has_name(sym::doc)
535 && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
539 /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
540 /// so that the channel is consistent.
542 /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
543 crate const DOC_RUST_LANG_ORG_CHANNEL: &'static str = env!("DOC_RUST_LANG_ORG_CHANNEL");
545 /// Render a sequence of macro arms in a format suitable for displaying to the user
546 /// as part of an item declaration.
547 pub(super) fn render_macro_arms<'a>(
548 matchers: impl Iterator<Item = &'a TokenTree>,
551 let mut out = String::new();
552 for matcher in matchers {
553 writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(matcher), arm_delim).unwrap();
558 /// Render a macro matcher in a format suitable for displaying to the user
559 /// as part of an item declaration.
560 pub(super) fn render_macro_matcher(matcher: &TokenTree) -> String {
561 rustc_ast_pretty::pprust::tt_to_string(matcher)
564 pub(super) fn display_macro_source(
565 cx: &mut DocContext<'_>,
569 vis: impl Clean<Visibility>,
571 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
572 // Extract the spans of all matchers. They represent the "interface" of the macro.
573 let matchers = tts.chunks(4).map(|arm| &arm[0]);
576 format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(matchers, ";"))
578 let vis = vis.clean(cx);
580 if matchers.len() <= 1 {
582 "{}macro {}{} {{\n ...\n}}",
583 vis.to_src_with_space(cx.tcx, def_id),
585 matchers.map(render_macro_matcher).collect::<String>(),
589 "{}macro {} {{\n{}}}",
590 vis.to_src_with_space(cx.tcx, def_id),
592 render_macro_arms(matchers, ","),