1#[cfg(bootstrap)]
2pub use std::assert_matches::debug_assert_matches;
3#[cfg(not(bootstrap))]
4pub use std::debug_assert_matches;
5use std::fmt::{self, Display, Write as _};
6use std::sync::LazyLock as Lazy;
7use std::{ascii, mem};
8
9use rustc_ast::join_path_idents;
10use rustc_ast::tokenstream::TokenTree;
11use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
12use rustc_hir::Attribute;
13use rustc_hir::attrs::{AttributeKind, DocAttribute};
14use rustc_hir::def::{DefKind, Res};
15use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
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};
21use {rustc_ast as ast, rustc_hir as hir};
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,
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)
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)
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 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
121 if has_self && index == 0 {
123 return None;
124 }
125
126 let param = generics.param_at(index, cx.tcx);
127 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
128
129 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
131 let default = default.instantiate(cx.tcx, args.as_ref());
132 if can_elide_generic_arg(arg, arg.rebind(default)) {
133 return None;
134 }
135 elision_has_failed_once_before = true;
136 }
137
138 match arg.skip_binder().kind() {
139 GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
140 clean_middle_region(lt, cx).unwrap_or(Lifetime::elided()),
141 )),
142 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
143 arg.rebind(ty),
144 cx,
145 None,
146 Some(crate::clean::ContainerTy::Regular {
147 ty: owner,
148 args: arg.rebind(args.as_ref()),
149 arg: index,
150 }),
151 ))),
152 GenericArgKind::Const(ct) => {
153 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
154 }
155 }
156 };
157
158 let offset = if has_self { 1 } else { 0 };
159 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
160 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
161 clean_args.reverse();
162 clean_args
163}
164
165fn can_elide_generic_arg<'tcx>(
171 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
172 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
173) -> bool {
174 debug_assert_matches!(
175 (actual.skip_binder().kind(), default.skip_binder().kind()),
176 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
177 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
178 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
179 );
180
181 if actual.has_infer() || default.has_infer() {
184 return false;
185 }
186
187 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
191 return false;
192 }
193
194 actual.skip_binder() == default.skip_binder()
208}
209
210fn clean_middle_generic_args_with_constraints<'tcx>(
211 cx: &mut DocContext<'tcx>,
212 did: DefId,
213 has_self: bool,
214 mut constraints: ThinVec<AssocItemConstraint>,
215 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
216) -> GenericArgs {
217 if cx.tcx.is_trait(did)
218 && cx.tcx.trait_def(did).paren_sugar
219 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
220 {
221 let inputs = tys
222 .iter()
223 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
224 .collect::<Vec<_>>()
225 .into();
226 let output = constraints.pop().and_then(|constraint| match constraint.kind {
227 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
228 Some(Box::new(ty))
229 }
230 _ => None,
231 });
232 return GenericArgs::Parenthesized { inputs, output };
233 }
234
235 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
236
237 GenericArgs::AngleBracketed { args, constraints }
238}
239
240pub(super) fn clean_middle_path<'tcx>(
241 cx: &mut DocContext<'tcx>,
242 did: DefId,
243 has_self: bool,
244 constraints: ThinVec<AssocItemConstraint>,
245 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
246) -> Path {
247 let def_kind = cx.tcx.def_kind(did);
248 let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
249 Path {
250 res: Res::Def(def_kind, did),
251 segments: thin_vec![PathSegment {
252 name,
253 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
254 }],
255 }
256}
257
258pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
259 let segments = match *p {
260 hir::QPath::Resolved(_, path) => &path.segments,
261 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
262 };
263
264 join_path_idents(segments.iter().map(|seg| seg.ident))
265}
266
267pub(crate) fn build_deref_target_impls(
268 cx: &mut DocContext<'_>,
269 items: &[Item],
270 ret: &mut Vec<Item>,
271) {
272 let tcx = cx.tcx;
273
274 for item in items {
275 let target = match item.kind {
276 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
277 _ => continue,
278 };
279
280 if let Some(prim) = target.primitive_type() {
281 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
282 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
283 cx.with_param_env(did, |cx| {
284 inline::build_impl(cx, did, None, ret);
285 });
286 }
287 } else if let Type::Path { path } = target {
288 let did = path.def_id();
289 if !did.is_local() {
290 cx.with_param_env(did, |cx| {
291 inline::build_impls(cx, did, None, ret);
292 });
293 }
294 }
295 }
296}
297
298pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
299 use rustc_hir::*;
300 debug!("trying to get a name from pattern: {p:?}");
301
302 Symbol::intern(&match &p.kind {
303 PatKind::Err(_)
304 | PatKind::Missing | PatKind::Never
306 | PatKind::Range(..)
307 | PatKind::Struct(..)
308 | PatKind::Wild => {
309 return kw::Underscore;
310 }
311 PatKind::Binding(_, _, ident, _) => return ident.name,
312 PatKind::Box(p) | PatKind::Ref(p, _, _) | PatKind::Guard(p, _) => return name_from_pat(p),
313 PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
314 qpath_to_string(p)
315 }
316 PatKind::Or(pats) => {
317 fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
318 }
319 PatKind::Tuple(elts, _) => {
320 format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
321 }
322 PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
323 PatKind::Expr(..) => {
324 warn!(
325 "tried to get argument name from PatKind::Expr, which is silly in function arguments"
326 );
327 return Symbol::intern("()");
328 }
329 PatKind::Slice(begin, mid, end) => {
330 fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
331 fmt::from_fn(move |f| {
332 if wild {
333 f.write_str("..")?;
334 }
335 name_from_pat(pat).fmt(f)
336 })
337 }
338
339 format!(
340 "[{}]",
341 fmt::from_fn(|f| {
342 let begin = begin.iter().map(|p| print_pat(p, false));
343 let mid = mid.map(|p| print_pat(p, true));
344 let end = end.iter().map(|p| print_pat(p, false));
345 begin.chain(mid).chain(end).joined(", ", f)
346 })
347 )
348 }
349 })
350}
351
352pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
353 match n.kind() {
354 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
355 if let Some(def) = def.as_local() {
356 rendered_const(cx.tcx, cx.tcx.hir_body_owned_by(def), def)
357 } else {
358 inline::print_inlined_const(cx.tcx, def)
359 }
360 }
361 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
363 cv.to_leaf().to_string()
364 }
365 _ => n.to_string(),
366 }
367}
368
369pub(crate) fn print_evaluated_const(
370 tcx: TyCtxt<'_>,
371 def_id: DefId,
372 with_underscores: bool,
373 with_type: bool,
374) -> Option<String> {
375 tcx.const_eval_poly(def_id).ok().and_then(|val| {
376 let ty = tcx.type_of(def_id).instantiate_identity();
377 match (val, ty.kind()) {
378 (_, &ty::Ref(..)) => None,
379 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
380 (mir::ConstValue::Scalar(_), _) => {
381 let const_ = mir::Const::from_value(val, ty);
382 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
383 }
384 _ => None,
385 }
386 })
387}
388
389fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
390 let num = num.to_string();
391 let chars = num.as_ascii().unwrap();
392 let mut result = if is_negative { "-".to_string() } else { String::new() };
393 result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
394 result
395}
396
397fn print_const_with_custom_print_scalar<'tcx>(
398 tcx: TyCtxt<'tcx>,
399 ct: mir::Const<'tcx>,
400 with_underscores: bool,
401 with_type: bool,
402) -> String {
403 match (ct, ct.ty().kind()) {
406 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
407 let mut output = if with_underscores {
408 format_integer_with_underscore_sep(
409 int.assert_scalar_int().to_bits_unchecked(),
410 false,
411 )
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(
429 sign_extended_data.unsigned_abs(),
430 sign_extended_data.is_negative(),
431 )
432 } else {
433 sign_extended_data.to_string()
434 };
435 if with_type {
436 output += i.name_str();
437 }
438 output
439 }
440 _ => ct.to_string(),
441 }
442}
443
444pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
445 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
446 if let hir::ExprKind::Lit(_) = &expr.kind {
447 return true;
448 }
449
450 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
451 && let hir::ExprKind::Lit(_) = &expr.kind
452 {
453 return true;
454 }
455 }
456
457 false
458}
459
460pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
462 debug!("resolve_type({path:?})");
463
464 match path.res {
465 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
466 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
467 Type::SelfTy
468 }
469 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
470 _ => {
471 let _ = register_res(cx, path.res);
472 Type::Path { path }
473 }
474 }
475}
476
477pub(crate) fn synthesize_auto_trait_and_blanket_impls(
478 cx: &mut DocContext<'_>,
479 item_def_id: DefId,
480) -> impl Iterator<Item = Item> + use<> {
481 let auto_impls = cx
482 .sess()
483 .prof
484 .generic_activity("synthesize_auto_trait_impls")
485 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
486 let blanket_impls = cx
487 .sess()
488 .prof
489 .generic_activity("synthesize_blanket_impls")
490 .run(|| synthesize_blanket_impls(cx, item_def_id));
491 auto_impls.into_iter().chain(blanket_impls)
492}
493
494pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
500 use DefKind::*;
501 debug!("register_res({res:?})");
502
503 let (kind, did) = match res {
504 Res::Def(
505 AssocTy
506 | AssocFn
507 | AssocConst
508 | Variant
509 | Fn
510 | TyAlias
511 | Enum
512 | Trait
513 | Struct
514 | Union
515 | Mod
516 | ForeignTy
517 | Const
518 | Static { .. }
519 | Macro(..)
520 | TraitAlias,
521 did,
522 ) => (ItemType::from_def_id(did, cx.tcx), did),
523
524 _ => panic!("register_res: unexpected {res:?}"),
525 };
526 if did.is_local() {
527 return did;
528 }
529 inline::record_extern_fqn(cx, did, kind);
530 did
531}
532
533pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
534 ImportSource {
535 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
536 path,
537 }
538}
539
540pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
541where
542 F: FnOnce(&mut DocContext<'tcx>) -> R,
543{
544 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
545 let r = f(cx);
546 assert!(cx.impl_trait_bounds.is_empty());
547 cx.impl_trait_bounds = old_bounds;
548 r
549}
550
551pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
553 if def_id.is_top_level_module() {
554 Some(def_id)
556 } else {
557 let mut current = def_id;
558 while let Some(parent) = tcx.opt_parent(current) {
561 if tcx.def_kind(parent) == DefKind::Mod {
562 return Some(parent);
563 }
564 current = parent;
565 }
566 None
567 }
568}
569
570pub(crate) fn has_doc_flag<F: Fn(&DocAttribute) -> bool>(
573 tcx: TyCtxt<'_>,
574 did: DefId,
575 callback: F,
576) -> bool {
577 tcx.get_all_attrs(did).iter().any(|attr| match attr {
578 Attribute::Parsed(AttributeKind::Doc(d)) => callback(d),
579 _ => false,
580 })
581}
582
583pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
588pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
589 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
590
591fn render_macro_arms<'a>(
594 tcx: TyCtxt<'_>,
595 matchers: impl Iterator<Item = &'a TokenTree>,
596 arm_delim: &str,
597) -> String {
598 let mut out = String::new();
599 for matcher in matchers {
600 writeln!(
601 out,
602 " {matcher} => {{ ... }}{arm_delim}",
603 matcher = render_macro_matcher(tcx, matcher),
604 )
605 .unwrap();
606 }
607 out
608}
609
610pub(super) fn display_macro_source(
611 cx: &mut DocContext<'_>,
612 name: Symbol,
613 def: &ast::MacroDef,
614) -> String {
615 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
617
618 if def.macro_rules {
619 format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
620 } else {
621 if matchers.len() <= 1 {
622 format!(
623 "macro {name}{matchers} {{\n ...\n}}",
624 matchers = matchers
625 .map(|matcher| render_macro_matcher(cx.tcx, matcher))
626 .collect::<String>(),
627 )
628 } else {
629 format!("macro {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ","))
630 }
631 }
632}
633
634pub(crate) fn inherits_doc_hidden(
635 tcx: TyCtxt<'_>,
636 mut def_id: LocalDefId,
637 stop_at: Option<LocalDefId>,
638) -> bool {
639 while let Some(id) = tcx.opt_local_parent(def_id) {
640 if let Some(stop_at) = stop_at
641 && id == stop_at
642 {
643 return false;
644 }
645 def_id = id;
646 if tcx.is_doc_hidden(def_id.to_def_id()) {
647 return true;
648 } else if matches!(
649 tcx.hir_node_by_def_id(def_id),
650 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
651 ) {
652 return false;
655 }
656 }
657 false
658}
659
660#[inline]
661pub(crate) fn should_ignore_res(res: Res) -> bool {
662 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
663}