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, 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, AssocType, Crate, ExternalCrate, Generic,
27 GenericArg, 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::Module(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::Module(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::PrimitiveType(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::Keyword, 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::Attribute, 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, ty::GenericArgs<'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.mk_args_from_iter(
110 [cx.tcx.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()),
111 )
112 } else {
113 args
114 };
115
116 let mut elision_has_failed_once_before = false;
117
118 let index_offset = generics.count() - args.len();
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 + index_offset, cx.tcx);
128 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
129
130 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
132 let default = default.instantiate(cx.tcx, args.as_ref()).skip_normalization();
133 if can_elide_generic_arg(arg, arg.rebind(default)) {
134 return None;
135 }
136 elision_has_failed_once_before = true;
137 }
138
139 match arg.skip_binder().kind() {
140 GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
141 clean_middle_region(lt, cx.tcx).unwrap_or(Lifetime::elided()),
142 )),
143 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
144 arg.rebind(ty),
145 cx,
146 None,
147 Some(crate::clean::ContainerTy::Regular {
148 ty: owner,
149 args: arg.rebind(args.as_ref()),
150 arg: index,
151 }),
152 ))),
153 GenericArgKind::Const(ct) => {
154 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct)))))
155 }
156 }
157 };
158
159 let offset = if has_self { 1 } else { 0 };
160 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
161 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
162 clean_args.reverse();
163 clean_args
164}
165
166fn can_elide_generic_arg<'tcx>(
172 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
173 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
174) -> bool {
175 debug_assert_matches!(
176 (actual.skip_binder().kind(), default.skip_binder().kind()),
177 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
178 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
179 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
180 );
181
182 if actual.has_infer() || default.has_infer() {
185 return false;
186 }
187
188 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
192 return false;
193 }
194
195 actual.skip_binder() == default.skip_binder()
209}
210
211fn clean_middle_generic_args_with_constraints<'tcx>(
212 cx: &mut DocContext<'tcx>,
213 did: DefId,
214 has_self: bool,
215 mut constraints: ThinVec<AssocItemConstraint>,
216 args: ty::Binder<'tcx, ty::GenericArgs<'tcx>>,
217) -> GenericArgs {
218 if cx.tcx.is_trait(did)
219 && cx.tcx.trait_def(did).paren_sugar
220 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
221 {
222 let inputs = tys
223 .iter()
224 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
225 .collect::<Vec<_>>()
226 .into();
227 let output = constraints.pop().and_then(|constraint| match constraint.kind {
228 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
229 Some(Box::new(ty))
230 }
231 _ => None,
232 });
233 return GenericArgs::Parenthesized { inputs, output };
234 }
235
236 let args = clean_middle_generic_args(cx, args, has_self, did);
237
238 GenericArgs::AngleBracketed { args, constraints }
239}
240
241pub(super) fn clean_middle_path<'tcx>(
242 cx: &mut DocContext<'tcx>,
243 did: DefId,
244 has_self: bool,
245 constraints: ThinVec<AssocItemConstraint>,
246 args: ty::Binder<'tcx, ty::GenericArgs<'tcx>>,
247) -> Path {
248 let def_kind = cx.tcx.def_kind(did);
249 let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
250 Path {
251 res: Res::Def(def_kind, did),
252 segments: thin_vec![PathSegment {
253 name,
254 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
255 }],
256 }
257}
258
259pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
260 let segments = match *p {
261 hir::QPath::Resolved(_, path) => &path.segments,
262 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
263 };
264
265 join_path_idents(segments.iter().map(|seg| seg.ident))
266}
267
268pub(crate) fn build_deref_target_impls(
269 cx: &mut DocContext<'_>,
270 items: &[Item],
271 ret: &mut Vec<Item>,
272) {
273 let tcx = cx.tcx;
274
275 for item in items {
276 let ItemKind::AssocType(AssocType { type_: Some(target), .. }) = &item.kind else {
277 continue;
278 };
279
280 if let Some(prim) = target.type_.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.type_ {
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::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 }
357 | ty::AliasConstKind::InherentSelf { def_id }
358 | ty::AliasConstKind::InherentImpl { def_id }
359 | ty::AliasConstKind::Free { def_id }
360 | ty::AliasConstKind::Anon { def_id } => def_id,
361 };
362 if let Some(local_def_id) = def_id.as_local()
363 && let Some(body_id) = tcx.hir_maybe_body_owned_by(local_def_id)
364 {
365 rendered_const(tcx, body_id, local_def_id)
366 } else {
367 n.to_string()
368 }
369 }
370 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
372 cv.to_leaf().to_string()
373 }
374 _ => n.to_string(),
375 }
376}
377
378pub(crate) fn print_evaluated_const(
379 tcx: TyCtxt<'_>,
380 def_id: DefId,
381 with_underscores: bool,
382 with_type: bool,
383) -> Option<String> {
384 tcx.const_eval_poly(def_id).ok().and_then(|val| {
385 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
386 match (val, ty.kind()) {
387 (_, &ty::Ref(..)) => None,
388 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
389 (mir::ConstValue::Scalar(_), _) => {
390 let const_ = mir::Const::from_value(val, ty);
391 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
392 }
393 _ => None,
394 }
395 })
396}
397
398fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
399 let num = num.to_string();
400 let chars = num.as_ascii().unwrap();
401 let mut result = if is_negative { "-".to_string() } else { String::new() };
402 result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
403 result
404}
405
406fn print_const_with_custom_print_scalar<'tcx>(
407 tcx: TyCtxt<'tcx>,
408 ct: mir::Const<'tcx>,
409 with_underscores: bool,
410 with_type: bool,
411) -> String {
412 match (ct, ct.ty().kind()) {
415 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
416 let mut output = if with_underscores {
417 format_integer_with_underscore_sep(
418 int.assert_scalar_int().to_bits_unchecked(),
419 false,
420 )
421 } else {
422 int.to_string()
423 };
424 if with_type {
425 output += ui.name_str();
426 }
427 output
428 }
429 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
430 let ty = ct.ty();
431 let size = tcx
432 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
433 .unwrap()
434 .size;
435 let sign_extended_data = int.assert_scalar_int().to_int(size);
436 let mut output = if with_underscores {
437 format_integer_with_underscore_sep(
438 sign_extended_data.unsigned_abs(),
439 sign_extended_data.is_negative(),
440 )
441 } else {
442 sign_extended_data.to_string()
443 };
444 if with_type {
445 output += i.name_str();
446 }
447 output
448 }
449 _ => ct.to_string(),
450 }
451}
452
453pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
454 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
455 if let hir::ExprKind::Lit(_) = &expr.kind {
456 return true;
457 }
458
459 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
460 && let hir::ExprKind::Lit(_) = &expr.kind
461 {
462 return true;
463 }
464 }
465
466 false
467}
468
469pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
471 debug!("resolve_type({path:?})");
472
473 match path.res {
474 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
475 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
476 Type::SelfTy
477 }
478 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
479 _ => {
480 let _ = register_res(cx, path.res);
481 Type::Path { path }
482 }
483 }
484}
485
486pub(crate) fn synthesize_auto_trait_and_blanket_impls(
487 cx: &mut DocContext<'_>,
488 item_def_id: DefId,
489) -> impl Iterator<Item = Item> + use<> {
490 let auto_impls = cx
491 .sess()
492 .prof
493 .generic_activity("synthesize_auto_trait_impls")
494 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
495 let blanket_impls = cx
496 .sess()
497 .prof
498 .generic_activity("synthesize_blanket_impls")
499 .run(|| synthesize_blanket_impls(cx, item_def_id));
500 auto_impls.into_iter().chain(blanket_impls)
501}
502
503pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
509 use DefKind::*;
510 debug!("register_res({res:?})");
511
512 let (kind, did) = match res {
513 Res::Def(
514 AssocTy
515 | AssocFn
516 | AssocConst { .. }
517 | Variant
518 | Fn
519 | TyAlias
520 | Enum
521 | Trait
522 | Struct
523 | Union
524 | Mod
525 | ForeignTy
526 | Const { .. }
527 | Static { .. }
528 | Macro(..)
529 | TraitAlias,
530 did,
531 ) => (ItemType::from_def_id(did, cx.tcx), did),
532
533 _ => panic!("register_res: unexpected {res:?}"),
534 };
535 if did.is_local() {
536 return did;
537 }
538 inline::record_extern_fqn(cx, did, kind);
539 did
540}
541
542pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
543 ImportSource {
544 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
545 path,
546 }
547}
548
549pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
550where
551 F: FnOnce(&mut DocContext<'tcx>) -> R,
552{
553 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
554 let r = f(cx);
555 assert!(cx.impl_trait_bounds.is_empty());
556 cx.impl_trait_bounds = old_bounds;
557 r
558}
559
560pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ModId> {
562 if def_id.is_top_level_module() {
563 Some(ModId::new_unchecked(def_id))
565 } else {
566 let mut current = def_id;
567 while let Some(parent) = tcx.opt_parent(current) {
570 if tcx.def_kind(parent) == DefKind::Mod {
571 return Some(ModId::new_unchecked(parent));
572 }
573 current = parent;
574 }
575 None
576 }
577}
578
579pub(crate) fn has_doc_flag<F: Fn(&DocAttribute) -> bool>(
582 tcx: TyCtxt<'_>,
583 did: DefId,
584 callback: F,
585) -> bool {
586 find_attr!(tcx, did, Doc(d) if callback(d))
587}
588
589pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
594pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
595 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
596
597fn render_macro_arms(
600 tcx: TyCtxt<'_>,
601 tokens: &rustc_ast::tokenstream::TokenStream,
602 arm_delim: &str,
603) -> String {
604 let mut tokens = tokens.iter();
605 let mut out = String::new();
606 while let Some(mut token) = tokens.next() {
607 let pre = if matches!(token, TokenTree::Token(..)) {
612 let pre = format!("{}() ", render_macro_matcher(tcx, token));
613 tokens.next();
615 let Some(next) = tokens.next() else {
616 return out;
617 };
618 token = next;
619 pre
620 } else {
621 String::new()
622 };
623 writeln!(
624 out,
625 " {pre}{matcher} => {{ ... }}{arm_delim}",
626 matcher = render_macro_matcher(tcx, token),
627 )
628 .unwrap();
629 let _token = tokens.next();
632 debug_assert_matches!(
634 _token,
635 Some(TokenTree::Token(Token { kind: TokenKind::FatArrow, .. }, _))
636 );
637 let _token = tokens.next();
638 debug_assert_matches!(_token, Some(TokenTree::Delimited(..)));
640 let _token = tokens.next();
642 debug_assert_matches!(_token, None | Some(TokenTree::Token(Token { .. }, _)));
643 }
644 out
645}
646
647pub(super) fn display_macro_source(tcx: TyCtxt<'_>, name: Symbol, def: &ast::MacroDef) -> String {
648 if def.macro_rules {
650 format!(
651 "macro_rules! {name} {{\n{arms}}}",
652 arms = render_macro_arms(tcx, &def.body.tokens, ";")
653 )
654 } else {
655 if def.body.tokens.len() <= 4 {
656 format!(
657 "macro {name}{matchers} {{\n ...\n}}",
658 matchers = def
659 .body
660 .tokens
661 .get(0)
662 .map(|matcher| render_macro_matcher(tcx, matcher))
663 .unwrap_or_default(),
664 )
665 } else {
666 format!(
667 "macro {name} {{\n{arms}}}",
668 arms = render_macro_arms(tcx, &def.body.tokens, ",")
669 )
670 }
671 }
672}
673
674pub(crate) fn inherits_doc_hidden(
675 tcx: TyCtxt<'_>,
676 mut def_id: LocalDefId,
677 stop_at: Option<LocalDefId>,
678) -> bool {
679 while let Some(id) = tcx.opt_local_parent(def_id) {
680 if let Some(stop_at) = stop_at
681 && id == stop_at
682 {
683 return false;
684 }
685 def_id = id;
686 if tcx.is_doc_hidden(def_id.to_def_id()) {
687 return true;
688 } else if matches!(
689 tcx.hir_node_by_def_id(def_id),
690 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
691 ) {
692 return false;
695 }
696 }
697 false
698}
699
700#[inline]
701pub(crate) fn should_ignore_res(res: Res) -> bool {
702 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
703}