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