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