1use std::assert_matches::debug_assert_matches;
2use std::fmt::{self, Display, Write as _};
3use std::mem;
4use std::sync::LazyLock as Lazy;
5
6use rustc_ast::tokenstream::TokenTree;
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
9use rustc_metadata::rendered_const;
10use rustc_middle::mir;
11use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt};
12use rustc_span::symbol::{Symbol, kw, sym};
13use thin_vec::{ThinVec, thin_vec};
14use tracing::{debug, warn};
15use {rustc_ast as ast, rustc_hir as hir};
16
17use crate::clean::auto_trait::synthesize_auto_trait_impls;
18use crate::clean::blanket_impl::synthesize_blanket_impls;
19use crate::clean::render_macro_matchers::render_macro_matcher;
20use crate::clean::{
21 AssocItemConstraint, AssocItemConstraintKind, Crate, ExternalCrate, Generic, GenericArg,
22 GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path, PathSegment, Primitive,
23 PrimitiveType, Term, Type, clean_doc_module, clean_middle_const, clean_middle_region,
24 clean_middle_ty, inline,
25};
26use crate::core::DocContext;
27use crate::display::Joined as _;
28
29#[cfg(test)]
30mod tests;
31
32pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
33 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
34
35 let mut module = clean_doc_module(&module, cx);
38
39 match module.kind {
40 ItemKind::ModuleItem(ref module) => {
41 for it in &module.items {
42 if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
45 cx.cache.masked_crates.insert(it.item_id.krate());
46 } else if it.is_extern_crate()
47 && it.attrs.has_doc_flag(sym::masked)
48 && let Some(def_id) = it.item_id.as_def_id()
49 && let Some(local_def_id) = def_id.as_local()
50 && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
51 {
52 cx.cache.masked_crates.insert(cnum);
53 }
54 }
55 }
56 _ => unreachable!(),
57 }
58
59 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
60 let primitives = local_crate.primitives(cx.tcx);
61 let keywords = local_crate.keywords(cx.tcx);
62 {
63 let ItemKind::ModuleItem(m) = &mut module.inner.kind else { unreachable!() };
64 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
65 Item::from_def_id_and_parts(
66 def_id,
67 Some(prim.as_sym()),
68 ItemKind::PrimitiveItem(prim),
69 cx,
70 )
71 }));
72 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
73 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
74 }));
75 }
76
77 Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
78}
79
80pub(crate) fn clean_middle_generic_args<'tcx>(
81 cx: &mut DocContext<'tcx>,
82 args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
83 mut has_self: bool,
84 owner: DefId,
85) -> ThinVec<GenericArg> {
86 let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
87 if args.is_empty() {
88 return ThinVec::new();
90 }
91
92 let generics = cx.tcx.generics_of(owner);
97 let args = if !has_self && generics.parent.is_none() && generics.has_self {
98 has_self = true;
99 [cx.tcx.types.trait_object_dummy_self.into()]
100 .into_iter()
101 .chain(args.iter().copied())
102 .collect::<Vec<_>>()
103 .into()
104 } else {
105 std::borrow::Cow::from(args)
106 };
107
108 let mut elision_has_failed_once_before = false;
109 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
110 if has_self && index == 0 {
112 return None;
113 }
114
115 let param = generics.param_at(index, cx.tcx);
116 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
117
118 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
120 let default = default.instantiate(cx.tcx, args.as_ref());
121 if can_elide_generic_arg(arg, arg.rebind(default)) {
122 return None;
123 }
124 elision_has_failed_once_before = true;
125 }
126
127 match arg.skip_binder().unpack() {
128 GenericArgKind::Lifetime(lt) => {
129 Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
130 }
131 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
132 arg.rebind(ty),
133 cx,
134 None,
135 Some(crate::clean::ContainerTy::Regular {
136 ty: owner,
137 args: arg.rebind(args.as_ref()),
138 arg: index,
139 }),
140 ))),
141 GenericArgKind::Const(ct) => {
142 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
143 }
144 }
145 };
146
147 let offset = if has_self { 1 } else { 0 };
148 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
149 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
150 clean_args.reverse();
151 clean_args
152}
153
154fn can_elide_generic_arg<'tcx>(
160 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
161 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
162) -> bool {
163 debug_assert_matches!(
164 (actual.skip_binder().unpack(), default.skip_binder().unpack()),
165 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
166 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
167 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
168 );
169
170 if actual.has_infer() || default.has_infer() {
173 return false;
174 }
175
176 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
180 return false;
181 }
182
183 actual.skip_binder() == default.skip_binder()
197}
198
199fn clean_middle_generic_args_with_constraints<'tcx>(
200 cx: &mut DocContext<'tcx>,
201 did: DefId,
202 has_self: bool,
203 mut constraints: ThinVec<AssocItemConstraint>,
204 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
205) -> GenericArgs {
206 if cx.tcx.is_trait(did)
207 && cx.tcx.trait_def(did).paren_sugar
208 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
209 {
210 let inputs = tys
211 .iter()
212 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
213 .collect::<Vec<_>>()
214 .into();
215 let output = constraints.pop().and_then(|constraint| match constraint.kind {
216 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
217 Some(Box::new(ty))
218 }
219 _ => None,
220 });
221 return GenericArgs::Parenthesized { inputs, output };
222 }
223
224 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
225
226 GenericArgs::AngleBracketed { args, constraints }
227}
228
229pub(super) fn clean_middle_path<'tcx>(
230 cx: &mut DocContext<'tcx>,
231 did: DefId,
232 has_self: bool,
233 constraints: ThinVec<AssocItemConstraint>,
234 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
235) -> Path {
236 let def_kind = cx.tcx.def_kind(did);
237 let name = cx.tcx.opt_item_name(did).unwrap_or(kw::Empty);
238 Path {
239 res: Res::Def(def_kind, did),
240 segments: thin_vec![PathSegment {
241 name,
242 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
243 }],
244 }
245}
246
247pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
248 let segments = match *p {
249 hir::QPath::Resolved(_, path) => &path.segments,
250 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
251 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
252 };
253
254 fmt::from_fn(|f| {
255 segments
256 .iter()
257 .map(|seg| {
258 fmt::from_fn(|f| {
259 if seg.ident.name != kw::PathRoot {
260 write!(f, "{}", seg.ident)?;
261 }
262 Ok(())
263 })
264 })
265 .joined("::", f)
266 })
267 .to_string()
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::Wild
308 | PatKind::Err(_)
309 | PatKind::Never
310 | PatKind::Struct(..)
311 | PatKind::Range(..) => {
312 return kw::Underscore;
313 }
314 PatKind::Binding(_, _, ident, _) => return ident.name,
315 PatKind::Box(p) | 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 Symbol::intern("()");
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(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
356 match n.kind() {
357 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
358 let s = if let Some(def) = def.as_local() {
359 rendered_const(cx.tcx, cx.tcx.hir_body_owned_by(def), def)
360 } else {
361 inline::print_inlined_const(cx.tcx, def)
362 };
363
364 s
365 }
366 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
368 cv.valtree.unwrap_leaf().to_string()
369 }
370 _ => n.to_string(),
371 }
372}
373
374pub(crate) fn print_evaluated_const(
375 tcx: TyCtxt<'_>,
376 def_id: DefId,
377 with_underscores: bool,
378 with_type: bool,
379) -> Option<String> {
380 tcx.const_eval_poly(def_id).ok().and_then(|val| {
381 let ty = tcx.type_of(def_id).instantiate_identity();
382 match (val, ty.kind()) {
383 (_, &ty::Ref(..)) => None,
384 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
385 (mir::ConstValue::Scalar(_), _) => {
386 let const_ = mir::Const::from_value(val, ty);
387 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
388 }
389 _ => None,
390 }
391 })
392}
393
394fn format_integer_with_underscore_sep(num: &str) -> String {
395 let num_chars: Vec<_> = num.chars().collect();
396 let mut num_start_index = if num_chars.first() == Some(&'-') { 1 } else { 0 };
397 let chunk_size = match &num.as_bytes()[num_start_index..] {
398 [b'0', b'b' | b'x', ..] => {
399 num_start_index += 2;
400 4
401 }
402 [b'0', b'o', ..] => {
403 num_start_index += 2;
404 let remaining_chars = num_chars.len() - num_start_index;
405 if remaining_chars <= 6 {
406 return num.to_string();
408 }
409 3
410 }
411 _ => 3,
412 };
413
414 num_chars[..num_start_index]
415 .iter()
416 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
417 .collect()
418}
419
420fn print_const_with_custom_print_scalar<'tcx>(
421 tcx: TyCtxt<'tcx>,
422 ct: mir::Const<'tcx>,
423 with_underscores: bool,
424 with_type: bool,
425) -> String {
426 match (ct, ct.ty().kind()) {
429 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
430 let mut output = if with_underscores {
431 format_integer_with_underscore_sep(&int.to_string())
432 } else {
433 int.to_string()
434 };
435 if with_type {
436 output += ui.name_str();
437 }
438 output
439 }
440 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
441 let ty = ct.ty();
442 let size = tcx
443 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
444 .unwrap()
445 .size;
446 let sign_extended_data = int.assert_scalar_int().to_int(size);
447 let mut output = if with_underscores {
448 format_integer_with_underscore_sep(&sign_extended_data.to_string())
449 } else {
450 sign_extended_data.to_string()
451 };
452 if with_type {
453 output += i.name_str();
454 }
455 output
456 }
457 _ => ct.to_string(),
458 }
459}
460
461pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
462 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
463 if let hir::ExprKind::Lit(_) = &expr.kind {
464 return true;
465 }
466
467 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
468 && let hir::ExprKind::Lit(_) = &expr.kind
469 {
470 return true;
471 }
472 }
473
474 false
475}
476
477pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
479 debug!("resolve_type({path:?})");
480
481 match path.res {
482 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
483 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
484 Type::SelfTy
485 }
486 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
487 _ => {
488 let _ = register_res(cx, path.res);
489 Type::Path { path }
490 }
491 }
492}
493
494pub(crate) fn synthesize_auto_trait_and_blanket_impls(
495 cx: &mut DocContext<'_>,
496 item_def_id: DefId,
497) -> impl Iterator<Item = Item> + use<> {
498 let auto_impls = cx
499 .sess()
500 .prof
501 .generic_activity("synthesize_auto_trait_impls")
502 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
503 let blanket_impls = cx
504 .sess()
505 .prof
506 .generic_activity("synthesize_blanket_impls")
507 .run(|| synthesize_blanket_impls(cx, item_def_id));
508 auto_impls.into_iter().chain(blanket_impls)
509}
510
511pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
517 use DefKind::*;
518 debug!("register_res({res:?})");
519
520 let (kind, did) = match res {
521 Res::Def(
522 kind @ (AssocTy
523 | AssocFn
524 | AssocConst
525 | Variant
526 | Fn
527 | TyAlias
528 | Enum
529 | Trait
530 | Struct
531 | Union
532 | Mod
533 | ForeignTy
534 | Const
535 | Static { .. }
536 | Macro(..)
537 | TraitAlias),
538 did,
539 ) => (kind.into(), did),
540
541 _ => panic!("register_res: unexpected {res:?}"),
542 };
543 if did.is_local() {
544 return did;
545 }
546 inline::record_extern_fqn(cx, did, kind);
547 did
548}
549
550pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
551 ImportSource {
552 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
553 path,
554 }
555}
556
557pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
558where
559 F: FnOnce(&mut DocContext<'tcx>) -> R,
560{
561 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
562 let r = f(cx);
563 assert!(cx.impl_trait_bounds.is_empty());
564 cx.impl_trait_bounds = old_bounds;
565 r
566}
567
568pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
570 if def_id.is_top_level_module() {
571 Some(def_id)
573 } else {
574 let mut current = def_id;
575 while let Some(parent) = tcx.opt_parent(current) {
578 if tcx.def_kind(parent) == DefKind::Mod {
579 return Some(parent);
580 }
581 current = parent;
582 }
583 None
584 }
585}
586
587pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
597 attrs_have_doc_flag(tcx.get_attrs(did, sym::doc), flag)
598}
599
600pub(crate) fn attrs_have_doc_flag<'a>(
601 mut attrs: impl Iterator<Item = &'a hir::Attribute>,
602 flag: Symbol,
603) -> bool {
604 attrs.any(|attr| attr.meta_item_list().is_some_and(|l| ast::attr::list_contains_name(&l, flag)))
605}
606
607pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
612pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
613 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
614
615fn render_macro_arms<'a>(
618 tcx: TyCtxt<'_>,
619 matchers: impl Iterator<Item = &'a TokenTree>,
620 arm_delim: &str,
621) -> String {
622 let mut out = String::new();
623 for matcher in matchers {
624 writeln!(
625 out,
626 " {matcher} => {{ ... }}{arm_delim}",
627 matcher = render_macro_matcher(tcx, matcher),
628 )
629 .unwrap();
630 }
631 out
632}
633
634pub(super) fn display_macro_source(
635 cx: &mut DocContext<'_>,
636 name: Symbol,
637 def: &ast::MacroDef,
638) -> String {
639 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
641
642 if def.macro_rules {
643 format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
644 } else {
645 if matchers.len() <= 1 {
646 format!(
647 "macro {name}{matchers} {{\n ...\n}}",
648 matchers = matchers
649 .map(|matcher| render_macro_matcher(cx.tcx, matcher))
650 .collect::<String>(),
651 )
652 } else {
653 format!("macro {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ","))
654 }
655 }
656}
657
658pub(crate) fn inherits_doc_hidden(
659 tcx: TyCtxt<'_>,
660 mut def_id: LocalDefId,
661 stop_at: Option<LocalDefId>,
662) -> bool {
663 while let Some(id) = tcx.opt_local_parent(def_id) {
664 if let Some(stop_at) = stop_at
665 && id == stop_at
666 {
667 return false;
668 }
669 def_id = id;
670 if tcx.is_doc_hidden(def_id.to_def_id()) {
671 return true;
672 } else if matches!(
673 tcx.hir_node_by_def_id(def_id),
674 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
675 ) {
676 return false;
679 }
680 }
681 false
682}
683
684#[inline]
685pub(crate) fn should_ignore_res(res: Res) -> bool {
686 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
687}