]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Rollup merge of #103744 - palfrey:unwind-upgrade-cc, r=Mark-Simulacrum
[rust.git] / src / librustdoc / clean / utils.rs
1 use crate::clean::auto_trait::AutoTraitFinder;
2 use crate::clean::blanket_impl::BlanketImplFinder;
3 use crate::clean::render_macro_matchers::render_macro_matcher;
4 use crate::clean::{
5     clean_doc_module, clean_middle_const, clean_middle_region, clean_middle_ty, inline, Crate,
6     ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path,
7     PathSegment, Primitive, PrimitiveType, Term, Type, TypeBinding, TypeBindingKind,
8 };
9 use crate::core::DocContext;
10 use crate::html::format::visibility_to_src_with_space;
11
12 use rustc_ast as ast;
13 use rustc_ast::tokenstream::TokenTree;
14 use rustc_hir as hir;
15 use rustc_hir::def::{DefKind, Res};
16 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
17 use rustc_middle::mir;
18 use rustc_middle::mir::interpret::ConstValue;
19 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
20 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
21 use rustc_span::symbol::{kw, sym, Symbol};
22 use std::fmt::Write as _;
23 use std::mem;
24 use thin_vec::{thin_vec, ThinVec};
25
26 #[cfg(test)]
27 mod tests;
28
29 pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
30     let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
31
32     for &cnum in cx.tcx.crates(()) {
33         // Analyze doc-reachability for extern items
34         crate::visit_lib::lib_embargo_visit_item(cx, cnum.as_def_id());
35     }
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 it.is_extern_crate()
47                     && (it.attrs.has_doc_flag(sym::masked)
48                         || cx.tcx.is_compiler_builtins(it.item_id.krate()))
49                 {
50                     cx.cache.masked_crates.insert(it.item_id.krate());
51                 }
52             }
53         }
54         _ => unreachable!(),
55     }
56
57     let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
58     let primitives = local_crate.primitives(cx.tcx);
59     let keywords = local_crate.keywords(cx.tcx);
60     {
61         let ItemKind::ModuleItem(ref mut m) = *module.kind
62         else { unreachable!() };
63         m.items.extend(primitives.iter().map(|&(def_id, prim)| {
64             Item::from_def_id_and_parts(
65                 def_id,
66                 Some(prim.as_sym()),
67                 ItemKind::PrimitiveItem(prim),
68                 cx,
69             )
70         }));
71         m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
72             Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
73         }));
74     }
75
76     Crate { module, primitives, external_traits: cx.external_traits.clone() }
77 }
78
79 pub(crate) fn substs_to_args<'tcx>(
80     cx: &mut DocContext<'tcx>,
81     substs: &[ty::subst::GenericArg<'tcx>],
82     mut skip_first: bool,
83 ) -> Vec<GenericArg> {
84     let mut ret_val =
85         Vec::with_capacity(substs.len().saturating_sub(if skip_first { 1 } else { 0 }));
86     ret_val.extend(substs.iter().filter_map(|kind| match kind.unpack() {
87         GenericArgKind::Lifetime(lt) => {
88             Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
89         }
90         GenericArgKind::Type(_) if skip_first => {
91             skip_first = false;
92             None
93         }
94         GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(ty, cx, None))),
95         GenericArgKind::Const(ct) => Some(GenericArg::Const(Box::new(clean_middle_const(ct, cx)))),
96     }));
97     ret_val
98 }
99
100 fn external_generic_args<'tcx>(
101     cx: &mut DocContext<'tcx>,
102     did: DefId,
103     has_self: bool,
104     bindings: ThinVec<TypeBinding>,
105     substs: SubstsRef<'tcx>,
106 ) -> GenericArgs {
107     let args = substs_to_args(cx, substs, has_self);
108
109     if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() {
110         let inputs =
111             // The trait's first substitution is the one after self, if there is one.
112             match substs.iter().nth(if has_self { 1 } else { 0 }).unwrap().expect_ty().kind() {
113                 ty::Tuple(tys) => tys.iter().map(|t| clean_middle_ty(t, cx, None)).collect::<Vec<_>>().into(),
114                 _ => return GenericArgs::AngleBracketed { args: args.into(), bindings },
115             };
116         let output = bindings.into_iter().next().and_then(|binding| match binding.kind {
117             TypeBindingKind::Equality { term: Term::Type(ty) } if ty != Type::Tuple(Vec::new()) => {
118                 Some(Box::new(ty))
119             }
120             _ => None,
121         });
122         GenericArgs::Parenthesized { inputs, output }
123     } else {
124         GenericArgs::AngleBracketed { args: args.into(), bindings: bindings.into() }
125     }
126 }
127
128 pub(super) fn external_path<'tcx>(
129     cx: &mut DocContext<'tcx>,
130     did: DefId,
131     has_self: bool,
132     bindings: ThinVec<TypeBinding>,
133     substs: SubstsRef<'tcx>,
134 ) -> Path {
135     let def_kind = cx.tcx.def_kind(did);
136     let name = cx.tcx.item_name(did);
137     Path {
138         res: Res::Def(def_kind, did),
139         segments: thin_vec![PathSegment {
140             name,
141             args: external_generic_args(cx, did, has_self, bindings, substs),
142         }],
143     }
144 }
145
146 /// Remove the generic arguments from a path.
147 pub(crate) fn strip_path_generics(mut path: Path) -> Path {
148     for ps in path.segments.iter_mut() {
149         ps.args = GenericArgs::AngleBracketed { args: Default::default(), bindings: ThinVec::new() }
150     }
151
152     path
153 }
154
155 pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
156     let segments = match *p {
157         hir::QPath::Resolved(_, path) => &path.segments,
158         hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
159         hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
160     };
161
162     let mut s = String::new();
163     for (i, seg) in segments.iter().enumerate() {
164         if i > 0 {
165             s.push_str("::");
166         }
167         if seg.ident.name != kw::PathRoot {
168             s.push_str(seg.ident.as_str());
169         }
170     }
171     s
172 }
173
174 pub(crate) fn build_deref_target_impls(
175     cx: &mut DocContext<'_>,
176     items: &[Item],
177     ret: &mut Vec<Item>,
178 ) {
179     let tcx = cx.tcx;
180
181     for item in items {
182         let target = match *item.kind {
183             ItemKind::AssocTypeItem(ref t, _) => &t.type_,
184             _ => continue,
185         };
186
187         if let Some(prim) = target.primitive_type() {
188             let _prof_timer = cx.tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
189             for did in prim.impls(tcx).filter(|did| !did.is_local()) {
190                 inline::build_impl(cx, None, did, None, ret);
191             }
192         } else if let Type::Path { path } = target {
193             let did = path.def_id();
194             if !did.is_local() {
195                 inline::build_impls(cx, None, did, None, ret);
196             }
197         }
198     }
199 }
200
201 pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
202     use rustc_hir::*;
203     debug!("trying to get a name from pattern: {:?}", p);
204
205     Symbol::intern(&match p.kind {
206         PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
207         PatKind::Binding(_, _, ident, _) => return ident.name,
208         PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
209         PatKind::Or(pats) => {
210             pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
211         }
212         PatKind::Tuple(elts, _) => format!(
213             "({})",
214             elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
215         ),
216         PatKind::Box(p) => return name_from_pat(&*p),
217         PatKind::Ref(p, _) => return name_from_pat(&*p),
218         PatKind::Lit(..) => {
219             warn!(
220                 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
221             );
222             return Symbol::intern("()");
223         }
224         PatKind::Range(..) => return kw::Underscore,
225         PatKind::Slice(begin, ref mid, end) => {
226             let begin = begin.iter().map(|p| name_from_pat(p).to_string());
227             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
228             let end = end.iter().map(|p| name_from_pat(p).to_string());
229             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
230         }
231     })
232 }
233
234 pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
235     match n.kind() {
236         ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs: _ }) => {
237             let s = if let Some(def) = def.as_local() {
238                 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(def.did))
239             } else {
240                 inline::print_inlined_const(cx.tcx, def.did)
241             };
242
243             s
244         }
245         // array lengths are obviously usize
246         ty::ConstKind::Value(ty::ValTree::Leaf(scalar))
247             if *n.ty().kind() == ty::Uint(ty::UintTy::Usize) =>
248         {
249             scalar.to_string()
250         }
251         _ => n.to_string(),
252     }
253 }
254
255 pub(crate) fn print_evaluated_const(
256     tcx: TyCtxt<'_>,
257     def_id: DefId,
258     underscores_and_type: bool,
259 ) -> Option<String> {
260     tcx.const_eval_poly(def_id).ok().and_then(|val| {
261         let ty = tcx.type_of(def_id);
262         match (val, ty.kind()) {
263             (_, &ty::Ref(..)) => None,
264             (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
265             (ConstValue::Scalar(_), _) => {
266                 let const_ = mir::ConstantKind::from_value(val, ty);
267                 Some(print_const_with_custom_print_scalar(tcx, const_, underscores_and_type))
268             }
269             _ => None,
270         }
271     })
272 }
273
274 fn format_integer_with_underscore_sep(num: &str) -> String {
275     let num_chars: Vec<_> = num.chars().collect();
276     let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
277     let chunk_size = match num[num_start_index..].as_bytes() {
278         [b'0', b'b' | b'x', ..] => {
279             num_start_index += 2;
280             4
281         }
282         [b'0', b'o', ..] => {
283             num_start_index += 2;
284             let remaining_chars = num_chars.len() - num_start_index;
285             if remaining_chars <= 6 {
286                 // don't add underscores to Unix permissions like 0755 or 100755
287                 return num.to_string();
288             }
289             3
290         }
291         _ => 3,
292     };
293
294     num_chars[..num_start_index]
295         .iter()
296         .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
297         .collect()
298 }
299
300 fn print_const_with_custom_print_scalar<'tcx>(
301     tcx: TyCtxt<'tcx>,
302     ct: mir::ConstantKind<'tcx>,
303     underscores_and_type: bool,
304 ) -> String {
305     // Use a slightly different format for integer types which always shows the actual value.
306     // For all other types, fallback to the original `pretty_print_const`.
307     match (ct, ct.ty().kind()) {
308         (mir::ConstantKind::Val(ConstValue::Scalar(int), _), ty::Uint(ui)) => {
309             if underscores_and_type {
310                 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
311             } else {
312                 int.to_string()
313             }
314         }
315         (mir::ConstantKind::Val(ConstValue::Scalar(int), _), ty::Int(i)) => {
316             let ty = ct.ty();
317             let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
318             let data = int.assert_bits(size);
319             let sign_extended_data = size.sign_extend(data) as i128;
320             if underscores_and_type {
321                 format!(
322                     "{}{}",
323                     format_integer_with_underscore_sep(&sign_extended_data.to_string()),
324                     i.name_str()
325                 )
326             } else {
327                 sign_extended_data.to_string()
328             }
329         }
330         _ => ct.to_string(),
331     }
332 }
333
334 pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
335     if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
336         if let hir::ExprKind::Lit(_) = &expr.kind {
337             return true;
338         }
339
340         if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
341             if let hir::ExprKind::Lit(_) = &expr.kind {
342                 return true;
343             }
344         }
345     }
346
347     false
348 }
349
350 /// Build a textual representation of an unevaluated constant expression.
351 ///
352 /// If the const expression is too complex, an underscore `_` is returned.
353 /// For const arguments, it's `{ _ }` to be precise.
354 /// This means that the output is not necessarily valid Rust code.
355 ///
356 /// Currently, only
357 ///
358 /// * literals (optionally with a leading `-`)
359 /// * unit `()`
360 /// * blocks (`{ … }`) around simple expressions and
361 /// * paths without arguments
362 ///
363 /// are considered simple enough. Simple blocks are included since they are
364 /// necessary to disambiguate unit from the unit type.
365 /// This list might get extended in the future.
366 ///
367 /// Without this censoring, in a lot of cases the output would get too large
368 /// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
369 /// Further, private and `doc(hidden)` fields of structs would get leaked
370 /// since HIR datatypes like the `body` parameter do not contain enough
371 /// semantic information for this function to be able to hide them –
372 /// at least not without significant performance overhead.
373 ///
374 /// Whenever possible, prefer to evaluate the constant first and try to
375 /// use a different method for pretty-printing. Ideally this function
376 /// should only ever be used as a fallback.
377 pub(crate) fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
378     let hir = tcx.hir();
379     let value = &hir.body(body).value;
380
381     #[derive(PartialEq, Eq)]
382     enum Classification {
383         Literal,
384         Simple,
385         Complex,
386     }
387
388     use Classification::*;
389
390     fn classify(expr: &hir::Expr<'_>) -> Classification {
391         match &expr.kind {
392             hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
393                 if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
394             }
395             hir::ExprKind::Lit(_) => Literal,
396             hir::ExprKind::Tup([]) => Simple,
397             hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
398                 if classify(expr) == Complex { Complex } else { Simple }
399             }
400             // Paths with a self-type or arguments are too “complex” following our measure since
401             // they may leak private fields of structs (with feature `adt_const_params`).
402             // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
403             // Paths without arguments are definitely harmless though.
404             hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
405                 if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
406             }
407             // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
408             //        contains const arguments. Is there a *concise* way to check for this?
409             hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
410             // FIXME: Can they contain const arguments and thus leak private struct fields?
411             hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple,
412             _ => Complex,
413         }
414     }
415
416     let classification = classify(value);
417
418     if classification == Literal
419     && !value.span.from_expansion()
420     && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) {
421         // For literals, we avoid invoking the pretty-printer and use the source snippet instead to
422         // preserve certain stylistic choices the user likely made for the sake legibility like
423         //
424         // * hexadecimal notation
425         // * underscores
426         // * character escapes
427         //
428         // FIXME: This passes through `-/*spacer*/0` verbatim.
429         snippet
430     } else if classification == Simple {
431         // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
432         // other formatting artifacts.
433         rustc_hir_pretty::id_to_string(&hir, body.hir_id)
434     } else if tcx.def_kind(hir.body_owner_def_id(body).to_def_id()) == DefKind::AnonConst {
435         // FIXME: Omit the curly braces if the enclosing expression is an array literal
436         //        with a repeated element (an `ExprKind::Repeat`) as in such case it
437         //        would not actually need any disambiguation.
438         "{ _ }".to_owned()
439     } else {
440         "_".to_owned()
441     }
442 }
443
444 /// Given a type Path, resolve it to a Type using the TyCtxt
445 pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
446     debug!("resolve_type({:?})", path);
447
448     match path.res {
449         Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
450         Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
451             Generic(kw::SelfUpper)
452         }
453         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
454         _ => {
455             let _ = register_res(cx, path.res);
456             Type::Path { path }
457         }
458     }
459 }
460
461 pub(crate) fn get_auto_trait_and_blanket_impls(
462     cx: &mut DocContext<'_>,
463     item_def_id: DefId,
464 ) -> impl Iterator<Item = Item> {
465     let auto_impls = cx
466         .sess()
467         .prof
468         .generic_activity("get_auto_trait_impls")
469         .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
470     let blanket_impls = cx
471         .sess()
472         .prof
473         .generic_activity("get_blanket_impls")
474         .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
475     auto_impls.into_iter().chain(blanket_impls)
476 }
477
478 /// If `res` has a documentation page associated, store it in the cache.
479 ///
480 /// This is later used by [`href()`] to determine the HTML link for the item.
481 ///
482 /// [`href()`]: crate::html::format::href
483 pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
484     use DefKind::*;
485     debug!("register_res({:?})", res);
486
487     let (kind, did) = match res {
488         Res::Def(
489             kind @ (AssocTy | AssocFn | AssocConst | Variant | Fn | TyAlias | Enum | Trait | Struct
490             | Union | Mod | ForeignTy | Const | Static(_) | Macro(..) | TraitAlias),
491             did,
492         ) => (kind.into(), did),
493
494         _ => panic!("register_res: unexpected {:?}", res),
495     };
496     if did.is_local() {
497         return did;
498     }
499     inline::record_extern_fqn(cx, did, kind);
500     did
501 }
502
503 pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
504     ImportSource {
505         did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
506         path,
507     }
508 }
509
510 pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
511 where
512     F: FnOnce(&mut DocContext<'tcx>) -> R,
513 {
514     let old_bounds = mem::take(&mut cx.impl_trait_bounds);
515     let r = f(cx);
516     assert!(cx.impl_trait_bounds.is_empty());
517     cx.impl_trait_bounds = old_bounds;
518     r
519 }
520
521 /// Find the nearest parent module of a [`DefId`].
522 pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
523     if def_id.is_top_level_module() {
524         // The crate root has no parent. Use it as the root instead.
525         Some(def_id)
526     } else {
527         let mut current = def_id;
528         // The immediate parent might not always be a module.
529         // Find the first parent which is.
530         while let Some(parent) = tcx.opt_parent(current) {
531             if tcx.def_kind(parent) == DefKind::Mod {
532                 return Some(parent);
533             }
534             current = parent;
535         }
536         None
537     }
538 }
539
540 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
541 ///
542 /// ```
543 /// #[doc(hidden)]
544 /// pub fn foo() {}
545 /// ```
546 ///
547 /// This function exists because it runs on `hir::Attributes` whereas the other is a
548 /// `clean::Attributes` method.
549 pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
550     tcx.get_attrs(did, sym::doc).any(|attr| {
551         attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
552     })
553 }
554
555 /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
556 /// so that the channel is consistent.
557 ///
558 /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
559 pub(crate) const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
560
561 /// Render a sequence of macro arms in a format suitable for displaying to the user
562 /// as part of an item declaration.
563 pub(super) fn render_macro_arms<'a>(
564     tcx: TyCtxt<'_>,
565     matchers: impl Iterator<Item = &'a TokenTree>,
566     arm_delim: &str,
567 ) -> String {
568     let mut out = String::new();
569     for matcher in matchers {
570         writeln!(out, "    {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim)
571             .unwrap();
572     }
573     out
574 }
575
576 pub(super) fn display_macro_source(
577     cx: &mut DocContext<'_>,
578     name: Symbol,
579     def: &ast::MacroDef,
580     def_id: DefId,
581     vis: ty::Visibility<DefId>,
582 ) -> String {
583     let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
584     // Extract the spans of all matchers. They represent the "interface" of the macro.
585     let matchers = tts.chunks(4).map(|arm| &arm[0]);
586
587     if def.macro_rules {
588         format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";"))
589     } else {
590         if matchers.len() <= 1 {
591             format!(
592                 "{}macro {}{} {{\n    ...\n}}",
593                 visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
594                 name,
595                 matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
596             )
597         } else {
598             format!(
599                 "{}macro {} {{\n{}}}",
600                 visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
601                 name,
602                 render_macro_arms(cx.tcx, matchers, ","),
603             )
604         }
605     }
606 }