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::tokenstream::TokenTree;
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
9use rustc_metadata::rendered_const;
10use rustc_middle::mir;
11use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt};
12use rustc_span::symbol::{Symbol, kw, sym};
13use thin_vec::{ThinVec, thin_vec};
14use tracing::{debug, warn};
15use {rustc_ast as ast, rustc_hir as hir};
16
17use crate::clean::auto_trait::synthesize_auto_trait_impls;
18use crate::clean::blanket_impl::synthesize_blanket_impls;
19use crate::clean::render_macro_matchers::render_macro_matcher;
20use crate::clean::{
21    AssocItemConstraint, AssocItemConstraintKind, Crate, ExternalCrate, Generic, GenericArg,
22    GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path, PathSegment, Primitive,
23    PrimitiveType, Term, Type, clean_doc_module, clean_middle_const, clean_middle_region,
24    clean_middle_ty, inline,
25};
26use crate::core::DocContext;
27use crate::display::{Joined as _, MaybeDisplay as _};
28
29#[cfg(test)]
30mod tests;
31
32pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
33    let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
34
35    // Clean the crate, translating the entire librustc_ast AST to one that is
36    // understood by rustdoc.
37    let mut module = clean_doc_module(&module, cx);
38
39    match module.kind {
40        ItemKind::ModuleItem(ref module) => {
41            for it in &module.items {
42                // `compiler_builtins` should be masked too, but we can't apply
43                // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
44                if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
45                    cx.cache.masked_crates.insert(it.item_id.krate());
46                } else if it.is_extern_crate()
47                    && it.attrs.has_doc_flag(sym::masked)
48                    && let Some(def_id) = it.item_id.as_def_id()
49                    && let Some(local_def_id) = def_id.as_local()
50                    && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
51                {
52                    cx.cache.masked_crates.insert(cnum);
53                }
54            }
55        }
56        _ => unreachable!(),
57    }
58
59    let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
60    let primitives = local_crate.primitives(cx.tcx);
61    let keywords = local_crate.keywords(cx.tcx);
62    {
63        let ItemKind::ModuleItem(m) = &mut module.inner.kind else { unreachable!() };
64        m.items.extend(primitives.iter().map(|&(def_id, prim)| {
65            Item::from_def_id_and_parts(
66                def_id,
67                Some(prim.as_sym()),
68                ItemKind::PrimitiveItem(prim),
69                cx,
70            )
71        }));
72        m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
73            Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
74        }));
75    }
76
77    Crate { module, external_traits: Box::new(mem::take(&mut cx.external_traits)) }
78}
79
80pub(crate) fn clean_middle_generic_args<'tcx>(
81    cx: &mut DocContext<'tcx>,
82    args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
83    mut has_self: bool,
84    owner: DefId,
85) -> ThinVec<GenericArg> {
86    let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
87    if args.is_empty() {
88        // Fast path which avoids executing the query `generics_of`.
89        return ThinVec::new();
90    }
91
92    // If the container is a trait object type, the arguments won't contain the self type but the
93    // generics of the corresponding trait will. In such a case, prepend a dummy self type in order
94    // to align the arguments and parameters for the iteration below and to enable us to correctly
95    // instantiate the generic parameter default later.
96    let generics = cx.tcx.generics_of(owner);
97    let args = if !has_self && generics.parent.is_none() && generics.has_self {
98        has_self = true;
99        [cx.tcx.types.trait_object_dummy_self.into()]
100            .into_iter()
101            .chain(args.iter().copied())
102            .collect::<Vec<_>>()
103            .into()
104    } else {
105        std::borrow::Cow::from(args)
106    };
107
108    let mut elision_has_failed_once_before = false;
109    let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
110        // Elide the self type.
111        if has_self && index == 0 {
112            return None;
113        }
114
115        let param = generics.param_at(index, cx.tcx);
116        let arg = ty::Binder::bind_with_vars(arg, bound_vars);
117
118        // Elide arguments that coincide with their default.
119        if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
120            let default = default.instantiate(cx.tcx, args.as_ref());
121            if can_elide_generic_arg(arg, arg.rebind(default)) {
122                return None;
123            }
124            elision_has_failed_once_before = true;
125        }
126
127        match arg.skip_binder().kind() {
128            GenericArgKind::Lifetime(lt) => {
129                Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
130            }
131            GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
132                arg.rebind(ty),
133                cx,
134                None,
135                Some(crate::clean::ContainerTy::Regular {
136                    ty: owner,
137                    args: arg.rebind(args.as_ref()),
138                    arg: index,
139                }),
140            ))),
141            GenericArgKind::Const(ct) => {
142                Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
143            }
144        }
145    };
146
147    let offset = if has_self { 1 } else { 0 };
148    let mut clean_args = ThinVec::with_capacity(args.len().saturating_sub(offset));
149    clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
150    clean_args.reverse();
151    clean_args
152}
153
154/// Check if the generic argument `actual` coincides with the `default` and can therefore be elided.
155///
156/// This uses a very conservative approach for performance and correctness reasons, meaning for
157/// several classes of terms it claims that they cannot be elided even if they theoretically could.
158/// This is absolutely fine since it mostly concerns edge cases.
159fn can_elide_generic_arg<'tcx>(
160    actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
161    default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
162) -> bool {
163    debug_assert_matches!(
164        (actual.skip_binder().kind(), default.skip_binder().kind()),
165        (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
166            | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
167            | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
168    );
169
170    // In practice, we shouldn't have any inference variables at this point.
171    // However to be safe, we bail out if we do happen to stumble upon them.
172    if actual.has_infer() || default.has_infer() {
173        return false;
174    }
175
176    // Since we don't properly keep track of bound variables in rustdoc (yet), we don't attempt to
177    // make any sense out of escaping bound variables. We simply don't have enough context and it
178    // would be incorrect to try to do so anyway.
179    if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
180        return false;
181    }
182
183    // Theoretically we could now check if either term contains (non-escaping) late-bound regions or
184    // projections, relate the two using an `InferCtxt` and check if the resulting obligations hold.
185    // Having projections means that the terms can potentially be further normalized thereby possibly
186    // revealing that they are equal after all. Regarding late-bound regions, they could to be
187    // liberated allowing us to consider more types to be equal by ignoring the names of binders
188    // (e.g., `for<'a> TYPE<'a>` and `for<'b> TYPE<'b>`).
189    //
190    // However, we are mostly interested in “reeliding” generic args, i.e., eliding generic args that
191    // were originally elided by the user and later filled in by the compiler contrary to eliding
192    // arbitrary generic arguments if they happen to semantically coincide with the default (of course,
193    // we cannot possibly distinguish these two cases). Therefore and for performance reasons, it
194    // suffices to only perform a syntactic / structural check by comparing the memory addresses of
195    // the interned arguments.
196    actual.skip_binder() == default.skip_binder()
197}
198
199fn clean_middle_generic_args_with_constraints<'tcx>(
200    cx: &mut DocContext<'tcx>,
201    did: DefId,
202    has_self: bool,
203    mut constraints: ThinVec<AssocItemConstraint>,
204    args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
205) -> GenericArgs {
206    if cx.tcx.is_trait(did)
207        && cx.tcx.trait_def(did).paren_sugar
208        && let ty::Tuple(tys) = args.skip_binder().type_at(has_self as usize).kind()
209    {
210        let inputs = tys
211            .iter()
212            .map(|ty| clean_middle_ty(args.rebind(ty), cx, None, None))
213            .collect::<Vec<_>>()
214            .into();
215        let output = constraints.pop().and_then(|constraint| match constraint.kind {
216            AssocItemConstraintKind::Equality { term: Term::Type(ty) } if !ty.is_unit() => {
217                Some(Box::new(ty))
218            }
219            _ => None,
220        });
221        return GenericArgs::Parenthesized { inputs, output };
222    }
223
224    let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did);
225
226    GenericArgs::AngleBracketed { args, constraints }
227}
228
229pub(super) fn clean_middle_path<'tcx>(
230    cx: &mut DocContext<'tcx>,
231    did: DefId,
232    has_self: bool,
233    constraints: ThinVec<AssocItemConstraint>,
234    args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
235) -> Path {
236    let def_kind = cx.tcx.def_kind(did);
237    let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy);
238    Path {
239        res: Res::Def(def_kind, did),
240        segments: thin_vec![PathSegment {
241            name,
242            args: clean_middle_generic_args_with_constraints(cx, did, has_self, constraints, args),
243        }],
244    }
245}
246
247pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
248    let segments = match *p {
249        hir::QPath::Resolved(_, path) => &path.segments,
250        hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
251        hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
252    };
253
254    fmt::from_fn(|f| {
255        segments
256            .iter()
257            .map(|seg| (seg.ident.name != kw::PathRoot).then_some(seg.ident).maybe_display())
258            .joined("::", f)
259    })
260    .to_string()
261}
262
263pub(crate) fn build_deref_target_impls(
264    cx: &mut DocContext<'_>,
265    items: &[Item],
266    ret: &mut Vec<Item>,
267) {
268    let tcx = cx.tcx;
269
270    for item in items {
271        let target = match item.kind {
272            ItemKind::AssocTypeItem(ref t, _) => &t.type_,
273            _ => continue,
274        };
275
276        if let Some(prim) = target.primitive_type() {
277            let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
278            for did in prim.impls(tcx).filter(|did| !did.is_local()) {
279                cx.with_param_env(did, |cx| {
280                    inline::build_impl(cx, did, None, ret);
281                });
282            }
283        } else if let Type::Path { path } = target {
284            let did = path.def_id();
285            if !did.is_local() {
286                cx.with_param_env(did, |cx| {
287                    inline::build_impls(cx, did, None, ret);
288                });
289            }
290        }
291    }
292}
293
294pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
295    use rustc_hir::*;
296    debug!("trying to get a name from pattern: {p:?}");
297
298    Symbol::intern(&match &p.kind {
299        PatKind::Err(_)
300        | PatKind::Missing // Let's not perpetuate anon params from Rust 2015; use `_` for them.
301        | PatKind::Never
302        | PatKind::Range(..)
303        | PatKind::Struct(..)
304        | PatKind::Wild => {
305            return kw::Underscore;
306        }
307        PatKind::Binding(_, _, ident, _) => return ident.name,
308        PatKind::Box(p) | PatKind::Ref(p, _) | PatKind::Guard(p, _) => return name_from_pat(p),
309        PatKind::TupleStruct(p, ..) | PatKind::Expr(PatExpr { kind: PatExprKind::Path(p), .. }) => {
310            qpath_to_string(p)
311        }
312        PatKind::Or(pats) => {
313            fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
314        }
315        PatKind::Tuple(elts, _) => {
316            format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
317        }
318        PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
319        PatKind::Expr(..) => {
320            warn!(
321                "tried to get argument name from PatKind::Expr, which is silly in function arguments"
322            );
323            return Symbol::intern("()");
324        }
325        PatKind::Slice(begin, mid, end) => {
326            fn print_pat(pat: &Pat<'_>, wild: bool) -> impl Display {
327                fmt::from_fn(move |f| {
328                    if wild {
329                        f.write_str("..")?;
330                    }
331                    name_from_pat(pat).fmt(f)
332                })
333            }
334
335            format!(
336                "[{}]",
337                fmt::from_fn(|f| {
338                    let begin = begin.iter().map(|p| print_pat(p, false));
339                    let mid = mid.map(|p| print_pat(p, true));
340                    let end = end.iter().map(|p| print_pat(p, false));
341                    begin.chain(mid).chain(end).joined(", ", f)
342                })
343            )
344        }
345    })
346}
347
348pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
349    match n.kind() {
350        ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
351            let s = if let Some(def) = def.as_local() {
352                rendered_const(cx.tcx, cx.tcx.hir_body_owned_by(def), def)
353            } else {
354                inline::print_inlined_const(cx.tcx, def)
355            };
356
357            s
358        }
359        // array lengths are obviously usize
360        ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => {
361            cv.valtree.unwrap_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    // Use a slightly different format for integer types which always shows the actual value.
402    // For all other types, fallback to the original `pretty_print_const`.
403    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
458/// Given a type Path, resolve it to a Type using the TyCtxt
459pub(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
492/// If `res` has a documentation page associated, store it in the cache.
493///
494/// This is later used by [`href()`] to determine the HTML link for the item.
495///
496/// [`href()`]: crate::html::format::href
497pub(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            kind @ (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        ) => (kind.into(), 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
549/// Find the nearest parent module of a [`DefId`].
550pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
551    if def_id.is_top_level_module() {
552        // The crate root has no parent. Use it as the root instead.
553        Some(def_id)
554    } else {
555        let mut current = def_id;
556        // The immediate parent might not always be a module.
557        // Find the first parent which is.
558        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
568/// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
569///
570/// ```
571/// #[doc(hidden)]
572/// pub fn foo() {}
573/// ```
574///
575/// This function exists because it runs on `hir::Attributes` whereas the other is a
576/// `clean::Attributes` method.
577pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
578    attrs_have_doc_flag(tcx.get_attrs(did, sym::doc), flag)
579}
580
581pub(crate) fn attrs_have_doc_flag<'a>(
582    mut attrs: impl Iterator<Item = &'a hir::Attribute>,
583    flag: Symbol,
584) -> bool {
585    attrs.any(|attr| attr.meta_item_list().is_some_and(|l| ast::attr::list_contains_name(&l, flag)))
586}
587
588/// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
589/// so that the channel is consistent.
590///
591/// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
592pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
593pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> =
594    Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap());
595
596/// Render a sequence of macro arms in a format suitable for displaying to the user
597/// as part of an item declaration.
598fn render_macro_arms<'a>(
599    tcx: TyCtxt<'_>,
600    matchers: impl Iterator<Item = &'a TokenTree>,
601    arm_delim: &str,
602) -> String {
603    let mut out = String::new();
604    for matcher in matchers {
605        writeln!(
606            out,
607            "    {matcher} => {{ ... }}{arm_delim}",
608            matcher = render_macro_matcher(tcx, matcher),
609        )
610        .unwrap();
611    }
612    out
613}
614
615pub(super) fn display_macro_source(
616    cx: &mut DocContext<'_>,
617    name: Symbol,
618    def: &ast::MacroDef,
619) -> String {
620    // Extract the spans of all matchers. They represent the "interface" of the macro.
621    let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
622
623    if def.macro_rules {
624        format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
625    } else {
626        if matchers.len() <= 1 {
627            format!(
628                "macro {name}{matchers} {{\n    ...\n}}",
629                matchers = matchers
630                    .map(|matcher| render_macro_matcher(cx.tcx, matcher))
631                    .collect::<String>(),
632            )
633        } else {
634            format!("macro {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ","))
635        }
636    }
637}
638
639pub(crate) fn inherits_doc_hidden(
640    tcx: TyCtxt<'_>,
641    mut def_id: LocalDefId,
642    stop_at: Option<LocalDefId>,
643) -> bool {
644    while let Some(id) = tcx.opt_local_parent(def_id) {
645        if let Some(stop_at) = stop_at
646            && id == stop_at
647        {
648            return false;
649        }
650        def_id = id;
651        if tcx.is_doc_hidden(def_id.to_def_id()) {
652            return true;
653        } else if matches!(
654            tcx.hir_node_by_def_id(def_id),
655            hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
656        ) {
657            // `impl` blocks stand a bit on their own: unless they have `#[doc(hidden)]` directly
658            // on them, they don't inherit it from the parent context.
659            return false;
660        }
661    }
662    false
663}
664
665#[inline]
666pub(crate) fn should_ignore_res(res: Res) -> bool {
667    matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
668}