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 Symbol::intern("()");
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 { def, args: _ }) => {
354 if let Some(def) = def.as_local() {
355 rendered_const(tcx, tcx.hir_body_owned_by(def), def)
356 } else {
357 inline::print_inlined_const(tcx, def)
358 }
359 }
360 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
362 cv.to_leaf().to_string()
363 }
364 _ => n.to_string(),
365 }
366}
367
368pub(crate) fn print_evaluated_const(
369 tcx: TyCtxt<'_>,
370 def_id: DefId,
371 with_underscores: bool,
372 with_type: bool,
373) -> Option<String> {
374 tcx.const_eval_poly(def_id).ok().and_then(|val| {
375 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
376 match (val, ty.kind()) {
377 (_, &ty::Ref(..)) => None,
378 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
379 (mir::ConstValue::Scalar(_), _) => {
380 let const_ = mir::Const::from_value(val, ty);
381 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
382 }
383 _ => None,
384 }
385 })
386}
387
388fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
389 let num = num.to_string();
390 let chars = num.as_ascii().unwrap();
391 let mut result = if is_negative { "-".to_string() } else { String::new() };
392 result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
393 result
394}
395
396fn print_const_with_custom_print_scalar<'tcx>(
397 tcx: TyCtxt<'tcx>,
398 ct: mir::Const<'tcx>,
399 with_underscores: bool,
400 with_type: bool,
401) -> String {
402 match (ct, ct.ty().kind()) {
405 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
406 let mut output = if with_underscores {
407 format_integer_with_underscore_sep(
408 int.assert_scalar_int().to_bits_unchecked(),
409 false,
410 )
411 } else {
412 int.to_string()
413 };
414 if with_type {
415 output += ui.name_str();
416 }
417 output
418 }
419 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
420 let ty = ct.ty();
421 let size = tcx
422 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
423 .unwrap()
424 .size;
425 let sign_extended_data = int.assert_scalar_int().to_int(size);
426 let mut output = if with_underscores {
427 format_integer_with_underscore_sep(
428 sign_extended_data.unsigned_abs(),
429 sign_extended_data.is_negative(),
430 )
431 } else {
432 sign_extended_data.to_string()
433 };
434 if with_type {
435 output += i.name_str();
436 }
437 output
438 }
439 _ => ct.to_string(),
440 }
441}
442
443pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
444 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
445 if let hir::ExprKind::Lit(_) = &expr.kind {
446 return true;
447 }
448
449 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
450 && let hir::ExprKind::Lit(_) = &expr.kind
451 {
452 return true;
453 }
454 }
455
456 false
457}
458
459pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
461 debug!("resolve_type({path:?})");
462
463 match path.res {
464 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
465 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
466 Type::SelfTy
467 }
468 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
469 _ => {
470 let _ = register_res(cx, path.res);
471 Type::Path { path }
472 }
473 }
474}
475
476pub(crate) fn synthesize_auto_trait_and_blanket_impls(
477 cx: &mut DocContext<'_>,
478 item_def_id: DefId,
479) -> impl Iterator<Item = Item> + use<> {
480 let auto_impls = cx
481 .sess()
482 .prof
483 .generic_activity("synthesize_auto_trait_impls")
484 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
485 let blanket_impls = cx
486 .sess()
487 .prof
488 .generic_activity("synthesize_blanket_impls")
489 .run(|| synthesize_blanket_impls(cx, item_def_id));
490 auto_impls.into_iter().chain(blanket_impls)
491}
492
493pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
499 use DefKind::*;
500 debug!("register_res({res:?})");
501
502 let (kind, did) = match res {
503 Res::Def(
504 AssocTy
505 | AssocFn
506 | AssocConst { .. }
507 | Variant
508 | Fn
509 | TyAlias
510 | Enum
511 | Trait
512 | Struct
513 | Union
514 | Mod
515 | ForeignTy
516 | Const { .. }
517 | Static { .. }
518 | Macro(..)
519 | TraitAlias,
520 did,
521 ) => (ItemType::from_def_id(did, cx.tcx), did),
522
523 _ => panic!("register_res: unexpected {res:?}"),
524 };
525 if did.is_local() {
526 return did;
527 }
528 inline::record_extern_fqn(cx, did, kind);
529 did
530}
531
532pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
533 ImportSource {
534 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
535 path,
536 }
537}
538
539pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
540where
541 F: FnOnce(&mut DocContext<'tcx>) -> R,
542{
543 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
544 let r = f(cx);
545 assert!(cx.impl_trait_bounds.is_empty());
546 cx.impl_trait_bounds = old_bounds;
547 r
548}
549
550pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
552 if def_id.is_top_level_module() {
553 Some(def_id)
555 } else {
556 let mut current = def_id;
557 while let Some(parent) = tcx.opt_parent(current) {
560 if tcx.def_kind(parent) == DefKind::Mod {
561 return Some(parent);
562 }
563 current = parent;
564 }
565 None
566 }
567}
568
569pub(crate) fn has_doc_flag<F: Fn(&DocAttribute) -> bool>(
572 tcx: TyCtxt<'_>,
573 did: DefId,
574 callback: F,
575) -> bool {
576 find_attr!(tcx, did, Doc(d) if callback(d))
577}
578
579pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
584pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
585 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
586
587fn render_macro_arms(
590 tcx: TyCtxt<'_>,
591 tokens: &rustc_ast::tokenstream::TokenStream,
592 arm_delim: &str,
593) -> String {
594 let mut tokens = tokens.iter();
595 let mut out = String::new();
596 while let Some(mut token) = tokens.next() {
597 let pre = if matches!(token, TokenTree::Token(..)) {
602 let pre = format!("{}() ", render_macro_matcher(tcx, token));
603 tokens.next();
605 let Some(next) = tokens.next() else {
606 return out;
607 };
608 token = next;
609 pre
610 } else {
611 String::new()
612 };
613 writeln!(
614 out,
615 " {pre}{matcher} => {{ ... }}{arm_delim}",
616 matcher = render_macro_matcher(tcx, token),
617 )
618 .unwrap();
619 let _token = tokens.next();
622 debug_assert_matches!(
624 _token,
625 Some(TokenTree::Token(Token { kind: TokenKind::FatArrow, .. }, _))
626 );
627 let _token = tokens.next();
628 debug_assert_matches!(_token, Some(TokenTree::Delimited(..)));
630 let _token = tokens.next();
632 debug_assert_matches!(_token, None | Some(TokenTree::Token(Token { .. }, _)));
633 }
634 out
635}
636
637pub(super) fn display_macro_source(tcx: TyCtxt<'_>, name: Symbol, def: &ast::MacroDef) -> String {
638 if def.macro_rules {
640 format!(
641 "macro_rules! {name} {{\n{arms}}}",
642 arms = render_macro_arms(tcx, &def.body.tokens, ";")
643 )
644 } else {
645 if def.body.tokens.len() <= 4 {
646 format!(
647 "macro {name}{matchers} {{\n ...\n}}",
648 matchers = def
649 .body
650 .tokens
651 .get(0)
652 .map(|matcher| render_macro_matcher(tcx, matcher))
653 .unwrap_or_default(),
654 )
655 } else {
656 format!(
657 "macro {name} {{\n{arms}}}",
658 arms = render_macro_arms(tcx, &def.body.tokens, ",")
659 )
660 }
661 }
662}
663
664pub(crate) fn inherits_doc_hidden(
665 tcx: TyCtxt<'_>,
666 mut def_id: LocalDefId,
667 stop_at: Option<LocalDefId>,
668) -> bool {
669 while let Some(id) = tcx.opt_local_parent(def_id) {
670 if let Some(stop_at) = stop_at
671 && id == stop_at
672 {
673 return false;
674 }
675 def_id = id;
676 if tcx.is_doc_hidden(def_id.to_def_id()) {
677 return true;
678 } else if matches!(
679 tcx.hir_node_by_def_id(def_id),
680 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
681 ) {
682 return false;
685 }
686 }
687 false
688}
689
690#[inline]
691pub(crate) fn should_ignore_res(res: Res) -> bool {
692 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
693}