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 ItemKind::ModuleItem(ref mut m) = *module.kind
61 else { unreachable!() };
62 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
63 Item::from_def_id_and_parts(
66 ItemKind::PrimitiveItem(prim),
70 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
71 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
75 Crate { module, primitives, external_traits: cx.external_traits.clone() }
78 crate fn substs_to_args(
79 cx: &mut DocContext<'_>,
80 substs: &[ty::subst::GenericArg<'_>],
82 ) -> Vec<GenericArg> {
85 .filter_map(|kind| match kind.unpack() {
86 GenericArgKind::Lifetime(lt) => match *lt {
87 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_), .. }) => {
88 Some(GenericArg::Lifetime(Lifetime::elided()))
90 _ => lt.clean(cx).map(GenericArg::Lifetime),
92 GenericArgKind::Type(_) if skip_first => {
96 GenericArgKind::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
97 GenericArgKind::Const(ct) => Some(GenericArg::Const(Box::new(ct.clean(cx)))),
102 fn external_generic_args(
103 cx: &mut DocContext<'_>,
106 bindings: Vec<TypeBinding>,
107 substs: SubstsRef<'_>,
109 let args = substs_to_args(cx, &substs, has_self);
111 if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() {
113 // The trait's first substitution is the one after self, if there is one.
114 match substs.iter().nth(if has_self { 1 } else { 0 }).unwrap().expect_ty().kind() {
115 ty::Tuple(tys) => tys.iter().map(|t| t.clean(cx)).collect(),
116 _ => return GenericArgs::AngleBracketed { args, bindings: bindings.into() },
119 // FIXME(#20299) return type comes from a projection now
120 // match types[1].kind {
121 // ty::Tuple(ref v) if v.is_empty() => None, // -> ()
122 // _ => Some(types[1].clean(cx))
124 GenericArgs::Parenthesized { inputs, output }
126 GenericArgs::AngleBracketed { args, bindings: bindings.into() }
130 pub(super) fn external_path(
131 cx: &mut DocContext<'_>,
134 bindings: Vec<TypeBinding>,
135 substs: SubstsRef<'_>,
137 let def_kind = cx.tcx.def_kind(did);
138 let name = cx.tcx.item_name(did);
140 res: Res::Def(def_kind, did),
141 segments: vec![PathSegment {
143 args: external_generic_args(cx, did, has_self, bindings, substs),
148 /// Remove the generic arguments from a path.
149 crate fn strip_path_generics(mut path: Path) -> Path {
150 for ps in path.segments.iter_mut() {
151 ps.args = GenericArgs::AngleBracketed { args: vec![], bindings: ThinVec::new() }
157 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
158 let segments = match *p {
159 hir::QPath::Resolved(_, path) => &path.segments,
160 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
161 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
164 let mut s = String::new();
165 for (i, seg) in segments.iter().enumerate() {
169 if seg.ident.name != kw::PathRoot {
170 s.push_str(seg.ident.as_str());
176 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
180 let target = match *item.kind {
181 ItemKind::TypedefItem(ref t, true) => &t.type_,
185 if let Some(prim) = target.primitive_type() {
186 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
187 for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
188 inline::build_impl(cx, None, did, None, ret);
190 } else if let Type::Path { path } = target {
191 let did = path.def_id();
193 inline::build_impls(cx, None, did, None, ret);
199 crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
201 debug!("trying to get a name from pattern: {:?}", p);
203 Symbol::intern(&match p.kind {
204 PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
205 PatKind::Binding(_, _, ident, _) => return ident.name,
206 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
207 PatKind::Or(pats) => {
208 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
210 PatKind::Tuple(elts, _) => format!(
212 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
214 PatKind::Box(p) => return name_from_pat(&*p),
215 PatKind::Ref(p, _) => return name_from_pat(&*p),
216 PatKind::Lit(..) => {
218 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
220 return Symbol::intern("()");
222 PatKind::Range(..) => return kw::Underscore,
223 PatKind::Slice(begin, ref mid, end) => {
224 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
225 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
226 let end = end.iter().map(|p| name_from_pat(p).to_string());
227 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
232 crate fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
234 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) => {
235 let mut s = if let Some(def) = def.as_local() {
236 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
237 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
239 inline::print_inlined_const(cx.tcx, def.did)
241 if let Some(promoted) = promoted {
242 s.push_str(&format!("::{:?}", promoted))
247 let mut s = n.to_string();
248 // array lengths are obviously usize
249 if s.ends_with("_usize") {
250 let n = s.len() - "_usize".len();
252 if s.ends_with(": ") {
253 let n = s.len() - ": ".len();
262 crate fn print_evaluated_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
263 tcx.const_eval_poly(def_id).ok().and_then(|val| {
264 let ty = tcx.type_of(def_id);
265 match (val, ty.kind()) {
266 (_, &ty::Ref(..)) => None,
267 (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
268 (ConstValue::Scalar(_), _) => {
269 let const_ = ty::Const::from_value(tcx, val, ty);
270 Some(print_const_with_custom_print_scalar(tcx, const_))
277 fn format_integer_with_underscore_sep(num: &str) -> String {
278 let num_chars: Vec<_> = num.chars().collect();
279 let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
280 let chunk_size = match num[num_start_index..].as_bytes() {
281 [b'0', b'b' | b'x', ..] => {
282 num_start_index += 2;
285 [b'0', b'o', ..] => {
286 num_start_index += 2;
287 let remaining_chars = num_chars.len() - num_start_index;
288 if remaining_chars <= 6 {
289 // don't add underscores to Unix permissions like 0755 or 100755
290 return num.to_string();
297 num_chars[..num_start_index]
299 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
303 fn print_const_with_custom_print_scalar(tcx: TyCtxt<'_>, ct: ty::Const<'_>) -> String {
304 // Use a slightly different format for integer types which always shows the actual value.
305 // For all other types, fallback to the original `pretty_print_const`.
306 match (ct.val(), ct.ty().kind()) {
307 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
308 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
310 (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
311 let ty = tcx.lift(ct.ty()).unwrap();
312 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
313 let data = int.assert_bits(size);
314 let sign_extended_data = size.sign_extend(data) as i128;
318 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
326 crate fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
327 if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
328 if let hir::ExprKind::Lit(_) = &expr.kind {
332 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
333 if let hir::ExprKind::Lit(_) = &expr.kind {
342 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
344 let value = &hir.body(body).value;
346 let snippet = if !value.span.from_expansion() {
347 tcx.sess.source_map().span_to_snippet(value.span).ok()
352 snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
355 /// Given a type Path, resolve it to a Type using the TyCtxt
356 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
357 debug!("resolve_type({:?})", path);
360 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
361 Res::SelfTy { .. } if path.segments.len() == 1 => Generic(kw::SelfUpper),
362 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
364 let _ = register_res(cx, path.res);
370 crate fn get_auto_trait_and_blanket_impls(
371 cx: &mut DocContext<'_>,
373 ) -> impl Iterator<Item = Item> {
377 .generic_activity("get_auto_trait_impls")
378 .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
379 let blanket_impls = cx
382 .generic_activity("get_blanket_impls")
383 .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
384 auto_impls.into_iter().chain(blanket_impls)
387 /// If `res` has a documentation page associated, store it in the cache.
389 /// This is later used by [`href()`] to determine the HTML link for the item.
391 /// [`href()`]: crate::html::format::href
392 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
394 debug!("register_res({:?})", res);
396 let (did, kind) = match res {
397 // These should be added to the cache using `record_extern_fqn`.
399 kind @ (AssocTy | AssocFn | AssocConst | Variant | Fn | TyAlias | Enum | Trait | Struct
400 | Union | Mod | ForeignTy | Const | Static | Macro(..) | TraitAlias),
402 ) => (i, kind.into()),
403 // This is part of a trait definition or trait impl; document the trait.
404 Res::SelfTy { trait_: Some(trait_def_id), alias_to: _ } => (trait_def_id, ItemType::Trait),
405 // This is an inherent impl or a type definition; it doesn't have its own page.
406 Res::SelfTy { trait_: None, alias_to: Some((item_def_id, _)) } => return item_def_id,
407 Res::SelfTy { trait_: None, alias_to: None }
412 | Res::NonMacroAttr(_)
413 | Res::Err => return res.def_id(),
415 TyParam | ConstParam | Ctor(..) | ExternCrate | Use | ForeignMod | AnonConst
416 | InlineConst | OpaqueTy | Field | LifetimeParam | GlobalAsm | Impl | Closure
424 inline::record_extern_fqn(cx, did, kind);
425 if let ItemType::Trait = kind {
426 inline::record_extern_trait(cx, did);
431 crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
433 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
438 crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R
440 F: FnOnce(&mut DocContext<'_>) -> R,
442 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
444 assert!(cx.impl_trait_bounds.is_empty());
445 cx.impl_trait_bounds = old_bounds;
449 /// Find the nearest parent module of a [`DefId`].
450 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
451 if def_id.is_top_level_module() {
452 // The crate root has no parent. Use it as the root instead.
455 let mut current = def_id;
456 // The immediate parent might not always be a module.
457 // Find the first parent which is.
458 while let Some(parent) = tcx.parent(current) {
459 if tcx.def_kind(parent) == DefKind::Mod {
468 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
475 /// This function exists because it runs on `hir::Attributes` whereas the other is a
476 /// `clean::Attributes` method.
477 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
478 attrs.iter().any(|attr| {
479 attr.has_name(sym::doc)
480 && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
484 /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
485 /// so that the channel is consistent.
487 /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
488 crate const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
490 /// Render a sequence of macro arms in a format suitable for displaying to the user
491 /// as part of an item declaration.
492 pub(super) fn render_macro_arms<'a>(
494 matchers: impl Iterator<Item = &'a TokenTree>,
497 let mut out = String::new();
498 for matcher in matchers {
499 writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim)
505 pub(super) fn display_macro_source(
506 cx: &mut DocContext<'_>,
512 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
513 // Extract the spans of all matchers. They represent the "interface" of the macro.
514 let matchers = tts.chunks(4).map(|arm| &arm[0]);
517 format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";"))
519 if matchers.len() <= 1 {
521 "{}macro {}{} {{\n ...\n}}",
522 vis.to_src_with_space(cx.tcx, def_id),
524 matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
528 "{}macro {} {{\n{}}}",
529 vis.to_src_with_space(cx.tcx, def_id),
531 render_macro_arms(cx.tcx, matchers, ","),