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