1pub use std::debug_assert_matches;
2use std::fmt::{self, Display, Write as _};
3use std::sync::LazyLock as Lazy;
4use std::{ascii, mem};
5
6use rustc_ast as ast;
7use rustc_ast::join_path_idents;
8use rustc_ast::token::{Token, TokenKind};
9use rustc_ast::tokenstream::TokenTree;
10use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
11use rustc_hir as hir;
12use rustc_hir::attrs::DocAttribute;
13use rustc_hir::def::{DefKind, Res};
14use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
15use rustc_hir::find_attr;
16use rustc_metadata::rendered_const;
17use rustc_middle::mir;
18use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt};
19use rustc_span::def_id::ModId;
20use rustc_span::symbol::{Symbol, kw, sym};
21use tracing::{debug, warn};
22
23use crate::clean::auto_trait::synthesize_auto_trait_impls;
24use crate::clean::blanket_impl::synthesize_blanket_impls;
25use crate::clean::render_macro_matchers::render_macro_matcher;
26use crate::clean::{
27 AssocItemConstraint, AssocItemConstraintKind, Crate, ExternalCrate, Generic, GenericArg,
28 GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path, PathSegment, Primitive,
29 PrimitiveType, Term, Type, clean_doc_module, clean_middle_const, clean_middle_region,
30 clean_middle_ty, inline,
31};
32use crate::core::DocContext;
33use crate::display::Joined as _;
34use crate::formats::item_type::ItemType;
35
36#[cfg(test)]
37mod tests;
38
39pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
40 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
41
42 let mut module = clean_doc_module(&module, cx);
45
46 match module.kind {
47 ItemKind::ModuleItem(ref module) => {
48 for it in &module.items {
49 if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
52 cx.cache.masked_crates.insert(it.item_id.krate());
53 } else if it.is_extern_crate()
54 && it.attrs.has_doc_flag(|d| d.masked.is_some())
55 && let Some(def_id) = it.item_id.as_def_id()
56 && let Some(local_def_id) = def_id.as_local()
57 && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
58 {
59 cx.cache.masked_crates.insert(cnum);
60 }
61 }
62 }
63 _ => unreachable!(),
64 }
65
66 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
67 let primitives = local_crate.primitives(cx.tcx);
68 let keywords = local_crate.keywords(cx.tcx);
69 let documented_attributes = local_crate.documented_attributes(cx.tcx);
70 {
71 let ItemKind::ModuleItem(m) = &mut module.inner.kind else { unreachable!() };
72 m.items.extend(primitives.map(|(def_id, prim)| {
73 Item::from_def_id_and_parts(
74 def_id,
75 Some(prim.as_sym()),
76 ItemKind::PrimitiveItem(prim),
77 cx.tcx,
78 )
79 }));
80 m.items.extend(keywords.map(|(def_id, kw)| {
81 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx.tcx)
82 }));
83 m.items.extend(documented_attributes.into_iter().map(|(def_id, kw)| {
84 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::AttributeItem, cx.tcx)
85 }));
86 }
87
88 Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
89}
90
91pub(crate) fn clean_middle_generic_args<'tcx>(
92 cx: &mut DocContext<'tcx>,
93 args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
94 mut has_self: bool,
95 owner: DefId,
96) -> ThinVec<GenericArg> {
97 let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
98 if args.is_empty() {
99 return ThinVec::new();
101 }
102
103 let generics = cx.tcx.generics_of(owner);
108 let args = if !has_self && generics.has_own_self() {
109 has_self = true;
110 [cx.tcx.types.trait_object_dummy_self.into()]
111 .into_iter()
112 .chain(args.iter().copied())
113 .collect::<Vec<_>>()
114 .into()
115 } else {
116 std::borrow::Cow::from(args)
117 };
118
119 let mut elision_has_failed_once_before = false;
120 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
121 if has_self && index == 0 {
123 return None;
124 }
125
126 let param = generics.param_at(index, cx.tcx);
127 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
128
129 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
131 let default = default.instantiate(cx.tcx, args.as_ref()).skip_norm_wip();
132 if can_elide_generic_arg(arg, arg.rebind(default)) {
133 return None;
134 }
135 elision_has_failed_once_before = true;
136 }
137
138 match arg.skip_binder().kind() {
139 GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
140 clean_middle_region(lt, cx.tcx).unwrap_or(Lifetime::elided()),
141 )),
142 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
143 arg.rebind(ty),
144 cx,
145 None,
146 Some(crate::clean::ContainerTy::Regular {
147 ty: owner,
148 args: arg.rebind(args.as_ref()),
149 arg: index,
150 }),
151 ))),
152 GenericArgKind::Const(ct) => {
153 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct)))))
154 }
155 }
156 };
157
158 let offset = if has_self { 1 } else { 0 };
159 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
160 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
161 clean_args.reverse();
162 clean_args
163}
164
165fn can_elide_generic_arg<'tcx>(
171 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
172 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
173) -> bool {
174 debug_assert_matches!(
175 (actual.skip_binder().kind(), default.skip_binder().kind()),
176 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
177 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
178 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
179 );
180
181 if actual.has_infer() || default.has_infer() {
184 return false;
185 }
186
187 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
191 return false;
192 }
193
194 actual.skip_binder() == default.skip_binder()
208}
209
210fn clean_middle_generic_args_with_constraints<'tcx>(
211 cx: &mut DocContext<'tcx>,
212 did: DefId,
213 has_self: bool,
214 mut constraints: ThinVec<AssocItemConstraint>,
215 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
216) -> GenericArgs {
217 if cx.tcx.is_trait(did)
218 && cx.tcx.trait_def(did).paren_sugar
219 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
220 {
221 let inputs = tys
222 .iter()
223 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
224 .collect::<Vec<_>>()
225 .into();
226 let output = constraints.pop().and_then(|constraint| match constraint.kind {
227 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
228 Some(Box::new(ty))
229 }
230 _ => None,
231 });
232 return GenericArgs::Parenthesized { inputs, output };
233 }
234
235 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
236
237 GenericArgs::AngleBracketed { args, constraints }
238}
239
240pub(super) fn clean_middle_path<'tcx>(
241 cx: &mut DocContext<'tcx>,
242 did: DefId,
243 has_self: bool,
244 constraints: ThinVec<AssocItemConstraint>,
245 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
246) -> Path {
247 let def_kind = cx.tcx.def_kind(did);
248 let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
249 Path {
250 res: Res::Def(def_kind, did),
251 segments: thin_vec![PathSegment {
252 name,
253 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
254 }],
255 }
256}
257
258pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
259 let segments = match *p {
260 hir::QPath::Resolved(_, path) => &path.segments,
261 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
262 };
263
264 join_path_idents(segments.iter().map(|seg| seg.ident))
265}
266
267pub(crate) fn build_deref_target_impls(
268 cx: &mut DocContext<'_>,
269 items: &[Item],
270 ret: &mut Vec<Item>,
271) {
272 let tcx = cx.tcx;
273
274 for item in items {
275 let target = match item.kind {
276 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
277 _ => continue,
278 };
279
280 if let Some(prim) = target.primitive_type() {
281 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
282 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
283 cx.with_param_env(did, |cx| {
284 inline::build_impl(cx, did, None, ret);
285 });
286 }
287 } else if let Type::Path { path } = target {
288 let did = path.def_id();
289 if !did.is_local() {
290 cx.with_param_env(did, |cx| {
291 inline::build_impls(cx, did, None, ret);
292 });
293 }
294 }
295 }
296}
297
298pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
299 use rustc_hir::*;
300 debug!("trying to get a name from pattern: {p:?}");
301
302 Symbol::intern(&match &p.kind {
303 PatKind::Err(_)
304 | PatKind::Missing | PatKind::Never
306 | PatKind::Range(..)
307 | PatKind::Struct(..)
308 | PatKind::Wild => {
309 return kw::Underscore;
310 }
311 PatKind::Binding(_, _, ident, _) => return ident.name,
312 PatKind::Box(p) | PatKind::Ref(p, _, _) | PatKind::Guard(p, _) => return name_from_pat(p),
313 PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
314 qpath_to_string(p)
315 }
316 PatKind::Or(pats) => {
317 fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
318 }
319 PatKind::Tuple(elts, _) => {
320 format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
321 }
322 PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
323 PatKind::Expr(..) => {
324 warn!(
325 "tried to get argument name from PatKind::Expr, which is silly in function arguments"
326 );
327 return sym::empty_parens;
328 }
329 PatKind::Slice(begin, mid, end) => {
330 fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
331 fmt::from_fn(move |f| {
332 if wild {
333 f.write_str("..")?;
334 }
335 name_from_pat(pat).fmt(f)
336 })
337 }
338
339 format!(
340 "[{}]",
341 fmt::from_fn(|f| {
342 let begin = begin.iter().map(|p| print_pat(p, false));
343 let mid = mid.map(|p| print_pat(p, true));
344 let end = end.iter().map(|p| print_pat(p, false));
345 begin.chain(mid).chain(end).joined(", ", f)
346 })
347 )
348 }
349 })
350}
351
352pub(crate) fn print_const(tcx: TyCtxt<'_>, n: ty::Const<'_>) -> String {
353 match n.kind() {
354 ty::ConstKind::Alias(_, ty::AliasConst { kind, .. }) => {
355 let def_id: DefId = match kind {
356 ty::AliasConstKind::Projection { def_id } => def_id.into(),
357 ty::AliasConstKind::Inherent { def_id } => def_id.into(),
358 ty::AliasConstKind::Free { def_id } => def_id.into(),
359 ty::AliasConstKind::Anon { def_id } => def_id.into(),
360 };
361 if let Some(local_def_id) = def_id.as_local()
362 && let Some(body_id) = tcx.hir_maybe_body_owned_by(local_def_id)
363 {
364 rendered_const(tcx, body_id, local_def_id)
365 } else {
366 n.to_string()
367 }
368 }
369 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
371 cv.to_leaf().to_string()
372 }
373 _ => n.to_string(),
374 }
375}
376
377pub(crate) fn print_evaluated_const(
378 tcx: TyCtxt<'_>,
379 def_id: DefId,
380 with_underscores: bool,
381 with_type: bool,
382) -> Option<String> {
383 tcx.const_eval_poly(def_id).ok().and_then(|val| {
384 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
385 match (val, ty.kind()) {
386 (_, &ty::Ref(..)) => None,
387 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
388 (mir::ConstValue::Scalar(_), _) => {
389 let const_ = mir::Const::from_value(val, ty);
390 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
391 }
392 _ => None,
393 }
394 })
395}
396
397fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
398 let num = num.to_string();
399 let chars = num.as_ascii().unwrap();
400 let mut result = if is_negative { "-".to_string() } else { String::new() };
401 result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
402 result
403}
404
405fn print_const_with_custom_print_scalar<'tcx>(
406 tcx: TyCtxt<'tcx>,
407 ct: mir::Const<'tcx>,
408 with_underscores: bool,
409 with_type: bool,
410) -> String {
411 match (ct, ct.ty().kind()) {
414 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
415 let mut output = if with_underscores {
416 format_integer_with_underscore_sep(
417 int.assert_scalar_int().to_bits_unchecked(),
418 false,
419 )
420 } else {
421 int.to_string()
422 };
423 if with_type {
424 output += ui.name_str();
425 }
426 output
427 }
428 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
429 let ty = ct.ty();
430 let size = tcx
431 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
432 .unwrap()
433 .size;
434 let sign_extended_data = int.assert_scalar_int().to_int(size);
435 let mut output = if with_underscores {
436 format_integer_with_underscore_sep(
437 sign_extended_data.unsigned_abs(),
438 sign_extended_data.is_negative(),
439 )
440 } else {
441 sign_extended_data.to_string()
442 };
443 if with_type {
444 output += i.name_str();
445 }
446 output
447 }
448 _ => ct.to_string(),
449 }
450}
451
452pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
453 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
454 if let hir::ExprKind::Lit(_) = &expr.kind {
455 return true;
456 }
457
458 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
459 && let hir::ExprKind::Lit(_) = &expr.kind
460 {
461 return true;
462 }
463 }
464
465 false
466}
467
468pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
470 debug!("resolve_type({path:?})");
471
472 match path.res {
473 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
474 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
475 Type::SelfTy
476 }
477 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
478 _ => {
479 let _ = register_res(cx, path.res);
480 Type::Path { path }
481 }
482 }
483}
484
485pub(crate) fn synthesize_auto_trait_and_blanket_impls(
486 cx: &mut DocContext<'_>,
487 item_def_id: DefId,
488) -> impl Iterator<Item = Item> + use<> {
489 let auto_impls = cx
490 .sess()
491 .prof
492 .generic_activity("synthesize_auto_trait_impls")
493 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
494 let blanket_impls = cx
495 .sess()
496 .prof
497 .generic_activity("synthesize_blanket_impls")
498 .run(|| synthesize_blanket_impls(cx, item_def_id));
499 auto_impls.into_iter().chain(blanket_impls)
500}
501
502pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
508 use DefKind::*;
509 debug!("register_res({res:?})");
510
511 let (kind, did) = match res {
512 Res::Def(
513 AssocTy
514 | AssocFn
515 | AssocConst { .. }
516 | Variant
517 | Fn
518 | TyAlias
519 | Enum
520 | Trait
521 | Struct
522 | Union
523 | Mod
524 | ForeignTy
525 | Const { .. }
526 | Static { .. }
527 | Macro(..)
528 | TraitAlias,
529 did,
530 ) => (ItemType::from_def_id(did, cx.tcx), did),
531
532 _ => panic!("register_res: unexpected {res:?}"),
533 };
534 if did.is_local() {
535 return did;
536 }
537 inline::record_extern_fqn(cx, did, kind);
538 did
539}
540
541pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
542 ImportSource {
543 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
544 path,
545 }
546}
547
548pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
549where
550 F: FnOnce(&mut DocContext<'tcx>) -> R,
551{
552 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
553 let r = f(cx);
554 assert!(cx.impl_trait_bounds.is_empty());
555 cx.impl_trait_bounds = old_bounds;
556 r
557}
558
559pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ModId> {
561 if def_id.is_top_level_module() {
562 Some(ModId::new_unchecked(def_id))
564 } else {
565 let mut current = def_id;
566 while let Some(parent) = tcx.opt_parent(current) {
569 if tcx.def_kind(parent) == DefKind::Mod {
570 return Some(ModId::new_unchecked(parent));
571 }
572 current = parent;
573 }
574 None
575 }
576}
577
578pub(crate) fn has_doc_flag<F: Fn(&DocAttribute) -> bool>(
581 tcx: TyCtxt<'_>,
582 did: DefId,
583 callback: F,
584) -> bool {
585 find_attr!(tcx, did, Doc(d) if callback(d))
586}
587
588pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
593pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
594 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
595
596fn render_macro_arms(
599 tcx: TyCtxt<'_>,
600 tokens: &rustc_ast::tokenstream::TokenStream,
601 arm_delim: &str,
602) -> String {
603 let mut tokens = tokens.iter();
604 let mut out = String::new();
605 while let Some(mut token) = tokens.next() {
606 let pre = if matches!(token, TokenTree::Token(..)) {
611 let pre = format!("{}() ", render_macro_matcher(tcx, token));
612 tokens.next();
614 let Some(next) = tokens.next() else {
615 return out;
616 };
617 token = next;
618 pre
619 } else {
620 String::new()
621 };
622 writeln!(
623 out,
624 " {pre}{matcher} => {{ ... }}{arm_delim}",
625 matcher = render_macro_matcher(tcx, token),
626 )
627 .unwrap();
628 let _token = tokens.next();
631 debug_assert_matches!(
633 _token,
634 Some(TokenTree::Token(Token { kind: TokenKind::FatArrow, .. }, _))
635 );
636 let _token = tokens.next();
637 debug_assert_matches!(_token, Some(TokenTree::Delimited(..)));
639 let _token = tokens.next();
641 debug_assert_matches!(_token, None | Some(TokenTree::Token(Token { .. }, _)));
642 }
643 out
644}
645
646pub(super) fn display_macro_source(tcx: TyCtxt<'_>, name: Symbol, def: &ast::MacroDef) -> String {
647 if def.macro_rules {
649 format!(
650 "macro_rules! {name} {{\n{arms}}}",
651 arms = render_macro_arms(tcx, &def.body.tokens, ";")
652 )
653 } else {
654 if def.body.tokens.len() <= 4 {
655 format!(
656 "macro {name}{matchers} {{\n ...\n}}",
657 matchers = def
658 .body
659 .tokens
660 .get(0)
661 .map(|matcher| render_macro_matcher(tcx, matcher))
662 .unwrap_or_default(),
663 )
664 } else {
665 format!(
666 "macro {name} {{\n{arms}}}",
667 arms = render_macro_arms(tcx, &def.body.tokens, ",")
668 )
669 }
670 }
671}
672
673pub(crate) fn inherits_doc_hidden(
674 tcx: TyCtxt<'_>,
675 mut def_id: LocalDefId,
676 stop_at: Option<LocalDefId>,
677) -> bool {
678 while let Some(id) = tcx.opt_local_parent(def_id) {
679 if let Some(stop_at) = stop_at
680 && id == stop_at
681 {
682 return false;
683 }
684 def_id = id;
685 if tcx.is_doc_hidden(def_id.to_def_id()) {
686 return true;
687 } else if matches!(
688 tcx.hir_node_by_def_id(def_id),
689 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
690 ) {
691 return false;
694 }
695 }
696 false
697}
698
699#[inline]
700pub(crate) fn should_ignore_res(res: Res) -> bool {
701 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
702}