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