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_data_structures::thin_vec::{ThinVec, thin_vec};
9use rustc_hir::Attribute;
10use rustc_hir::attrs::{AttributeKind, DocAttribute};
11use rustc_hir::def::{DefKind, Res};
12use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
13use rustc_metadata::rendered_const;
14use rustc_middle::mir;
15use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt};
16use rustc_span::symbol::{Symbol, kw, sym};
17use tracing::{debug, warn};
18use {rustc_ast as ast, rustc_hir as hir};
19
20use crate::clean::auto_trait::synthesize_auto_trait_impls;
21use crate::clean::blanket_impl::synthesize_blanket_impls;
22use crate::clean::render_macro_matchers::render_macro_matcher;
23use crate::clean::{
24 AssocItemConstraint, AssocItemConstraintKind, Crate, ExternalCrate, Generic, GenericArg,
25 GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path, PathSegment, Primitive,
26 PrimitiveType, Term, Type, clean_doc_module, clean_middle_const, clean_middle_region,
27 clean_middle_ty, inline,
28};
29use crate::core::DocContext;
30use crate::display::Joined as _;
31use crate::formats::item_type::ItemType;
32
33#[cfg(test)]
34mod tests;
35
36pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
37 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
38
39 let mut module = clean_doc_module(&module, cx);
42
43 match module.kind {
44 ItemKind::ModuleItem(ref module) => {
45 for it in &module.items {
46 if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
49 cx.cache.masked_crates.insert(it.item_id.krate());
50 } else if it.is_extern_crate()
51 && it.attrs.has_doc_flag(|d| d.masked.is_some())
52 && let Some(def_id) = it.item_id.as_def_id()
53 && let Some(local_def_id) = def_id.as_local()
54 && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
55 {
56 cx.cache.masked_crates.insert(cnum);
57 }
58 }
59 }
60 _ => unreachable!(),
61 }
62
63 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
64 let primitives = local_crate.primitives(cx.tcx);
65 let keywords = local_crate.keywords(cx.tcx);
66 let documented_attributes = local_crate.documented_attributes(cx.tcx);
67 {
68 let ItemKind::ModuleItem(m) = &mut module.inner.kind else { unreachable!() };
69 m.items.extend(primitives.map(|(def_id, prim)| {
70 Item::from_def_id_and_parts(
71 def_id,
72 Some(prim.as_sym()),
73 ItemKind::PrimitiveItem(prim),
74 cx,
75 )
76 }));
77 m.items.extend(keywords.map(|(def_id, kw)| {
78 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
79 }));
80 m.items.extend(documented_attributes.into_iter().map(|(def_id, kw)| {
81 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::AttributeItem, cx)
82 }));
83 }
84
85 Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
86}
87
88pub(crate) fn clean_middle_generic_args<'tcx>(
89 cx: &mut DocContext<'tcx>,
90 args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
91 mut has_self: bool,
92 owner: DefId,
93) -> ThinVec<GenericArg> {
94 let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
95 if args.is_empty() {
96 return ThinVec::new();
98 }
99
100 let generics = cx.tcx.generics_of(owner);
105 let args = if !has_self && generics.parent.is_none() && generics.has_self {
106 has_self = true;
107 [cx.tcx.types.trait_object_dummy_self.into()]
108 .into_iter()
109 .chain(args.iter().copied())
110 .collect::<Vec<_>>()
111 .into()
112 } else {
113 std::borrow::Cow::from(args)
114 };
115
116 let mut elision_has_failed_once_before = false;
117 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
118 if has_self && index == 0 {
120 return None;
121 }
122
123 let param = generics.param_at(index, cx.tcx);
124 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
125
126 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
128 let default = default.instantiate(cx.tcx, args.as_ref());
129 if can_elide_generic_arg(arg, arg.rebind(default)) {
130 return None;
131 }
132 elision_has_failed_once_before = true;
133 }
134
135 match arg.skip_binder().kind() {
136 GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
137 clean_middle_region(lt, cx).unwrap_or(Lifetime::elided()),
138 )),
139 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
140 arg.rebind(ty),
141 cx,
142 None,
143 Some(crate::clean::ContainerTy::Regular {
144 ty: owner,
145 args: arg.rebind(args.as_ref()),
146 arg: index,
147 }),
148 ))),
149 GenericArgKind::Const(ct) => {
150 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
151 }
152 }
153 };
154
155 let offset = if has_self { 1 } else { 0 };
156 let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
157 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
158 clean_args.reverse();
159 clean_args
160}
161
162fn can_elide_generic_arg<'tcx>(
168 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
169 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
170) -> bool {
171 debug_assert_matches!(
172 (actual.skip_binder().kind(), default.skip_binder().kind()),
173 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
174 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
175 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
176 );
177
178 if actual.has_infer() || default.has_infer() {
181 return false;
182 }
183
184 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
188 return false;
189 }
190
191 actual.skip_binder() == default.skip_binder()
205}
206
207fn clean_middle_generic_args_with_constraints<'tcx>(
208 cx: &mut DocContext<'tcx>,
209 did: DefId,
210 has_self: bool,
211 mut constraints: ThinVec<AssocItemConstraint>,
212 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
213) -> GenericArgs {
214 if cx.tcx.is_trait(did)
215 && cx.tcx.trait_def(did).paren_sugar
216 && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
217 {
218 let inputs = tys
219 .iter()
220 .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
221 .collect::<Vec<_>>()
222 .into();
223 let output = constraints.pop().and_then(|constraint| match constraint.kind {
224 AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
225 Some(Box::new(ty))
226 }
227 _ => None,
228 });
229 return GenericArgs::Parenthesized { inputs, output };
230 }
231
232 let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
233
234 GenericArgs::AngleBracketed { args, constraints }
235}
236
237pub(super) fn clean_middle_path<'tcx>(
238 cx: &mut DocContext<'tcx>,
239 did: DefId,
240 has_self: bool,
241 constraints: ThinVec<AssocItemConstraint>,
242 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
243) -> Path {
244 let def_kind = cx.tcx.def_kind(did);
245 let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
246 Path {
247 res: Res::Def(def_kind, did),
248 segments: thin_vec![PathSegment {
249 name,
250 args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
251 }],
252 }
253}
254
255pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
256 let segments = match *p {
257 hir::QPath::Resolved(_, path) => &path.segments,
258 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
259 };
260
261 join_path_idents(segments.iter().map(|seg| seg.ident))
262}
263
264pub(crate) fn build_deref_target_impls(
265 cx: &mut DocContext<'_>,
266 items: &[Item],
267 ret: &mut Vec<Item>,
268) {
269 let tcx = cx.tcx;
270
271 for item in items {
272 let target = match item.kind {
273 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
274 _ => continue,
275 };
276
277 if let Some(prim) = target.primitive_type() {
278 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
279 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
280 cx.with_param_env(did, |cx| {
281 inline::build_impl(cx, did, None, ret);
282 });
283 }
284 } else if let Type::Path { path } = target {
285 let did = path.def_id();
286 if !did.is_local() {
287 cx.with_param_env(did, |cx| {
288 inline::build_impls(cx, did, None, ret);
289 });
290 }
291 }
292 }
293}
294
295pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
296 use rustc_hir::*;
297 debug!("trying to get a name from pattern: {p:?}");
298
299 Symbol::intern(&match &p.kind {
300 PatKind::Err(_)
301 | PatKind::Missing | PatKind::Never
303 | PatKind::Range(..)
304 | PatKind::Struct(..)
305 | PatKind::Wild => {
306 return kw::Underscore;
307 }
308 PatKind::Binding(_, _, ident, _) => return ident.name,
309 PatKind::Box(p) | PatKind::Ref(p, _, _) | PatKind::Guard(p, _) => return name_from_pat(p),
310 PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
311 qpath_to_string(p)
312 }
313 PatKind::Or(pats) => {
314 fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
315 }
316 PatKind::Tuple(elts, _) => {
317 format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
318 }
319 PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
320 PatKind::Expr(..) => {
321 warn!(
322 "tried to get argument name from PatKind::Expr, which is silly in function arguments"
323 );
324 return Symbol::intern("()");
325 }
326 PatKind::Slice(begin, mid, end) => {
327 fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
328 fmt::from_fn(move |f| {
329 if wild {
330 f.write_str("..")?;
331 }
332 name_from_pat(pat).fmt(f)
333 })
334 }
335
336 format!(
337 "[{}]",
338 fmt::from_fn(|f| {
339 let begin = begin.iter().map(|p| print_pat(p, false));
340 let mid = mid.map(|p| print_pat(p, true));
341 let end = end.iter().map(|p| print_pat(p, false));
342 begin.chain(mid).chain(end).joined(", ", f)
343 })
344 )
345 }
346 })
347}
348
349pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
350 match n.kind() {
351 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
352 if let Some(def) = def.as_local() {
353 rendered_const(cx.tcx, cx.tcx.hir_body_owned_by(def), def)
354 } else {
355 inline::print_inlined_const(cx.tcx, def)
356 }
357 }
358 ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
360 cv.valtree.unwrap_leaf().to_string()
361 }
362 _ => n.to_string(),
363 }
364}
365
366pub(crate) fn print_evaluated_const(
367 tcx: TyCtxt<'_>,
368 def_id: DefId,
369 with_underscores: bool,
370 with_type: bool,
371) -> Option<String> {
372 tcx.const_eval_poly(def_id).ok().and_then(|val| {
373 let ty = tcx.type_of(def_id).instantiate_identity();
374 match (val, ty.kind()) {
375 (_, &ty::Ref(..)) => None,
376 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
377 (mir::ConstValue::Scalar(_), _) => {
378 let const_ = mir::Const::from_value(val, ty);
379 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
380 }
381 _ => None,
382 }
383 })
384}
385
386fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
387 let num = num.to_string();
388 let chars = num.as_ascii().unwrap();
389 let mut result = if is_negative { "-".to_string() } else { String::new() };
390 result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
391 result
392}
393
394fn print_const_with_custom_print_scalar<'tcx>(
395 tcx: TyCtxt<'tcx>,
396 ct: mir::Const<'tcx>,
397 with_underscores: bool,
398 with_type: bool,
399) -> String {
400 match (ct, ct.ty().kind()) {
403 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
404 let mut output = if with_underscores {
405 format_integer_with_underscore_sep(
406 int.assert_scalar_int().to_bits_unchecked(),
407 false,
408 )
409 } else {
410 int.to_string()
411 };
412 if with_type {
413 output += ui.name_str();
414 }
415 output
416 }
417 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
418 let ty = ct.ty();
419 let size = tcx
420 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
421 .unwrap()
422 .size;
423 let sign_extended_data = int.assert_scalar_int().to_int(size);
424 let mut output = if with_underscores {
425 format_integer_with_underscore_sep(
426 sign_extended_data.unsigned_abs(),
427 sign_extended_data.is_negative(),
428 )
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> + use<> {
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 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 ) => (ItemType::from_def_id(did, cx.tcx), 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<F: Fn(&DocAttribute) -> bool>(
570 tcx: TyCtxt<'_>,
571 did: DefId,
572 callback: F,
573) -> bool {
574 tcx.get_all_attrs(did).iter().any(|attr| match attr {
575 Attribute::Parsed(AttributeKind::Doc(d)) => callback(d),
576 _ => false,
577 })
578}
579
580pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
585pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
586 Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
587
588fn render_macro_arms<'a>(
591 tcx: TyCtxt<'_>,
592 matchers: impl Iterator<Item = &'a TokenTree>,
593 arm_delim: &str,
594) -> String {
595 let mut out = String::new();
596 for matcher in matchers {
597 writeln!(
598 out,
599 " {matcher} => {{ ... }}{arm_delim}",
600 matcher = render_macro_matcher(tcx, matcher),
601 )
602 .unwrap();
603 }
604 out
605}
606
607pub(super) fn display_macro_source(
608 cx: &mut DocContext<'_>,
609 name: Symbol,
610 def: &ast::MacroDef,
611) -> String {
612 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
614
615 if def.macro_rules {
616 format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
617 } else {
618 if matchers.len() <= 1 {
619 format!(
620 "macro {name}{matchers} {{\n ...\n}}",
621 matchers = matchers
622 .map(|matcher| render_macro_matcher(cx.tcx, matcher))
623 .collect::<String>(),
624 )
625 } else {
626 format!("macro {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ","))
627 }
628 }
629}
630
631pub(crate) fn inherits_doc_hidden(
632 tcx: TyCtxt<'_>,
633 mut def_id: LocalDefId,
634 stop_at: Option<LocalDefId>,
635) -> bool {
636 while let Some(id) = tcx.opt_local_parent(def_id) {
637 if let Some(stop_at) = stop_at
638 && id == stop_at
639 {
640 return false;
641 }
642 def_id = id;
643 if tcx.is_doc_hidden(def_id.to_def_id()) {
644 return true;
645 } else if matches!(
646 tcx.hir_node_by_def_id(def_id),
647 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
648 ) {
649 return false;
652 }
653 }
654 false
655}
656
657#[inline]
658pub(crate) fn should_ignore_res(res: Res) -> bool {
659 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
660}