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
121 let index_offset = generics.count() - args.len();
123 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
124 if has_self && index == 0 {
126 return None;
127 }
128
129 let param = generics.param_at(index + index_offset, cx.tcx);
131 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
132
133 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
135 let default = default.instantiate(cx.tcx, args.as_ref()).skip_normalization();
136 if can_elide_generic_arg(arg, arg.rebind(default)) {
137 return None;
138 }
139 elision_has_failed_once_before = true;
140 }
141
142 match arg.skip_binder().kind() {
143 GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
144 clean_middle_region(lt, cx.tcx).unwrap_or(Lifetime::elided()),
145 )),
146 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
147 arg.rebind(ty),
148 cx,
149 None,
150 Some(crate::clean::ContainerTy::Regular {
151 ty: owner,
152 args: arg.rebind(args.as_ref()),
153 arg: index,
154 }),
155 ))),
156 GenericArgKind::Const(ct) => {
157 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct)))))
158 }
159 }
160 };
161
162 let offset = if has_self { 1 } else { 0 };
163 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
164 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
165 clean_args.reverse();
166 clean_args
167}
168
169fn can_elide_generic_arg<'tcx>(
175 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
176 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
177) -> bool {
178 debug_assert_matches!(
179 (actual.skip_binder().kind(), default.skip_binder().kind()),
180 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
181 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
182 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
183 );
184
185 if actual.has_infer() || default.has_infer() {
188 return false;
189 }
190
191 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
195 return false;
196 }
197
198 actual.skip_binder() == default.skip_binder()
212}
213
214fn clean_middle_generic_args_with_constraints<'tcx>(
215 cx: &mut DocContext<'tcx>,
216 did: DefId,
217 has_self: bool,
218 mut constraints: ThinVec<AssocItemConstraint>,
219 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
220) -> GenericArgs {
221 if cx.tcx.is_trait(did)
222 && cx.tcx.trait_def(did).paren_sugar
223 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
224 {
225 let inputs = tys
226 .iter()
227 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
228 .collect::<Vec<_>>()
229 .into();
230 let output = constraints.pop().and_then(|constraint| match constraint.kind {
231 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
232 Some(Box::new(ty))
233 }
234 _ => None,
235 });
236 return GenericArgs::Parenthesized { inputs, output };
237 }
238
239 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
240
241 GenericArgs::AngleBracketed { args, constraints }
242}
243
244pub(super) fn clean_middle_path<'tcx>(
245 cx: &mut DocContext<'tcx>,
246 did: DefId,
247 has_self: bool,
248 constraints: ThinVec<AssocItemConstraint>,
249 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
250) -> Path {
251 let def_kind = cx.tcx.def_kind(did);
252 let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
253 Path {
254 res: Res::Def(def_kind, did),
255 segments: thin_vec![PathSegment {
256 name,
257 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
258 }],
259 }
260}
261
262pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
263 let segments = match *p {
264 hir::QPath::Resolved(_, path) => &path.segments,
265 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
266 };
267
268 join_path_idents(segments.iter().map(|seg| seg.ident))
269}
270
271pub(crate) fn build_deref_target_impls(
272 cx: &mut DocContext<'_>,
273 items: &[Item],
274 ret: &mut Vec<Item>,
275) {
276 let tcx = cx.tcx;
277
278 for item in items {
279 let target = match item.kind {
280 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
281 _ => continue,
282 };
283
284 if let Some(prim) = target.primitive_type() {
285 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
286 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
287 cx.with_param_env(did, |cx| {
288 inline::build_impl(cx, did, None, ret);
289 });
290 }
291 } else if let Type::Path { path } = target {
292 let did = path.def_id();
293 if !did.is_local() {
294 cx.with_param_env(did, |cx| {
295 inline::build_impls(cx, did, None, ret);
296 });
297 }
298 }
299 }
300}
301
302pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
303 use rustc_hir::*;
304 debug!("trying to get a name from pattern: {p:?}");
305
306 Symbol::intern(&match &p.kind {
307 PatKind::Err(_)
308 | PatKind::Missing | PatKind::Never
310 | PatKind::Range(..)
311 | PatKind::Struct(..)
312 | PatKind::Wild => {
313 return kw::Underscore;
314 }
315 PatKind::Binding(_, _, ident, _) => return ident.name,
316 PatKind::Ref(p, _, _) | PatKind::Guard(p, _) => return name_from_pat(p),
317 PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
318 qpath_to_string(p)
319 }
320 PatKind::Or(pats) => {
321 fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
322 }
323 PatKind::Tuple(elts, _) => {
324 format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
325 }
326 PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
327 PatKind::Expr(..) => {
328 warn!(
329 "tried to get argument name from PatKind::Expr, which is silly in function arguments"
330 );
331 return sym::empty_parens;
332 }
333 PatKind::Slice(begin, mid, end) => {
334 fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
335 fmt::from_fn(move |f| {
336 if wild {
337 f.write_str("..")?;
338 }
339 name_from_pat(pat).fmt(f)
340 })
341 }
342
343 format!(
344 "[{}]",
345 fmt::from_fn(|f| {
346 let begin = begin.iter().map(|p| print_pat(p, false));
347 let mid = mid.map(|p| print_pat(p, true));
348 let end = end.iter().map(|p| print_pat(p, false));
349 begin.chain(mid).chain(end).joined(", ", f)
350 })
351 )
352 }
353 })
354}
355
356pub(crate) fn print_const(tcx: TyCtxt<'_>, n: ty::Const<'_>) -> String {
357 match n.kind() {
358 ty::ConstKind::Alias(_, ty::AliasConst { kind, .. }) => {
359 let def_id: DefId = match kind {
360 ty::AliasConstKind::Projection { def_id } => def_id.into(),
361 ty::AliasConstKind::InherentSelf { def_id } => def_id.into(),
362 ty::AliasConstKind::InherentImpl { def_id } => def_id.into(),
363 ty::AliasConstKind::Free { def_id } => def_id.into(),
364 ty::AliasConstKind::Anon { def_id } => def_id.into(),
365 };
366 if let Some(local_def_id) = def_id.as_local()
367 && let Some(body_id) = tcx.hir_maybe_body_owned_by(local_def_id)
368 {
369 rendered_const(tcx, body_id, local_def_id)
370 } else {
371 n.to_string()
372 }
373 }
374 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
376 cv.to_leaf().to_string()
377 }
378 _ => n.to_string(),
379 }
380}
381
382pub(crate) fn print_evaluated_const(
383 tcx: TyCtxt<'_>,
384 def_id: DefId,
385 with_underscores: bool,
386 with_type: bool,
387) -> Option<String> {
388 tcx.const_eval_poly(def_id).ok().and_then(|val| {
389 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
390 match (val, ty.kind()) {
391 (_, &ty::Ref(..)) => None,
392 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
393 (mir::ConstValue::Scalar(_), _) => {
394 let const_ = mir::Const::from_value(val, ty);
395 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
396 }
397 _ => None,
398 }
399 })
400}
401
402fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
403 let num = num.to_string();
404 let chars = num.as_ascii().unwrap();
405 let mut result = if is_negative { "-".to_string() } else { String::new() };
406 result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
407 result
408}
409
410fn print_const_with_custom_print_scalar<'tcx>(
411 tcx: TyCtxt<'tcx>,
412 ct: mir::Const<'tcx>,
413 with_underscores: bool,
414 with_type: bool,
415) -> String {
416 match (ct, ct.ty().kind()) {
419 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
420 let mut output = if with_underscores {
421 format_integer_with_underscore_sep(
422 int.assert_scalar_int().to_bits_unchecked(),
423 false,
424 )
425 } else {
426 int.to_string()
427 };
428 if with_type {
429 output += ui.name_str();
430 }
431 output
432 }
433 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
434 let ty = ct.ty();
435 let size = tcx
436 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
437 .unwrap()
438 .size;
439 let sign_extended_data = int.assert_scalar_int().to_int(size);
440 let mut output = if with_underscores {
441 format_integer_with_underscore_sep(
442 sign_extended_data.unsigned_abs(),
443 sign_extended_data.is_negative(),
444 )
445 } else {
446 sign_extended_data.to_string()
447 };
448 if with_type {
449 output += i.name_str();
450 }
451 output
452 }
453 _ => ct.to_string(),
454 }
455}
456
457pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
458 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
459 if let hir::ExprKind::Lit(_) = &expr.kind {
460 return true;
461 }
462
463 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
464 && let hir::ExprKind::Lit(_) = &expr.kind
465 {
466 return true;
467 }
468 }
469
470 false
471}
472
473pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
475 debug!("resolve_type({path:?})");
476
477 match path.res {
478 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
479 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
480 Type::SelfTy
481 }
482 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
483 _ => {
484 let _ = register_res(cx, path.res);
485 Type::Path { path }
486 }
487 }
488}
489
490pub(crate) fn synthesize_auto_trait_and_blanket_impls(
491 cx: &mut DocContext<'_>,
492 item_def_id: DefId,
493) -> impl Iterator<Item = Item> + use<> {
494 let auto_impls = cx
495 .sess()
496 .prof
497 .generic_activity("synthesize_auto_trait_impls")
498 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
499 let blanket_impls = cx
500 .sess()
501 .prof
502 .generic_activity("synthesize_blanket_impls")
503 .run(|| synthesize_blanket_impls(cx, item_def_id));
504 auto_impls.into_iter().chain(blanket_impls)
505}
506
507pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
513 use DefKind::*;
514 debug!("register_res({res:?})");
515
516 let (kind, did) = match res {
517 Res::Def(
518 AssocTy
519 | AssocFn
520 | AssocConst { .. }
521 | Variant
522 | Fn
523 | TyAlias
524 | Enum
525 | Trait
526 | Struct
527 | Union
528 | Mod
529 | ForeignTy
530 | Const { .. }
531 | Static { .. }
532 | Macro(..)
533 | TraitAlias,
534 did,
535 ) => (ItemType::from_def_id(did, cx.tcx), did),
536
537 _ => panic!("register_res: unexpected {res:?}"),
538 };
539 if did.is_local() {
540 return did;
541 }
542 inline::record_extern_fqn(cx, did, kind);
543 did
544}
545
546pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
547 ImportSource {
548 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
549 path,
550 }
551}
552
553pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
554where
555 F: FnOnce(&mut DocContext<'tcx>) -> R,
556{
557 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
558 let r = f(cx);
559 assert!(cx.impl_trait_bounds.is_empty());
560 cx.impl_trait_bounds = old_bounds;
561 r
562}
563
564pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ModId> {
566 if def_id.is_top_level_module() {
567 Some(ModId::new_unchecked(def_id))
569 } else {
570 let mut current = def_id;
571 while let Some(parent) = tcx.opt_parent(current) {
574 if tcx.def_kind(parent) == DefKind::Mod {
575 return Some(ModId::new_unchecked(parent));
576 }
577 current = parent;
578 }
579 None
580 }
581}
582
583pub(crate) fn has_doc_flag<F: Fn(&DocAttribute) -> bool>(
586 tcx: TyCtxt<'_>,
587 did: DefId,
588 callback: F,
589) -> bool {
590 find_attr!(tcx, did, Doc(d) if callback(d))
591}
592
593pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
598pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
599 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
600
601fn render_macro_arms(
604 tcx: TyCtxt<'_>,
605 tokens: &rustc_ast::tokenstream::TokenStream,
606 arm_delim: &str,
607) -> String {
608 let mut tokens = tokens.iter();
609 let mut out = String::new();
610 while let Some(mut token) = tokens.next() {
611 let pre = if matches!(token, TokenTree::Token(..)) {
616 let pre = format!("{}() ", render_macro_matcher(tcx, token));
617 tokens.next();
619 let Some(next) = tokens.next() else {
620 return out;
621 };
622 token = next;
623 pre
624 } else {
625 String::new()
626 };
627 writeln!(
628 out,
629 " {pre}{matcher} => {{ ... }}{arm_delim}",
630 matcher = render_macro_matcher(tcx, token),
631 )
632 .unwrap();
633 let _token = tokens.next();
636 debug_assert_matches!(
638 _token,
639 Some(TokenTree::Token(Token { kind: TokenKind::FatArrow, .. }, _))
640 );
641 let _token = tokens.next();
642 debug_assert_matches!(_token, Some(TokenTree::Delimited(..)));
644 let _token = tokens.next();
646 debug_assert_matches!(_token, None | Some(TokenTree::Token(Token { .. }, _)));
647 }
648 out
649}
650
651pub(super) fn display_macro_source(tcx: TyCtxt<'_>, name: Symbol, def: &ast::MacroDef) -> String {
652 if def.macro_rules {
654 format!(
655 "macro_rules! {name} {{\n{arms}}}",
656 arms = render_macro_arms(tcx, &def.body.tokens, ";")
657 )
658 } else {
659 if def.body.tokens.len() <= 4 {
660 format!(
661 "macro {name}{matchers} {{\n ...\n}}",
662 matchers = def
663 .body
664 .tokens
665 .get(0)
666 .map(|matcher| render_macro_matcher(tcx, matcher))
667 .unwrap_or_default(),
668 )
669 } else {
670 format!(
671 "macro {name} {{\n{arms}}}",
672 arms = render_macro_arms(tcx, &def.body.tokens, ",")
673 )
674 }
675 }
676}
677
678pub(crate) fn inherits_doc_hidden(
679 tcx: TyCtxt<'_>,
680 mut def_id: LocalDefId,
681 stop_at: Option<LocalDefId>,
682) -> bool {
683 while let Some(id) = tcx.opt_local_parent(def_id) {
684 if let Some(stop_at) = stop_at
685 && id == stop_at
686 {
687 return false;
688 }
689 def_id = id;
690 if tcx.is_doc_hidden(def_id.to_def_id()) {
691 return true;
692 } else if matches!(
693 tcx.hir_node_by_def_id(def_id),
694 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
695 ) {
696 return false;
699 }
700 }
701 false
702}
703
704#[inline]
705pub(crate) fn should_ignore_res(res: Res) -> bool {
706 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
707}