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