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