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::def_id::ModId;
20use rustc_span::symbol::{Symbol, kw, sym};
21use tracing::{debug, warn};
22
23use crate::clean::auto_trait::synthesize_auto_trait_impls;
24use crate::clean::blanket_impl::synthesize_blanket_impls;
25use crate::clean::render_macro_matchers::render_macro_matcher;
26use crate::clean::{
27 AssocItemConstraint, AssocItemConstraintKind, Crate, ExternalCrate, Generic, GenericArg,
28 GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path, PathSegment, Primitive,
29 PrimitiveType, Term, Type, clean_doc_module, clean_middle_const, clean_middle_region,
30 clean_middle_ty, inline,
31};
32use crate::core::DocContext;
33use crate::display::Joined as _;
34use crate::formats::item_type::ItemType;
35
36#[cfg(test)]
37mod tests;
38
39pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
40 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
41
42 let mut module = clean_doc_module(&module, cx);
45
46 match module.kind {
47 ItemKind::ModuleItem(ref module) => {
48 for it in &module.items {
49 if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
52 cx.cache.masked_crates.insert(it.item_id.krate());
53 } else if it.is_extern_crate()
54 && it.attrs.has_doc_flag(|d| d.masked.is_some())
55 && let Some(def_id) = it.item_id.as_def_id()
56 && let Some(local_def_id) = def_id.as_local()
57 && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
58 {
59 cx.cache.masked_crates.insert(cnum);
60 }
61 }
62 }
63 _ => unreachable!(),
64 }
65
66 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
67 let primitives = local_crate.primitives(cx.tcx);
68 let keywords = local_crate.keywords(cx.tcx);
69 let documented_attributes = local_crate.documented_attributes(cx.tcx);
70 {
71 let ItemKind::ModuleItem(m) = &mut module.inner.kind else { unreachable!() };
72 m.items.extend(primitives.map(|(def_id, prim)| {
73 Item::from_def_id_and_parts(
74 def_id,
75 Some(prim.as_sym()),
76 ItemKind::PrimitiveItem(prim),
77 cx.tcx,
78 )
79 }));
80 m.items.extend(keywords.map(|(def_id, kw)| {
81 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx.tcx)
82 }));
83 m.items.extend(documented_attributes.into_iter().map(|(def_id, kw)| {
84 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::AttributeItem, cx.tcx)
85 }));
86 }
87
88 Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
89}
90
91pub(crate) fn clean_middle_generic_args<'tcx>(
92 cx: &mut DocContext<'tcx>,
93 args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
94 mut has_self: bool,
95 owner: DefId,
96) -> ThinVec<GenericArg> {
97 let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
98 if args.is_empty() {
99 return ThinVec::new();
101 }
102
103 let generics = cx.tcx.generics_of(owner);
108 let args = if !has_self && generics.has_own_self() {
109 has_self = true;
110 [cx.tcx.types.trait_object_dummy_self.into()]
111 .into_iter()
112 .chain(args.iter().copied())
113 .collect::<Vec<_>>()
114 .into()
115 } else {
116 std::borrow::Cow::from(args)
117 };
118
119 let mut elision_has_failed_once_before = false;
120
121 let index_offset = generics.count() - args.len();
123 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
124 if has_self && index == 0 {
126 return None;
127 }
128
129 let param = generics.param_at(index + index_offset, cx.tcx);
131 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
132
133 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
135 let default = default.instantiate(cx.tcx, args.as_ref()).skip_normalization();
136 if can_elide_generic_arg(arg, arg.rebind(default)) {
137 return None;
138 }
139 elision_has_failed_once_before = true;
140 }
141
142 match arg.skip_binder().kind() {
143 GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
144 clean_middle_region(lt, cx.tcx).unwrap_or(Lifetime::elided()),
145 )),
146 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
147 arg.rebind(ty),
148 cx,
149 None,
150 Some(crate::clean::ContainerTy::Regular {
151 ty: owner,
152 args: arg.rebind(args.as_ref()),
153 arg: index,
154 }),
155 ))),
156 GenericArgKind::Const(ct) => {
157 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct)))))
158 }
159 }
160 };
161
162 let offset = if has_self { 1 } else { 0 };
163 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
164 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
165 clean_args.reverse();
166 clean_args
167}
168
169fn can_elide_generic_arg<'tcx>(
175 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
176 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
177) -> bool {
178 debug_assert_matches!(
179 (actual.skip_binder().kind(), default.skip_binder().kind()),
180 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
181 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
182 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
183 );
184
185 if actual.has_infer() || default.has_infer() {
188 return false;
189 }
190
191 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
195 return false;
196 }
197
198 actual.skip_binder() == default.skip_binder()
212}
213
214fn clean_middle_generic_args_with_constraints<'tcx>(
215 cx: &mut DocContext<'tcx>,
216 did: DefId,
217 has_self: bool,
218 mut constraints: ThinVec<AssocItemConstraint>,
219 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
220) -> GenericArgs {
221 if cx.tcx.is_trait(did)
222 && cx.tcx.trait_def(did).paren_sugar
223 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
224 {
225 let inputs = tys
226 .iter()
227 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
228 .collect::<Vec<_>>()
229 .into();
230 let output = constraints.pop().and_then(|constraint| match constraint.kind {
231 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
232 Some(Box::new(ty))
233 }
234 _ => None,
235 });
236 return GenericArgs::Parenthesized { inputs, output };
237 }
238
239 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
240
241 GenericArgs::AngleBracketed { args, constraints }
242}
243
244pub(super) fn clean_middle_path<'tcx>(
245 cx: &mut DocContext<'tcx>,
246 did: DefId,
247 has_self: bool,
248 constraints: ThinVec<AssocItemConstraint>,
249 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
250) -> Path {
251 let def_kind = cx.tcx.def_kind(did);
252 let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
253 Path {
254 res: Res::Def(def_kind, did),
255 segments: thin_vec![PathSegment {
256 name,
257 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
258 }],
259 }
260}
261
262pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
263 let segments = match *p {
264 hir::QPath::Resolved(_, path) => &path.segments,
265 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
266 };
267
268 join_path_idents(segments.iter().map(|seg| seg.ident))
269}
270
271pub(crate) fn build_deref_target_impls(
272 cx: &mut DocContext<'_>,
273 items: &[Item],
274 ret: &mut Vec<Item>,
275) {
276 let tcx = cx.tcx;
277
278 for item in items {
279 let target = match item.kind {
280 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
281 _ => continue,
282 };
283
284 if let Some(prim) = target.primitive_type() {
285 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
286 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
287 cx.with_param_env(did, |cx| {
288 inline::build_impl(cx, did, None, ret);
289 });
290 }
291 } else if let Type::Path { path } = target {
292 let did = path.def_id();
293 if !did.is_local() {
294 cx.with_param_env(did, |cx| {
295 inline::build_impls(cx, did, None, ret);
296 });
297 }
298 }
299 }
300}
301
302pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
303 use rustc_hir::*;
304 debug!("trying to get a name from pattern: {p:?}");
305
306 Symbol::intern(&match &p.kind {
307 PatKind::Err(_)
308 | PatKind::Missing | PatKind::Never
310 | PatKind::Range(..)
311 | PatKind::Struct(..)
312 | PatKind::Wild => {
313 return kw::Underscore;
314 }
315 PatKind::Binding(_, _, ident, _) => return ident.name,
316 PatKind::Box(p) | PatKind::Ref(p, _, _) | PatKind::Guard(p, _) => return name_from_pat(p),
317 PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
318 qpath_to_string(p)
319 }
320 PatKind::Or(pats) => {
321 fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
322 }
323 PatKind::Tuple(elts, _) => {
324 format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
325 }
326 PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
327 PatKind::Expr(..) => {
328 warn!(
329 "tried to get argument name from PatKind::Expr, which is silly in function arguments"
330 );
331 return sym::empty_parens;
332 }
333 PatKind::Slice(begin, mid, end) => {
334 fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
335 fmt::from_fn(move |f| {
336 if wild {
337 f.write_str("..")?;
338 }
339 name_from_pat(pat).fmt(f)
340 })
341 }
342
343 format!(
344 "[{}]",
345 fmt::from_fn(|f| {
346 let begin = begin.iter().map(|p| print_pat(p, false));
347 let mid = mid.map(|p| print_pat(p, true));
348 let end = end.iter().map(|p| print_pat(p, false));
349 begin.chain(mid).chain(end).joined(", ", f)
350 })
351 )
352 }
353 })
354}
355
356pub(crate) fn print_const(tcx: TyCtxt<'_>, n: ty::Const<'_>) -> String {
357 match n.kind() {
358 ty::ConstKind::Alias(_, ty::AliasConst { kind, .. }) => {
359 let def_id: DefId = match kind {
360 ty::AliasConstKind::Projection { def_id } => def_id.into(),
361 ty::AliasConstKind::Inherent { 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}