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