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