1 use crate::clean::auto_trait::AutoTraitFinder;
2 use crate::clean::blanket_impl::BlanketImplFinder;
3 use crate::clean::render_macro_matchers::render_macro_matcher;
5 inline, Clean, Crate, ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item,
6 ItemKind, Lifetime, Path, PathSegment, Primitive, PrimitiveType, Type, TypeBinding, Visibility,
8 use crate::core::DocContext;
9 use crate::formats::item_type::ItemType;
10 use crate::visit_lib::LibEmbargoVisitor;
13 use rustc_ast::tokenstream::TokenTree;
14 use rustc_data_structures::thin_vec::ThinVec;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
18 use rustc_middle::mir::interpret::ConstValue;
19 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
20 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
21 use rustc_span::symbol::{kw, sym, Symbol};
22 use std::fmt::Write as _;
28 crate fn krate(cx: &mut DocContext<'_>) -> Crate {
29 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
31 for &cnum in cx.tcx.crates(()) {
32 // Analyze doc-reachability for extern items
33 LibEmbargoVisitor::new(cx).visit_lib(cnum);
36 // Clean the crate, translating the entire librustc_ast AST to one that is
37 // understood by rustdoc.
38 let mut module = module.clean(cx);
41 ItemKind::ModuleItem(ref module) => {
42 for it in &module.items {
43 // `compiler_builtins` should be masked too, but we can't apply
44 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
45 if it.is_extern_crate()
46 && (it.attrs.has_doc_flag(sym::masked)
47 || cx.tcx.is_compiler_builtins(it.def_id.krate()))
49 cx.cache.masked_crates.insert(it.def_id.krate());
56 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
57 let primitives = local_crate.primitives(cx.tcx);
58 let keywords = local_crate.keywords(cx.tcx);
60 let m = match *module.kind {
61 ItemKind::ModuleItem(ref mut m) => m,
64 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
65 Item::from_def_id_and_parts(
68 ItemKind::PrimitiveItem(prim),
72 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
73 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
77 Crate { module, primitives, external_traits: cx.external_traits.clone() }
80 fn external_generic_args(
81 cx: &mut DocContext<'_>,
84 bindings: Vec<TypeBinding>,
85 substs: SubstsRef<'_>,
87 let mut skip_self = has_self;
88 let mut ty_kind = None;
89 let args: Vec<_> = substs
91 .filter_map(|kind| match kind.unpack() {
92 GenericArgKind::Lifetime(lt) => match lt {
93 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_), .. }) => {
94 Some(GenericArg::Lifetime(Lifetime::elided()))
96 _ => lt.clean(cx).map(GenericArg::Lifetime),
98 GenericArgKind::Type(_) if skip_self => {
102 GenericArgKind::Type(ty) => {
103 ty_kind = Some(ty.kind());
104 Some(GenericArg::Type(ty.clean(cx)))
106 GenericArgKind::Const(ct) => Some(GenericArg::Const(Box::new(ct.clean(cx)))),
110 if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() {
111 let inputs = match ty_kind.unwrap() {
112 ty::Tuple(tys) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
113 _ => return GenericArgs::AngleBracketed { args, bindings: bindings.into() },
116 // FIXME(#20299) return type comes from a projection now
117 // match types[1].kind {
118 // ty::Tuple(ref v) if v.is_empty() => None, // -> ()
119 // _ => Some(types[1].clean(cx))
121 GenericArgs::Parenthesized { inputs, output }
123 GenericArgs::AngleBracketed { args, bindings: bindings.into() }
127 pub(super) fn external_path(
128 cx: &mut DocContext<'_>,
131 bindings: Vec<TypeBinding>,
132 substs: SubstsRef<'_>,
134 let def_kind = cx.tcx.def_kind(did);
135 let name = cx.tcx.item_name(did);
137 res: Res::Def(def_kind, did),
138 segments: vec![PathSegment {
140 args: external_generic_args(cx, did, has_self, bindings, substs),
145 /// Remove the generic arguments from a path.
146 crate fn strip_path_generics(mut path: Path) -> Path {
147 for ps in path.segments.iter_mut() {
148 ps.args = GenericArgs::AngleBracketed { args: vec![], bindings: ThinVec::new() }
154 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
155 let segments = match *p {
156 hir::QPath::Resolved(_, path) => &path.segments,
157 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
158 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
161 let mut s = String::new();
162 for (i, seg) in segments.iter().enumerate() {
166 if seg.ident.name != kw::PathRoot {
167 s.push_str(seg.ident.as_str());
173 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
177 let target = match *item.kind {
178 ItemKind::TypedefItem(ref t, true) => &t.type_,
182 if let Some(prim) = target.primitive_type() {
183 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
184 for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
185 inline::build_impl(cx, None, did, None, ret);
187 } else if let Type::Path { path } = target {
188 let did = path.def_id();
190 inline::build_impls(cx, None, did, None, ret);
196 crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
198 debug!("trying to get a name from pattern: {:?}", p);
200 Symbol::intern(&match p.kind {
201 PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
202 PatKind::Binding(_, _, ident, _) => return ident.name,
203 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
204 PatKind::Or(pats) => {
205 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
207 PatKind::Tuple(elts, _) => format!(
209 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
211 PatKind::Box(p) => return name_from_pat(&*p),
212 PatKind::Ref(p, _) => return name_from_pat(&*p),
213 PatKind::Lit(..) => {
215 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
217 return Symbol::intern("()");
219 PatKind::Range(..) => return kw::Underscore,
220 PatKind::Slice(begin, ref mid, end) => {
221 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
222 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
223 let end = end.iter().map(|p| name_from_pat(p).to_string());
224 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
229 crate fn print_const(cx: &DocContext<'_>, n: &ty::Const<'_>) -> String {
231 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) => {
232 let mut s = if let Some(def) = def.as_local() {
233 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
234 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
236 inline::print_inlined_const(cx.tcx, def.did)
238 if let Some(promoted) = promoted {
239 s.push_str(&format!("::{:?}", promoted))
244 let mut s = n.to_string();
245 // array lengths are obviously usize
246 if s.ends_with("_usize") {
247 let n = s.len() - "_usize".len();
249 if s.ends_with(": ") {
250 let n = s.len() - ": ".len();
259 crate fn print_evaluated_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
260 tcx.const_eval_poly(def_id).ok().and_then(|val| {
261 let ty = tcx.type_of(def_id);
262 match (val, ty.kind()) {
263 (_, &ty::Ref(..)) => None,
264 (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
265 (ConstValue::Scalar(_), _) => {
266 let const_ = ty::Const::from_value(tcx, val, ty);
267 Some(print_const_with_custom_print_scalar(tcx, const_))
274 fn format_integer_with_underscore_sep(num: &str) -> String {
275 let num_chars: Vec<_> = num.chars().collect();
276 let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
277 let chunk_size = match num[num_start_index..].as_bytes() {
278 [b'0', b'b' | b'x', ..] => {
279 num_start_index += 2;
282 [b'0', b'o', ..] => {
283 num_start_index += 2;
284 let remaining_chars = num_chars.len() - num_start_index;
285 if remaining_chars <= 6 {
286 // don't add underscores to Unix permissions like 0755 or 100755
287 return num.to_string();
294 num_chars[..num_start_index]
296 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
300 fn print_const_with_custom_print_scalar(tcx: TyCtxt<'_>, ct: &ty::Const<'_>) -> String {
301 // Use a slightly different format for integer types which always shows the actual value.
302 // For all other types, fallback to the original `pretty_print_const`.
303 match (ct.val, ct.ty.kind()) {
304 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
305 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
307 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
308 let ty = tcx.lift(ct.ty).unwrap();
309 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
310 let data = int.assert_bits(size);
311 let sign_extended_data = size.sign_extend(data) as i128;
315 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
323 crate fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
324 if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
325 if let hir::ExprKind::Lit(_) = &expr.kind {
329 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
330 if let hir::ExprKind::Lit(_) = &expr.kind {
339 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
341 let value = &hir.body(body).value;
343 let snippet = if !value.span.from_expansion() {
344 tcx.sess.source_map().span_to_snippet(value.span).ok()
349 snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
352 /// Given a type Path, resolve it to a Type using the TyCtxt
353 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
354 debug!("resolve_type({:?})", path);
357 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
358 Res::SelfTy(..) if path.segments.len() == 1 => Generic(kw::SelfUpper),
359 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
361 let _ = register_res(cx, path.res);
367 crate fn get_auto_trait_and_blanket_impls(
368 cx: &mut DocContext<'_>,
370 ) -> impl Iterator<Item = Item> {
374 .generic_activity("get_auto_trait_impls")
375 .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
376 let blanket_impls = cx
379 .generic_activity("get_blanket_impls")
380 .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
381 auto_impls.into_iter().chain(blanket_impls)
384 /// If `res` has a documentation page associated, store it in the cache.
386 /// This is later used by [`href()`] to determine the HTML link for the item.
388 /// [`href()`]: crate::html::format::href
389 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
391 debug!("register_res({:?})", res);
393 let (did, kind) = match res {
394 // These should be added to the cache using `record_extern_fqn`.
396 kind @ (AssocTy | AssocFn | AssocConst | Variant | Fn | TyAlias | Enum | Trait | Struct
397 | Union | Mod | ForeignTy | Const | Static | Macro(..) | TraitAlias),
399 ) => (i, kind.into()),
400 // This is part of a trait definition; document the trait.
401 Res::SelfTy(Some(trait_def_id), _) => (trait_def_id, ItemType::Trait),
402 // This is an inherent impl; it doesn't have its own page.
403 Res::SelfTy(None, Some((impl_def_id, _))) => return impl_def_id,
404 Res::SelfTy(None, None)
409 | Res::NonMacroAttr(_)
410 | Res::Err => return res.def_id(),
412 TyParam | ConstParam | Ctor(..) | ExternCrate | Use | ForeignMod | AnonConst
413 | InlineConst | OpaqueTy | Field | LifetimeParam | GlobalAsm | Impl | Closure
421 inline::record_extern_fqn(cx, did, kind);
422 if let ItemType::Trait = kind {
423 inline::record_extern_trait(cx, did);
428 crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
430 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
435 crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R
437 F: FnOnce(&mut DocContext<'_>) -> R,
439 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
441 assert!(cx.impl_trait_bounds.is_empty());
442 cx.impl_trait_bounds = old_bounds;
446 /// Find the nearest parent module of a [`DefId`].
447 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
448 if def_id.is_top_level_module() {
449 // The crate root has no parent. Use it as the root instead.
452 let mut current = def_id;
453 // The immediate parent might not always be a module.
454 // Find the first parent which is.
455 while let Some(parent) = tcx.parent(current) {
456 if tcx.def_kind(parent) == DefKind::Mod {
465 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
472 /// This function exists because it runs on `hir::Attributes` whereas the other is a
473 /// `clean::Attributes` method.
474 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
475 attrs.iter().any(|attr| {
476 attr.has_name(sym::doc)
477 && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
481 /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
482 /// so that the channel is consistent.
484 /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
485 crate const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
487 /// Render a sequence of macro arms in a format suitable for displaying to the user
488 /// as part of an item declaration.
489 pub(super) fn render_macro_arms<'a>(
491 matchers: impl Iterator<Item = &'a TokenTree>,
494 let mut out = String::new();
495 for matcher in matchers {
496 writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim)
502 pub(super) fn display_macro_source(
503 cx: &mut DocContext<'_>,
509 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
510 // Extract the spans of all matchers. They represent the "interface" of the macro.
511 let matchers = tts.chunks(4).map(|arm| &arm[0]);
514 format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";"))
516 if matchers.len() <= 1 {
518 "{}macro {}{} {{\n ...\n}}",
519 vis.to_src_with_space(cx.tcx, def_id),
521 matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
525 "{}macro {} {{\n{}}}",
526 vis.to_src_with_space(cx.tcx, def_id),
528 render_macro_arms(cx.tcx, matchers, ","),