1use std::assert_matches::debug_assert_matches;
2use std::fmt::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;
27
28#[cfg(test)]
29mod tests;
30
31pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
32 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
33
34 let mut module = clean_doc_module(&module, cx);
37
38 match module.kind {
39 ItemKind::ModuleItem(ref module) => {
40 for it in &module.items {
41 if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
44 cx.cache.masked_crates.insert(it.item_id.krate());
45 } else if it.is_extern_crate()
46 && it.attrs.has_doc_flag(sym::masked)
47 && let Some(def_id) = it.item_id.as_def_id()
48 && let Some(local_def_id) = def_id.as_local()
49 && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
50 {
51 cx.cache.masked_crates.insert(cnum);
52 }
53 }
54 }
55 _ => unreachable!(),
56 }
57
58 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
59 let primitives = local_crate.primitives(cx.tcx);
60 let keywords = local_crate.keywords(cx.tcx);
61 {
62 let ItemKind::ModuleItem(ref mut m) = &mut module.inner.kind else { unreachable!() };
63 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
64 Item::from_def_id_and_parts(
65 def_id,
66 Some(prim.as_sym()),
67 ItemKind::PrimitiveItem(prim),
68 cx,
69 )
70 }));
71 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
72 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
73 }));
74 }
75
76 Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
77}
78
79pub(crate) fn clean_middle_generic_args<'tcx>(
80 cx: &mut DocContext<'tcx>,
81 args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
82 mut has_self: bool,
83 owner: DefId,
84) -> ThinVec<GenericArg> {
85 let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
86 if args.is_empty() {
87 return ThinVec::new();
89 }
90
91 let generics = cx.tcx.generics_of(owner);
96 let args = if !has_self && generics.parent.is_none() && generics.has_self {
97 has_self = true;
98 [cx.tcx.types.trait_object_dummy_self.into()]
99 .into_iter()
100 .chain(args.iter().copied())
101 .collect::<Vec<_>>()
102 .into()
103 } else {
104 std::borrow::Cow::from(args)
105 };
106
107 let mut elision_has_failed_once_before = false;
108 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
109 if has_self && index == 0 {
111 return None;
112 }
113
114 let param = generics.param_at(index, cx.tcx);
115 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
116
117 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
119 let default = default.instantiate(cx.tcx, args.as_ref());
120 if can_elide_generic_arg(arg, arg.rebind(default)) {
121 return None;
122 }
123 elision_has_failed_once_before = true;
124 }
125
126 match arg.skip_binder().unpack() {
127 GenericArgKind::Lifetime(lt) => {
128 Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
129 }
130 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
131 arg.rebind(ty),
132 cx,
133 None,
134 Some(crate::clean::ContainerTy::Regular {
135 ty: owner,
136 args: arg.rebind(args.as_ref()),
137 arg: index,
138 }),
139 ))),
140 GenericArgKind::Const(ct) => {
141 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
142 }
143 }
144 };
145
146 let offset = if has_self { 1 } else { 0 };
147 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
148 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
149 clean_args.reverse();
150 clean_args
151}
152
153fn can_elide_generic_arg<'tcx>(
159 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
160 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
161) -> bool {
162 debug_assert_matches!(
163 (actual.skip_binder().unpack(), default.skip_binder().unpack()),
164 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
165 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
166 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
167 );
168
169 if actual.has_infer() || default.has_infer() {
172 return false;
173 }
174
175 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
179 return false;
180 }
181
182 actual.skip_binder() == default.skip_binder()
196}
197
198fn clean_middle_generic_args_with_constraints<'tcx>(
199 cx: &mut DocContext<'tcx>,
200 did: DefId,
201 has_self: bool,
202 mut constraints: ThinVec<AssocItemConstraint>,
203 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
204) -> GenericArgs {
205 if cx.tcx.is_trait(did)
206 && cx.tcx.trait_def(did).paren_sugar
207 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
208 {
209 let inputs = tys
210 .iter()
211 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
212 .collect::<Vec<_>>()
213 .into();
214 let output = constraints.pop().and_then(|constraint| match constraint.kind {
215 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
216 Some(Box::new(ty))
217 }
218 _ => None,
219 });
220 return GenericArgs::Parenthesized { inputs, output };
221 }
222
223 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
224
225 GenericArgs::AngleBracketed { args: args.into(), constraints }
226}
227
228pub(super) fn clean_middle_path<'tcx>(
229 cx: &mut DocContext<'tcx>,
230 did: DefId,
231 has_self: bool,
232 constraints: ThinVec<AssocItemConstraint>,
233 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
234) -> Path {
235 let def_kind = cx.tcx.def_kind(did);
236 let name = cx.tcx.opt_item_name(did).unwrap_or(kw::Empty);
237 Path {
238 res: Res::Def(def_kind, did),
239 segments: thin_vec![PathSegment {
240 name,
241 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
242 }],
243 }
244}
245
246pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
247 let segments = match *p {
248 hir::QPath::Resolved(_, path) => &path.segments,
249 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
250 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
251 };
252
253 let mut s = String::new();
254 for (i, seg) in segments.iter().enumerate() {
255 if i > 0 {
256 s.push_str("::");
257 }
258 if seg.ident.name != kw::PathRoot {
259 s.push_str(seg.ident.as_str());
260 }
261 }
262 s
263}
264
265pub(crate) fn build_deref_target_impls(
266 cx: &mut DocContext<'_>,
267 items: &[Item],
268 ret: &mut Vec<Item>,
269) {
270 let tcx = cx.tcx;
271
272 for item in items {
273 let target = match item.kind {
274 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
275 _ => continue,
276 };
277
278 if let Some(prim) = target.primitive_type() {
279 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
280 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
281 cx.with_param_env(did, |cx| {
282 inline::build_impl(cx, did, None, ret);
283 });
284 }
285 } else if let Type::Path { path } = target {
286 let did = path.def_id();
287 if !did.is_local() {
288 cx.with_param_env(did, |cx| {
289 inline::build_impls(cx, did, None, ret);
290 });
291 }
292 }
293 }
294}
295
296pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
297 use rustc_hir::*;
298 debug!("trying to get a name from pattern: {p:?}");
299
300 Symbol::intern(&match p.kind {
301 PatKind::Wild | PatKind::Err(_) | PatKind::Never | PatKind::Struct(..) => {
303 return kw::Underscore;
304 }
305 PatKind::Binding(_, _, ident, _) => return ident.name,
306 PatKind::TupleStruct(ref p, ..)
307 | PatKind::Expr(PatExpr { kind: PatExprKind::Path(ref p), .. }) => qpath_to_string(p),
308 PatKind::Or(pats) => {
309 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
310 }
311 PatKind::Tuple(elts, _) => format!(
312 "({})",
313 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
314 ),
315 PatKind::Box(p) => return name_from_pat(p),
316 PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
317 PatKind::Ref(p, _) => return name_from_pat(p),
318 PatKind::Expr(..) => {
319 warn!(
320 "tried to get argument name from PatKind::Expr, which is silly in function arguments"
321 );
322 return Symbol::intern("()");
323 }
324 PatKind::Guard(p, _) => return name_from_pat(p),
325 PatKind::Range(..) => return kw::Underscore,
326 PatKind::Slice(begin, ref mid, end) => {
327 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
328 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(p))).into_iter();
329 let end = end.iter().map(|p| name_from_pat(p).to_string());
330 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
331 }
332 })
333}
334
335pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
336 match n.kind() {
337 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
338 let s = if let Some(def) = def.as_local() {
339 rendered_const(cx.tcx, cx.tcx.hir().body_owned_by(def), def)
340 } else {
341 inline::print_inlined_const(cx.tcx, def)
342 };
343
344 s
345 }
346 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
348 cv.valtree.unwrap_leaf().to_string()
349 }
350 _ => n.to_string(),
351 }
352}
353
354pub(crate) fn print_evaluated_const(
355 tcx: TyCtxt<'_>,
356 def_id: DefId,
357 with_underscores: bool,
358 with_type: bool,
359) -> Option<String> {
360 tcx.const_eval_poly(def_id).ok().and_then(|val| {
361 let ty = tcx.type_of(def_id).instantiate_identity();
362 match (val, ty.kind()) {
363 (_, &ty::Ref(..)) => None,
364 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
365 (mir::ConstValue::Scalar(_), _) => {
366 let const_ = mir::Const::from_value(val, ty);
367 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
368 }
369 _ => None,
370 }
371 })
372}
373
374fn format_integer_with_underscore_sep(num: &str) -> String {
375 let num_chars: Vec<_> = num.chars().collect();
376 let mut num_start_index = if num_chars.first() == Some(&'-') { 1 } else { 0 };
377 let chunk_size = match num[num_start_index..].as_bytes() {
378 [b'0', b'b' | b'x', ..] => {
379 num_start_index += 2;
380 4
381 }
382 [b'0', b'o', ..] => {
383 num_start_index += 2;
384 let remaining_chars = num_chars.len() - num_start_index;
385 if remaining_chars <= 6 {
386 return num.to_string();
388 }
389 3
390 }
391 _ => 3,
392 };
393
394 num_chars[..num_start_index]
395 .iter()
396 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
397 .collect()
398}
399
400fn print_const_with_custom_print_scalar<'tcx>(
401 tcx: TyCtxt<'tcx>,
402 ct: mir::Const<'tcx>,
403 with_underscores: bool,
404 with_type: bool,
405) -> String {
406 match (ct, ct.ty().kind()) {
409 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
410 let mut output = if with_underscores {
411 format_integer_with_underscore_sep(&int.to_string())
412 } else {
413 int.to_string()
414 };
415 if with_type {
416 output += ui.name_str();
417 }
418 output
419 }
420 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
421 let ty = ct.ty();
422 let size = tcx
423 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
424 .unwrap()
425 .size;
426 let sign_extended_data = int.assert_scalar_int().to_int(size);
427 let mut output = if with_underscores {
428 format_integer_with_underscore_sep(&sign_extended_data.to_string())
429 } else {
430 sign_extended_data.to_string()
431 };
432 if with_type {
433 output += i.name_str();
434 }
435 output
436 }
437 _ => ct.to_string(),
438 }
439}
440
441pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
442 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
443 if let hir::ExprKind::Lit(_) = &expr.kind {
444 return true;
445 }
446
447 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
448 && let hir::ExprKind::Lit(_) = &expr.kind
449 {
450 return true;
451 }
452 }
453
454 false
455}
456
457pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
459 debug!("resolve_type({path:?})");
460
461 match path.res {
462 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
463 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
464 Type::SelfTy
465 }
466 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
467 _ => {
468 let _ = register_res(cx, path.res);
469 Type::Path { path }
470 }
471 }
472}
473
474pub(crate) fn synthesize_auto_trait_and_blanket_impls(
475 cx: &mut DocContext<'_>,
476 item_def_id: DefId,
477) -> impl Iterator<Item = Item> {
478 let auto_impls = cx
479 .sess()
480 .prof
481 .generic_activity("synthesize_auto_trait_impls")
482 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
483 let blanket_impls = cx
484 .sess()
485 .prof
486 .generic_activity("synthesize_blanket_impls")
487 .run(|| synthesize_blanket_impls(cx, item_def_id));
488 auto_impls.into_iter().chain(blanket_impls)
489}
490
491pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
497 use DefKind::*;
498 debug!("register_res({res:?})");
499
500 let (kind, did) = match res {
501 Res::Def(
502 kind @ (AssocTy
503 | AssocFn
504 | AssocConst
505 | Variant
506 | Fn
507 | TyAlias { .. }
508 | Enum
509 | Trait
510 | Struct
511 | Union
512 | Mod
513 | ForeignTy
514 | Const
515 | Static { .. }
516 | Macro(..)
517 | TraitAlias),
518 did,
519 ) => (kind.into(), did),
520
521 _ => panic!("register_res: unexpected {res:?}"),
522 };
523 if did.is_local() {
524 return did;
525 }
526 inline::record_extern_fqn(cx, did, kind);
527 did
528}
529
530pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
531 ImportSource {
532 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
533 path,
534 }
535}
536
537pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
538where
539 F: FnOnce(&mut DocContext<'tcx>) -> R,
540{
541 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
542 let r = f(cx);
543 assert!(cx.impl_trait_bounds.is_empty());
544 cx.impl_trait_bounds = old_bounds;
545 r
546}
547
548pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
550 if def_id.is_top_level_module() {
551 Some(def_id)
553 } else {
554 let mut current = def_id;
555 while let Some(parent) = tcx.opt_parent(current) {
558 if tcx.def_kind(parent) == DefKind::Mod {
559 return Some(parent);
560 }
561 current = parent;
562 }
563 None
564 }
565}
566
567pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
577 attrs_have_doc_flag(tcx.get_attrs(did, sym::doc), flag)
578}
579
580pub(crate) fn attrs_have_doc_flag<'a>(
581 mut attrs: impl Iterator<Item = &'a hir::Attribute>,
582 flag: Symbol,
583) -> bool {
584 attrs.any(|attr| attr.meta_item_list().is_some_and(|l| ast::attr::list_contains_name(&l, flag)))
585}
586
587pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
592pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
593 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
594
595fn render_macro_arms<'a>(
598 tcx: TyCtxt<'_>,
599 matchers: impl Iterator<Item = &'a TokenTree>,
600 arm_delim: &str,
601) -> String {
602 let mut out = String::new();
603 for matcher in matchers {
604 writeln!(
605 out,
606 " {matcher} => {{ ... }}{arm_delim}",
607 matcher = render_macro_matcher(tcx, matcher),
608 )
609 .unwrap();
610 }
611 out
612}
613
614pub(super) fn display_macro_source(
615 cx: &mut DocContext<'_>,
616 name: Symbol,
617 def: &ast::MacroDef,
618) -> String {
619 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
621
622 if def.macro_rules {
623 format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
624 } else {
625 if matchers.len() <= 1 {
626 format!(
627 "macro {name}{matchers} {{\n ...\n}}",
628 matchers = matchers
629 .map(|matcher| render_macro_matcher(cx.tcx, matcher))
630 .collect::<String>(),
631 )
632 } else {
633 format!("macro {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ","))
634 }
635 }
636}
637
638pub(crate) fn inherits_doc_hidden(
639 tcx: TyCtxt<'_>,
640 mut def_id: LocalDefId,
641 stop_at: Option<LocalDefId>,
642) -> bool {
643 while let Some(id) = tcx.opt_local_parent(def_id) {
644 if let Some(stop_at) = stop_at
645 && id == stop_at
646 {
647 return false;
648 }
649 def_id = id;
650 if tcx.is_doc_hidden(def_id.to_def_id()) {
651 return true;
652 } else if matches!(
653 tcx.hir_node_by_def_id(def_id),
654 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
655 ) {
656 return false;
659 }
660 }
661 false
662}
663
664#[inline]
665pub(crate) fn should_ignore_res(res: Res) -> bool {
666 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
667}