rustdoc/clean/
utils.rs

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    // Clean the crate, translating the entire librustc_ast AST to one that is
37    // understood by rustdoc.
38    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                // `compiler_builtins` should be masked too, but we can't apply
44                // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
45                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    {
64        let ItemKind::ModuleItem(m) = &mut module.inner.kind else { unreachable!() };
65        m.items.extend(primitives.map(|(def_id, prim)| {
66            Item::from_def_id_and_parts(
67                def_id,
68                Some(prim.as_sym()),
69                ItemKind::PrimitiveItem(prim),
70                cx,
71            )
72        }));
73        m.items.extend(keywords.map(|(def_id, kw)| {
74            Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
75        }));
76    }
77
78    Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
79}
80
81pub(crate) fn clean_middle_generic_args<'tcx>(
82    cx: &mut DocContext<'tcx>,
83    args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
84    mut has_self: bool,
85    owner: DefId,
86) -> ThinVec<GenericArg> {
87    let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
88    if args.is_empty() {
89        // Fast path which avoids executing the query `generics_of`.
90        return ThinVec::new();
91    }
92
93    // If the container is a trait object type, the arguments won't contain the self type but the
94    // generics of the corresponding trait will. In such a case, prepend a dummy self type in order
95    // to align the arguments and parameters for the iteration below and to enable us to correctly
96    // instantiate the generic parameter default later.
97    let generics = cx.tcx.generics_of(owner);
98    let args = if !has_self && generics.parent.is_none() && generics.has_self {
99        has_self = true;
100        [cx.tcx.types.trait_object_dummy_self.into()]
101            .into_iter()
102            .chain(args.iter().copied())
103            .collect::<Vec<_>>()
104            .into()
105    } else {
106        std::borrow::Cow::from(args)
107    };
108
109    let mut elision_has_failed_once_before = false;
110    let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
111        // Elide the self type.
112        if has_self && index == 0 {
113            return None;
114        }
115
116        let param = generics.param_at(index, cx.tcx);
117        let arg = ty::Binder::bind_with_vars(arg, bound_vars);
118
119        // Elide arguments that coincide with their default.
120        if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
121            let default = default.instantiate(cx.tcx, args.as_ref());
122            if can_elide_generic_arg(arg, arg.rebind(default)) {
123                return None;
124            }
125            elision_has_failed_once_before = true;
126        }
127
128        match arg.skip_binder().kind() {
129            GenericArgKind::Lifetime(lt) => Some(GenericArg::Lifetime(
130                clean_middle_region(lt, cx).unwrap_or(Lifetime::elided()),
131            )),
132            GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
133                arg.rebind(ty),
134                cx,
135                None,
136                Some(crate::clean::ContainerTy::Regular {
137                    ty: owner,
138                    args: arg.rebind(args.as_ref()),
139                    arg: index,
140                }),
141            ))),
142            GenericArgKind::Const(ct) => {
143                Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
144            }
145        }
146    };
147
148    let offset = if has_self { 1 } else { 0 };
149    let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
150    clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
151    clean_args.reverse();
152    clean_args
153}
154
155/// Check if the generic argument `actual` coincides with the `default` and can therefore be elided.
156///
157/// This uses a very conservative approach for performance and correctness reasons, meaning for
158/// several classes of terms it claims that they cannot be elided even if they theoretically could.
159/// This is absolutely fine since it mostly concerns edge cases.
160fn can_elide_generic_arg<'tcx>(
161    actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
162    default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
163) -> bool {
164    debug_assert_matches!(
165        (actual.skip_binder().kind(), default.skip_binder().kind()),
166        (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
167            | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
168            | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
169    );
170
171    // In practice, we shouldn't have any inference variables at this point.
172    // However to be safe, we bail out if we do happen to stumble upon them.
173    if actual.has_infer() || default.has_infer() {
174        return false;
175    }
176
177    // Since we don't properly keep track of bound variables in rustdoc (yet), we don't attempt to
178    // make any sense out of escaping bound variables. We simply don't have enough context and it
179    // would be incorrect to try to do so anyway.
180    if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
181        return false;
182    }
183
184    // Theoretically we could now check if either term contains (non-escaping) late-bound regions or
185    // projections, relate the two using an `InferCtxt` and check if the resulting obligations hold.
186    // Having projections means that the terms can potentially be further normalized thereby possibly
187    // revealing that they are equal after all. Regarding late-bound regions, they could to be
188    // liberated allowing us to consider more types to be equal by ignoring the names of binders
189    // (e.g., `for<'a> TYPE<'a>` and `for<'b> TYPE<'b>`).
190    //
191    // However, we are mostly interested in “reeliding” generic args, i.e., eliding generic args that
192    // were originally elided by the user and later filled in by the compiler contrary to eliding
193    // arbitrary generic arguments if they happen to semantically coincide with the default (of course,
194    // we cannot possibly distinguish these two cases). Therefore and for performance reasons, it
195    // suffices to only perform a syntactic / structural check by comparing the memory addresses of
196    // the interned arguments.
197    actual.skip_binder() == default.skip_binder()
198}
199
200fn clean_middle_generic_args_with_constraints<'tcx>(
201    cx: &mut DocContext<'tcx>,
202    did: DefId,
203    has_self: bool,
204    mut constraints: ThinVec<AssocItemConstraint>,
205    args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
206) -> GenericArgs {
207    if cx.tcx.is_trait(did)
208        && cx.tcx.trait_def(did).paren_sugar
209        && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
210    {
211        let inputs = tys
212            .iter()
213            .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
214            .collect::<Vec<_>>()
215            .into();
216        let output = constraints.pop().and_then(|constraint| match constraint.kind {
217            AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
218                Some(Box::new(ty))
219            }
220            _ => None,
221        });
222        return GenericArgs::Parenthesized { inputs, output };
223    }
224
225    let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
226
227    GenericArgs::AngleBracketed { args, constraints }
228}
229
230pub(super) fn clean_middle_path<'tcx>(
231    cx: &mut DocContext<'tcx>,
232    did: DefId,
233    has_self: bool,
234    constraints: ThinVec<AssocItemConstraint>,
235    args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
236) -> Path {
237    let def_kind = cx.tcx.def_kind(did);
238    let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
239    Path {
240        res: Res::Def(def_kind, did),
241        segments: thin_vec![PathSegment {
242            name,
243            args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
244        }],
245    }
246}
247
248pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
249    let segments = match *p {
250        hir::QPath::Resolved(_, path) => &path.segments,
251        hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
252        hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
253    };
254
255    join_path_idents(segments.iter().map(|seg| seg.ident))
256}
257
258pub(crate) fn build_deref_target_impls(
259    cx: &mut DocContext<'_>,
260    items: &[Item],
261    ret: &mut Vec<Item>,
262) {
263    let tcx = cx.tcx;
264
265    for item in items {
266        let target = match item.kind {
267            ItemKind::AssocTypeItem(ref t, _) => &t.type_,
268            _ => continue,
269        };
270
271        if let Some(prim) = target.primitive_type() {
272            let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
273            for did in prim.impls(tcx).filter(|did| !did.is_local()) {
274                cx.with_param_env(did, |cx| {
275                    inline::build_impl(cx, did, None, ret);
276                });
277            }
278        } else if let Type::Path { path } = target {
279            let did = path.def_id();
280            if !did.is_local() {
281                cx.with_param_env(did, |cx| {
282                    inline::build_impls(cx, did, None, ret);
283                });
284            }
285        }
286    }
287}
288
289pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
290    use rustc_hir::*;
291    debug!("trying to get a name from pattern: {p:?}");
292
293    Symbol::intern(&match &p.kind {
294        PatKind::Err(_)
295        | PatKind::Missing // Let's not perpetuate anon params from Rust 2015; use `_` for them.
296        | PatKind::Never
297        | PatKind::Range(..)
298        | PatKind::Struct(..)
299        | PatKind::Wild => {
300            return kw::Underscore;
301        }
302        PatKind::Binding(_, _, ident, _) => return ident.name,
303        PatKind::Box(p) | PatKind::Ref(p, _) | PatKind::Guard(p, _) => return name_from_pat(p),
304        PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
305            qpath_to_string(p)
306        }
307        PatKind::Or(pats) => {
308            fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
309        }
310        PatKind::Tuple(elts, _) => {
311            format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
312        }
313        PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
314        PatKind::Expr(..) => {
315            warn!(
316                "tried to get argument name from PatKind::Expr, which is silly in function arguments"
317            );
318            return Symbol::intern("()");
319        }
320        PatKind::Slice(begin, mid, end) => {
321            fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
322                fmt::from_fn(move |f| {
323                    if wild {
324                        f.write_str("..")?;
325                    }
326                    name_from_pat(pat).fmt(f)
327                })
328            }
329
330            format!(
331                "[{}]",
332                fmt::from_fn(|f| {
333                    let begin = begin.iter().map(|p| print_pat(p, false));
334                    let mid = mid.map(|p| print_pat(p, true));
335                    let end = end.iter().map(|p| print_pat(p, false));
336                    begin.chain(mid).chain(end).joined(", ", f)
337                })
338            )
339        }
340    })
341}
342
343pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
344    match n.kind() {
345        ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
346            if let Some(def) = def.as_local() {
347                rendered_const(cx.tcx, cx.tcx.hir_body_owned_by(def), def)
348            } else {
349                inline::print_inlined_const(cx.tcx, def)
350            }
351        }
352        // array lengths are obviously usize
353        ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
354            cv.valtree.unwrap_leaf().to_string()
355        }
356        _ => n.to_string(),
357    }
358}
359
360pub(crate) fn print_evaluated_const(
361    tcx: TyCtxt<'_>,
362    def_id: DefId,
363    with_underscores: bool,
364    with_type: bool,
365) -> Option<String> {
366    tcx.const_eval_poly(def_id).ok().and_then(|val| {
367        let ty = tcx.type_of(def_id).instantiate_identity();
368        match (val, ty.kind()) {
369            (_, &ty::Ref(..)) => None,
370            (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
371            (mir::ConstValue::Scalar(_), _) => {
372                let const_ = mir::Const::from_value(val, ty);
373                Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
374            }
375            _ => None,
376        }
377    })
378}
379
380fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
381    let num = num.to_string();
382    let chars = num.as_ascii().unwrap();
383    let mut result = if is_negative { "-".to_string() } else { String::new() };
384    result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
385    result
386}
387
388fn print_const_with_custom_print_scalar<'tcx>(
389    tcx: TyCtxt<'tcx>,
390    ct: mir::Const<'tcx>,
391    with_underscores: bool,
392    with_type: bool,
393) -> String {
394    // Use a slightly different format for integer types which always shows the actual value.
395    // For all other types, fallback to the original `pretty_print_const`.
396    match (ct, ct.ty().kind()) {
397        (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
398            let mut output = if with_underscores {
399                format_integer_with_underscore_sep(
400                    int.assert_scalar_int().to_bits_unchecked(),
401                    false,
402                )
403            } else {
404                int.to_string()
405            };
406            if with_type {
407                output += ui.name_str();
408            }
409            output
410        }
411        (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
412            let ty = ct.ty();
413            let size = tcx
414                .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
415                .unwrap()
416                .size;
417            let sign_extended_data = int.assert_scalar_int().to_int(size);
418            let mut output = if with_underscores {
419                format_integer_with_underscore_sep(
420                    sign_extended_data.unsigned_abs(),
421                    sign_extended_data.is_negative(),
422                )
423            } else {
424                sign_extended_data.to_string()
425            };
426            if with_type {
427                output += i.name_str();
428            }
429            output
430        }
431        _ => ct.to_string(),
432    }
433}
434
435pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
436    if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
437        if let hir::ExprKind::Lit(_) = &expr.kind {
438            return true;
439        }
440
441        if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
442            && let hir::ExprKind::Lit(_) = &expr.kind
443        {
444            return true;
445        }
446    }
447
448    false
449}
450
451/// Given a type Path, resolve it to a Type using the TyCtxt
452pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
453    debug!("resolve_type({path:?})");
454
455    match path.res {
456        Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
457        Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
458            Type::SelfTy
459        }
460        Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
461        _ => {
462            let _ = register_res(cx, path.res);
463            Type::Path { path }
464        }
465    }
466}
467
468pub(crate) fn synthesize_auto_trait_and_blanket_impls(
469    cx: &mut DocContext<'_>,
470    item_def_id: DefId,
471) -> impl Iterator<Item = Item> + use<> {
472    let auto_impls = cx
473        .sess()
474        .prof
475        .generic_activity("synthesize_auto_trait_impls")
476        .run(|| synthesize_auto_trait_impls(cx, item_def_id));
477    let blanket_impls = cx
478        .sess()
479        .prof
480        .generic_activity("synthesize_blanket_impls")
481        .run(|| synthesize_blanket_impls(cx, item_def_id));
482    auto_impls.into_iter().chain(blanket_impls)
483}
484
485/// If `res` has a documentation page associated, store it in the cache.
486///
487/// This is later used by [`href()`] to determine the HTML link for the item.
488///
489/// [`href()`]: crate::html::format::href
490pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
491    use DefKind::*;
492    debug!("register_res({res:?})");
493
494    let (kind, did) = match res {
495        Res::Def(
496            kind @ (AssocTy
497            | AssocFn
498            | AssocConst
499            | Variant
500            | Fn
501            | TyAlias
502            | Enum
503            | Trait
504            | Struct
505            | Union
506            | Mod
507            | ForeignTy
508            | Const
509            | Static { .. }
510            | Macro(..)
511            | TraitAlias),
512            did,
513        ) => (kind.into(), did),
514
515        _ => panic!("register_res: unexpected {res:?}"),
516    };
517    if did.is_local() {
518        return did;
519    }
520    inline::record_extern_fqn(cx, did, kind);
521    did
522}
523
524pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
525    ImportSource {
526        did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
527        path,
528    }
529}
530
531pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
532where
533    F: FnOnce(&mut DocContext<'tcx>) -> R,
534{
535    let old_bounds = mem::take(&mut cx.impl_trait_bounds);
536    let r = f(cx);
537    assert!(cx.impl_trait_bounds.is_empty());
538    cx.impl_trait_bounds = old_bounds;
539    r
540}
541
542/// Find the nearest parent module of a [`DefId`].
543pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
544    if def_id.is_top_level_module() {
545        // The crate root has no parent. Use it as the root instead.
546        Some(def_id)
547    } else {
548        let mut current = def_id;
549        // The immediate parent might not always be a module.
550        // Find the first parent which is.
551        while let Some(parent) = tcx.opt_parent(current) {
552            if tcx.def_kind(parent) == DefKind::Mod {
553                return Some(parent);
554            }
555            current = parent;
556        }
557        None
558    }
559}
560
561/// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
562///
563/// ```
564/// #[doc(hidden)]
565/// pub fn foo() {}
566/// ```
567///
568/// This function exists because it runs on `hir::Attributes` whereas the other is a
569/// `clean::Attributes` method.
570pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
571    attrs_have_doc_flag(tcx.get_attrs(did, sym::doc), flag)
572}
573
574pub(crate) fn attrs_have_doc_flag<'a>(
575    mut attrs: impl Iterator<Item = &'a hir::Attribute>,
576    flag: Symbol,
577) -> bool {
578    attrs.any(|attr| attr.meta_item_list().is_some_and(|l| ast::attr::list_contains_name(&l, flag)))
579}
580
581/// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
582/// so that the channel is consistent.
583///
584/// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
585pub(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
589/// Render a sequence of macro arms in a format suitable for displaying to the user
590/// as part of an item declaration.
591fn render_macro_arms<'a>(
592    tcx: TyCtxt<'_>,
593    matchers: impl Iterator<Item = &'a TokenTree>,
594    arm_delim: &str,
595) -> String {
596    let mut out = String::new();
597    for matcher in matchers {
598        writeln!(
599            out,
600            "    {matcher} => {{ ... }}{arm_delim}",
601            matcher = render_macro_matcher(tcx, matcher),
602        )
603        .unwrap();
604    }
605    out
606}
607
608pub(super) fn display_macro_source(
609    cx: &mut DocContext<'_>,
610    name: Symbol,
611    def: &ast::MacroDef,
612) -> String {
613    // Extract the spans of all matchers. They represent the "interface" of the macro.
614    let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
615
616    if def.macro_rules {
617        format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
618    } else {
619        if matchers.len() <= 1 {
620            format!(
621                "macro {name}{matchers} {{\n    ...\n}}",
622                matchers = matchers
623                    .map(|matcher| render_macro_matcher(cx.tcx, matcher))
624                    .collect::<String>(),
625            )
626        } else {
627            format!("macro {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ","))
628        }
629    }
630}
631
632pub(crate) fn inherits_doc_hidden(
633    tcx: TyCtxt<'_>,
634    mut def_id: LocalDefId,
635    stop_at: Option<LocalDefId>,
636) -> bool {
637    while let Some(id) = tcx.opt_local_parent(def_id) {
638        if let Some(stop_at) = stop_at
639            && id == stop_at
640        {
641            return false;
642        }
643        def_id = id;
644        if tcx.is_doc_hidden(def_id.to_def_id()) {
645            return true;
646        } else if matches!(
647            tcx.hir_node_by_def_id(def_id),
648            hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
649        ) {
650            // `impl` blocks stand a bit on their own: unless they have `#[doc(hidden)]` directly
651            // on them, they don't inherit it from the parent context.
652            return false;
653        }
654    }
655    false
656}
657
658#[inline]
659pub(crate) fn should_ignore_res(res: Res) -> bool {
660    matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
661}