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