]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Auto merge of #93717 - pietroalbini:pa-ci-profiler, r=Mark-Simulacrum
[rust.git] / src / librustdoc / html / format.rs
1 //! HTML formatting module
2 //!
3 //! This module contains a large number of `fmt::Display` implementations for
4 //! various types in `rustdoc::clean`. These implementations all currently
5 //! assume that HTML output is desired, although it may be possible to redesign
6 //! them in the future to instead emit any format desired.
7
8 use std::borrow::Cow;
9 use std::cell::Cell;
10 use std::fmt;
11 use std::iter;
12
13 use rustc_attr::{ConstStability, StabilityLevel};
14 use rustc_data_structures::captures::Captures;
15 use rustc_data_structures::fx::FxHashSet;
16 use rustc_hir as hir;
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
19 use rustc_middle::ty;
20 use rustc_middle::ty::DefIdTree;
21 use rustc_middle::ty::TyCtxt;
22 use rustc_span::symbol::kw;
23 use rustc_span::{sym, Symbol};
24 use rustc_target::spec::abi::Abi;
25
26 use crate::clean::{
27     self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
28     PrimitiveType,
29 };
30 use crate::formats::item_type::ItemType;
31 use crate::html::escape::Escape;
32 use crate::html::render::Context;
33
34 use super::url_parts_builder::estimate_item_path_byte_length;
35 use super::url_parts_builder::UrlPartsBuilder;
36
37 pub(crate) trait Print {
38     fn print(self, buffer: &mut Buffer);
39 }
40
41 impl<F> Print for F
42 where
43     F: FnOnce(&mut Buffer),
44 {
45     fn print(self, buffer: &mut Buffer) {
46         (self)(buffer)
47     }
48 }
49
50 impl Print for String {
51     fn print(self, buffer: &mut Buffer) {
52         buffer.write_str(&self);
53     }
54 }
55
56 impl Print for &'_ str {
57     fn print(self, buffer: &mut Buffer) {
58         buffer.write_str(self);
59     }
60 }
61
62 #[derive(Debug, Clone)]
63 pub(crate) struct Buffer {
64     for_html: bool,
65     buffer: String,
66 }
67
68 impl core::fmt::Write for Buffer {
69     #[inline]
70     fn write_str(&mut self, s: &str) -> fmt::Result {
71         self.buffer.write_str(s)
72     }
73
74     #[inline]
75     fn write_char(&mut self, c: char) -> fmt::Result {
76         self.buffer.write_char(c)
77     }
78
79     #[inline]
80     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
81         self.buffer.write_fmt(args)
82     }
83 }
84
85 impl Buffer {
86     pub(crate) fn empty_from(v: &Buffer) -> Buffer {
87         Buffer { for_html: v.for_html, buffer: String::new() }
88     }
89
90     pub(crate) fn html() -> Buffer {
91         Buffer { for_html: true, buffer: String::new() }
92     }
93
94     pub(crate) fn new() -> Buffer {
95         Buffer { for_html: false, buffer: String::new() }
96     }
97
98     pub(crate) fn is_empty(&self) -> bool {
99         self.buffer.is_empty()
100     }
101
102     pub(crate) fn into_inner(self) -> String {
103         self.buffer
104     }
105
106     pub(crate) fn insert_str(&mut self, idx: usize, s: &str) {
107         self.buffer.insert_str(idx, s);
108     }
109
110     pub(crate) fn push_str(&mut self, s: &str) {
111         self.buffer.push_str(s);
112     }
113
114     pub(crate) fn push_buffer(&mut self, other: Buffer) {
115         self.buffer.push_str(&other.buffer);
116     }
117
118     // Intended for consumption by write! and writeln! (std::fmt) but without
119     // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
120     // import).
121     pub(crate) fn write_str(&mut self, s: &str) {
122         self.buffer.push_str(s);
123     }
124
125     // Intended for consumption by write! and writeln! (std::fmt) but without
126     // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
127     // import).
128     pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
129         use fmt::Write;
130         self.buffer.write_fmt(v).unwrap();
131     }
132
133     pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
134         t.print(&mut self);
135         self.into_inner()
136     }
137
138     pub(crate) fn is_for_html(&self) -> bool {
139         self.for_html
140     }
141
142     pub(crate) fn reserve(&mut self, additional: usize) {
143         self.buffer.reserve(additional)
144     }
145 }
146
147 fn comma_sep<T: fmt::Display>(
148     items: impl Iterator<Item = T>,
149     space_after_comma: bool,
150 ) -> impl fmt::Display {
151     display_fn(move |f| {
152         for (i, item) in items.enumerate() {
153             if i != 0 {
154                 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
155             }
156             fmt::Display::fmt(&item, f)?;
157         }
158         Ok(())
159     })
160 }
161
162 pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
163     bounds: &'a [clean::GenericBound],
164     cx: &'a Context<'tcx>,
165 ) -> impl fmt::Display + 'a + Captures<'tcx> {
166     display_fn(move |f| {
167         let mut bounds_dup = FxHashSet::default();
168
169         for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
170             if i > 0 {
171                 f.write_str(" + ")?;
172             }
173             fmt::Display::fmt(&bound.print(cx), f)?;
174         }
175         Ok(())
176     })
177 }
178
179 impl clean::GenericParamDef {
180     pub(crate) fn print<'a, 'tcx: 'a>(
181         &'a self,
182         cx: &'a Context<'tcx>,
183     ) -> impl fmt::Display + 'a + Captures<'tcx> {
184         display_fn(move |f| match &self.kind {
185             clean::GenericParamDefKind::Lifetime { outlives } => {
186                 write!(f, "{}", self.name)?;
187
188                 if !outlives.is_empty() {
189                     f.write_str(": ")?;
190                     for (i, lt) in outlives.iter().enumerate() {
191                         if i != 0 {
192                             f.write_str(" + ")?;
193                         }
194                         write!(f, "{}", lt.print())?;
195                     }
196                 }
197
198                 Ok(())
199             }
200             clean::GenericParamDefKind::Type { bounds, default, .. } => {
201                 f.write_str(self.name.as_str())?;
202
203                 if !bounds.is_empty() {
204                     if f.alternate() {
205                         write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
206                     } else {
207                         write!(f, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
208                     }
209                 }
210
211                 if let Some(ref ty) = default {
212                     if f.alternate() {
213                         write!(f, " = {:#}", ty.print(cx))?;
214                     } else {
215                         write!(f, "&nbsp;=&nbsp;{}", ty.print(cx))?;
216                     }
217                 }
218
219                 Ok(())
220             }
221             clean::GenericParamDefKind::Const { ty, default, .. } => {
222                 if f.alternate() {
223                     write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
224                 } else {
225                     write!(f, "const {}:&nbsp;{}", self.name, ty.print(cx))?;
226                 }
227
228                 if let Some(default) = default {
229                     if f.alternate() {
230                         write!(f, " = {:#}", default)?;
231                     } else {
232                         write!(f, "&nbsp;=&nbsp;{}", default)?;
233                     }
234                 }
235
236                 Ok(())
237             }
238         })
239     }
240 }
241
242 impl clean::Generics {
243     pub(crate) fn print<'a, 'tcx: 'a>(
244         &'a self,
245         cx: &'a Context<'tcx>,
246     ) -> impl fmt::Display + 'a + Captures<'tcx> {
247         display_fn(move |f| {
248             let mut real_params =
249                 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
250             if real_params.peek().is_none() {
251                 return Ok(());
252             }
253
254             if f.alternate() {
255                 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
256             } else {
257                 write!(f, "&lt;{}&gt;", comma_sep(real_params.map(|g| g.print(cx)), true))
258             }
259         })
260     }
261 }
262
263 /// * The Generics from which to emit a where-clause.
264 /// * The number of spaces to indent each line with.
265 /// * Whether the where-clause needs to add a comma and newline after the last bound.
266 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
267     gens: &'a clean::Generics,
268     cx: &'a Context<'tcx>,
269     indent: usize,
270     end_newline: bool,
271 ) -> impl fmt::Display + 'a + Captures<'tcx> {
272     use fmt::Write;
273
274     display_fn(move |f| {
275         let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
276             !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
277         }).map(|pred| {
278             display_fn(move |f| {
279                 if f.alternate() {
280                     f.write_str(" ")?;
281                 } else {
282                     f.write_str("<br>")?;
283                 }
284
285                 match pred {
286                     clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
287                         let ty_cx = ty.print(cx);
288                         let generic_bounds = print_generic_bounds(bounds, cx);
289
290                         if bound_params.is_empty() {
291                             if f.alternate() {
292                                 write!(f, "{ty_cx:#}: {generic_bounds:#}")
293                             } else {
294                                 write!(f, "{ty_cx}: {generic_bounds}")
295                             }
296                         } else {
297                             if f.alternate() {
298                                 write!(
299                                     f,
300                                     "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
301                                     comma_sep(bound_params.iter().map(|lt| lt.print()), true)
302                                 )
303                             } else {
304                                 write!(
305                                     f,
306                                     "for&lt;{}&gt; {ty_cx}: {generic_bounds}",
307                                     comma_sep(bound_params.iter().map(|lt| lt.print()), true)
308                                 )
309                             }
310                         }
311                     }
312                     clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
313                         let mut bounds_display = String::new();
314                         for bound in bounds.iter().map(|b| b.print(cx)) {
315                             write!(bounds_display, "{bound} + ")?;
316                         }
317                         bounds_display.truncate(bounds_display.len() - " + ".len());
318                         write!(f, "{}: {bounds_display}", lifetime.print())
319                     }
320                     clean::WherePredicate::EqPredicate { lhs, rhs } => {
321                         if f.alternate() {
322                             write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
323                         } else {
324                             write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
325                         }
326                     }
327                 }
328             })
329         }).peekable();
330
331         if where_predicates.peek().is_none() {
332             return Ok(());
333         }
334
335         let where_preds = comma_sep(where_predicates, false);
336         let clause = if f.alternate() {
337             if end_newline {
338                 // add a space so stripping <br> tags and breaking spaces still renders properly
339                 format!(" where{where_preds}, ")
340             } else {
341                 format!(" where{where_preds}")
342             }
343         } else {
344             let mut br_with_padding = String::with_capacity(6 * indent + 28);
345             br_with_padding.push_str("<br>");
346             for _ in 0..indent + 4 {
347                 br_with_padding.push_str("&nbsp;");
348             }
349             let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
350
351             if end_newline {
352                 let mut clause = "&nbsp;".repeat(indent.saturating_sub(1));
353                 // add a space so stripping <br> tags and breaking spaces still renders properly
354                 write!(
355                     clause,
356                     " <span class=\"where fmt-newline\">where{where_preds},&nbsp;</span>"
357                 )?;
358                 clause
359             } else {
360                 // insert a <br> tag after a single space but before multiple spaces at the start
361                 if indent == 0 {
362                     format!(" <br><span class=\"where\">where{where_preds}</span>")
363                 } else {
364                     let mut clause = br_with_padding;
365                     clause.truncate(clause.len() - 5 * "&nbsp;".len());
366                     write!(clause, " <span class=\"where\">where{where_preds}</span>")?;
367                     clause
368                 }
369             }
370         };
371         write!(f, "{clause}")
372     })
373 }
374
375 impl clean::Lifetime {
376     pub(crate) fn print(&self) -> impl fmt::Display + '_ {
377         self.0.as_str()
378     }
379 }
380
381 impl clean::Constant {
382     pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
383         let expr = self.expr(tcx);
384         display_fn(
385             move |f| {
386                 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
387             },
388         )
389     }
390 }
391
392 impl clean::PolyTrait {
393     fn print<'a, 'tcx: 'a>(
394         &'a self,
395         cx: &'a Context<'tcx>,
396     ) -> impl fmt::Display + 'a + Captures<'tcx> {
397         display_fn(move |f| {
398             if !self.generic_params.is_empty() {
399                 if f.alternate() {
400                     write!(
401                         f,
402                         "for<{:#}> ",
403                         comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
404                     )?;
405                 } else {
406                     write!(
407                         f,
408                         "for&lt;{}&gt; ",
409                         comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
410                     )?;
411                 }
412             }
413             if f.alternate() {
414                 write!(f, "{:#}", self.trait_.print(cx))
415             } else {
416                 write!(f, "{}", self.trait_.print(cx))
417             }
418         })
419     }
420 }
421
422 impl clean::GenericBound {
423     pub(crate) fn print<'a, 'tcx: 'a>(
424         &'a self,
425         cx: &'a Context<'tcx>,
426     ) -> impl fmt::Display + 'a + Captures<'tcx> {
427         display_fn(move |f| match self {
428             clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
429             clean::GenericBound::TraitBound(ty, modifier) => {
430                 let modifier_str = match modifier {
431                     hir::TraitBoundModifier::None => "",
432                     hir::TraitBoundModifier::Maybe => "?",
433                     // ~const is experimental; do not display those bounds in rustdoc
434                     hir::TraitBoundModifier::MaybeConst => "",
435                 };
436                 if f.alternate() {
437                     write!(f, "{}{:#}", modifier_str, ty.print(cx))
438                 } else {
439                     write!(f, "{}{}", modifier_str, ty.print(cx))
440                 }
441             }
442         })
443     }
444 }
445
446 impl clean::GenericArgs {
447     fn print<'a, 'tcx: 'a>(
448         &'a self,
449         cx: &'a Context<'tcx>,
450     ) -> impl fmt::Display + 'a + Captures<'tcx> {
451         display_fn(move |f| {
452             match self {
453                 clean::GenericArgs::AngleBracketed { args, bindings } => {
454                     if !args.is_empty() || !bindings.is_empty() {
455                         if f.alternate() {
456                             f.write_str("<")?;
457                         } else {
458                             f.write_str("&lt;")?;
459                         }
460                         let mut comma = false;
461                         for arg in args.iter() {
462                             if comma {
463                                 f.write_str(", ")?;
464                             }
465                             comma = true;
466                             if f.alternate() {
467                                 write!(f, "{:#}", arg.print(cx))?;
468                             } else {
469                                 write!(f, "{}", arg.print(cx))?;
470                             }
471                         }
472                         for binding in bindings.iter() {
473                             if comma {
474                                 f.write_str(", ")?;
475                             }
476                             comma = true;
477                             if f.alternate() {
478                                 write!(f, "{:#}", binding.print(cx))?;
479                             } else {
480                                 write!(f, "{}", binding.print(cx))?;
481                             }
482                         }
483                         if f.alternate() {
484                             f.write_str(">")?;
485                         } else {
486                             f.write_str("&gt;")?;
487                         }
488                     }
489                 }
490                 clean::GenericArgs::Parenthesized { inputs, output } => {
491                     f.write_str("(")?;
492                     let mut comma = false;
493                     for ty in inputs.iter() {
494                         if comma {
495                             f.write_str(", ")?;
496                         }
497                         comma = true;
498                         if f.alternate() {
499                             write!(f, "{:#}", ty.print(cx))?;
500                         } else {
501                             write!(f, "{}", ty.print(cx))?;
502                         }
503                     }
504                     f.write_str(")")?;
505                     if let Some(ref ty) = *output {
506                         if f.alternate() {
507                             write!(f, " -> {:#}", ty.print(cx))?;
508                         } else {
509                             write!(f, " -&gt; {}", ty.print(cx))?;
510                         }
511                     }
512                 }
513             }
514             Ok(())
515         })
516     }
517 }
518
519 // Possible errors when computing href link source for a `DefId`
520 pub(crate) enum HrefError {
521     /// This item is known to rustdoc, but from a crate that does not have documentation generated.
522     ///
523     /// This can only happen for non-local items.
524     ///
525     /// # Example
526     ///
527     /// Crate `a` defines a public trait and crate `b` â€“ the target crate that depends on `a` â€“
528     /// implements it for a local type.
529     /// We document `b` but **not** `a` (we only _build_ the latter â€“ with `rustc`):
530     ///
531     /// ```sh
532     /// rustc a.rs --crate-type=lib
533     /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
534     /// ```
535     ///
536     /// Now, the associated items in the trait impl want to link to the corresponding item in the
537     /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
538     /// *documentation (was) not built*.
539     DocumentationNotBuilt,
540     /// This can only happen for non-local items when `--document-private-items` is not passed.
541     Private,
542     // Not in external cache, href link should be in same page
543     NotInExternalCache,
544 }
545
546 // Panics if `syms` is empty.
547 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
548     let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
549     s.push_str(syms[0].as_str());
550     for sym in &syms[1..] {
551         s.push_str("::");
552         s.push_str(sym.as_str());
553     }
554     s
555 }
556
557 pub(crate) fn href_with_root_path(
558     did: DefId,
559     cx: &Context<'_>,
560     root_path: Option<&str>,
561 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
562     let tcx = cx.tcx();
563     let def_kind = tcx.def_kind(did);
564     let did = match def_kind {
565         DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
566             // documented on their parent's page
567             tcx.parent(did)
568         }
569         _ => did,
570     };
571     let cache = cx.cache();
572     let relative_to = &cx.current;
573     fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
574         if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
575     }
576
577     if !did.is_local()
578         && !cache.access_levels.is_public(did)
579         && !cache.document_private
580         && !cache.primitive_locations.values().any(|&id| id == did)
581     {
582         return Err(HrefError::Private);
583     }
584
585     let mut is_remote = false;
586     let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
587         Some(&(ref fqp, shortty)) => (fqp, shortty, {
588             let module_fqp = to_module_fqp(shortty, fqp.as_slice());
589             debug!(?fqp, ?shortty, ?module_fqp);
590             href_relative_parts(module_fqp, relative_to).collect()
591         }),
592         None => {
593             if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
594                 let module_fqp = to_module_fqp(shortty, fqp);
595                 (
596                     fqp,
597                     shortty,
598                     match cache.extern_locations[&did.krate] {
599                         ExternalLocation::Remote(ref s) => {
600                             is_remote = true;
601                             let s = s.trim_end_matches('/');
602                             let mut builder = UrlPartsBuilder::singleton(s);
603                             builder.extend(module_fqp.iter().copied());
604                             builder
605                         }
606                         ExternalLocation::Local => {
607                             href_relative_parts(module_fqp, relative_to).collect()
608                         }
609                         ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
610                     },
611                 )
612             } else {
613                 return Err(HrefError::NotInExternalCache);
614             }
615         }
616     };
617     if !is_remote {
618         if let Some(root_path) = root_path {
619             let root = root_path.trim_end_matches('/');
620             url_parts.push_front(root);
621         }
622     }
623     debug!(?url_parts);
624     match shortty {
625         ItemType::Module => {
626             url_parts.push("index.html");
627         }
628         _ => {
629             let prefix = shortty.as_str();
630             let last = fqp.last().unwrap();
631             url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
632         }
633     }
634     Ok((url_parts.finish(), shortty, fqp.to_vec()))
635 }
636
637 pub(crate) fn href(
638     did: DefId,
639     cx: &Context<'_>,
640 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
641     href_with_root_path(did, cx, None)
642 }
643
644 /// Both paths should only be modules.
645 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
646 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
647 pub(crate) fn href_relative_parts<'fqp>(
648     fqp: &'fqp [Symbol],
649     relative_to_fqp: &[Symbol],
650 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
651     for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
652         // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
653         if f != r {
654             let dissimilar_part_count = relative_to_fqp.len() - i;
655             let fqp_module = &fqp[i..fqp.len()];
656             return box iter::repeat(sym::dotdot)
657                 .take(dissimilar_part_count)
658                 .chain(fqp_module.iter().copied());
659         }
660     }
661     // e.g. linking to std::sync::atomic from std::sync
662     if relative_to_fqp.len() < fqp.len() {
663         box fqp[relative_to_fqp.len()..fqp.len()].iter().copied()
664     // e.g. linking to std::sync from std::sync::atomic
665     } else if fqp.len() < relative_to_fqp.len() {
666         let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
667         box iter::repeat(sym::dotdot).take(dissimilar_part_count)
668     // linking to the same module
669     } else {
670         box iter::empty()
671     }
672 }
673
674 /// Used to render a [`clean::Path`].
675 fn resolved_path<'cx>(
676     w: &mut fmt::Formatter<'_>,
677     did: DefId,
678     path: &clean::Path,
679     print_all: bool,
680     use_absolute: bool,
681     cx: &'cx Context<'_>,
682 ) -> fmt::Result {
683     let last = path.segments.last().unwrap();
684
685     if print_all {
686         for seg in &path.segments[..path.segments.len() - 1] {
687             write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
688         }
689     }
690     if w.alternate() {
691         write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
692     } else {
693         let path = if use_absolute {
694             if let Ok((_, _, fqp)) = href(did, cx) {
695                 format!(
696                     "{}::{}",
697                     join_with_double_colon(&fqp[..fqp.len() - 1]),
698                     anchor(did, *fqp.last().unwrap(), cx)
699                 )
700             } else {
701                 last.name.to_string()
702             }
703         } else {
704             anchor(did, last.name, cx).to_string()
705         };
706         write!(w, "{}{}", path, last.args.print(cx))?;
707     }
708     Ok(())
709 }
710
711 fn primitive_link(
712     f: &mut fmt::Formatter<'_>,
713     prim: clean::PrimitiveType,
714     name: &str,
715     cx: &Context<'_>,
716 ) -> fmt::Result {
717     let m = &cx.cache();
718     let mut needs_termination = false;
719     if !f.alternate() {
720         match m.primitive_locations.get(&prim) {
721             Some(&def_id) if def_id.is_local() => {
722                 let len = cx.current.len();
723                 let len = if len == 0 { 0 } else { len - 1 };
724                 write!(
725                     f,
726                     "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
727                     "../".repeat(len),
728                     prim.as_sym()
729                 )?;
730                 needs_termination = true;
731             }
732             Some(&def_id) => {
733                 let loc = match m.extern_locations[&def_id.krate] {
734                     ExternalLocation::Remote(ref s) => {
735                         let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
736                         let builder: UrlPartsBuilder =
737                             [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
738                                 .into_iter()
739                                 .collect();
740                         Some(builder)
741                     }
742                     ExternalLocation::Local => {
743                         let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
744                         Some(if cx.current.first() == Some(&cname_sym) {
745                             iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
746                         } else {
747                             iter::repeat(sym::dotdot)
748                                 .take(cx.current.len())
749                                 .chain(iter::once(cname_sym))
750                                 .collect()
751                         })
752                     }
753                     ExternalLocation::Unknown => None,
754                 };
755                 if let Some(mut loc) = loc {
756                     loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
757                     write!(f, "<a class=\"primitive\" href=\"{}\">", loc.finish())?;
758                     needs_termination = true;
759                 }
760             }
761             None => {}
762         }
763     }
764     write!(f, "{}", name)?;
765     if needs_termination {
766         write!(f, "</a>")?;
767     }
768     Ok(())
769 }
770
771 /// Helper to render type parameters
772 fn tybounds<'a, 'tcx: 'a>(
773     bounds: &'a [clean::PolyTrait],
774     lt: &'a Option<clean::Lifetime>,
775     cx: &'a Context<'tcx>,
776 ) -> impl fmt::Display + 'a + Captures<'tcx> {
777     display_fn(move |f| {
778         for (i, bound) in bounds.iter().enumerate() {
779             if i > 0 {
780                 write!(f, " + ")?;
781             }
782
783             fmt::Display::fmt(&bound.print(cx), f)?;
784         }
785
786         if let Some(lt) = lt {
787             write!(f, " + ")?;
788             fmt::Display::fmt(&lt.print(), f)?;
789         }
790         Ok(())
791     })
792 }
793
794 pub(crate) fn anchor<'a, 'cx: 'a>(
795     did: DefId,
796     text: Symbol,
797     cx: &'cx Context<'_>,
798 ) -> impl fmt::Display + 'a {
799     let parts = href(did, cx);
800     display_fn(move |f| {
801         if let Ok((url, short_ty, fqp)) = parts {
802             write!(
803                 f,
804                 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
805                 short_ty,
806                 url,
807                 short_ty,
808                 join_with_double_colon(&fqp),
809                 text.as_str()
810             )
811         } else {
812             write!(f, "{}", text)
813         }
814     })
815 }
816
817 fn fmt_type<'cx>(
818     t: &clean::Type,
819     f: &mut fmt::Formatter<'_>,
820     use_absolute: bool,
821     cx: &'cx Context<'_>,
822 ) -> fmt::Result {
823     trace!("fmt_type(t = {:?})", t);
824
825     match *t {
826         clean::Generic(name) => write!(f, "{}", name),
827         clean::Type::Path { ref path } => {
828             // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
829             let did = path.def_id();
830             resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
831         }
832         clean::DynTrait(ref bounds, ref lt) => {
833             f.write_str("dyn ")?;
834             fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
835         }
836         clean::Infer => write!(f, "_"),
837         clean::Primitive(clean::PrimitiveType::Never) => {
838             primitive_link(f, PrimitiveType::Never, "!", cx)
839         }
840         clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
841         clean::BareFunction(ref decl) => {
842             if f.alternate() {
843                 write!(
844                     f,
845                     "{:#}{}{:#}fn{:#}",
846                     decl.print_hrtb_with_space(cx),
847                     decl.unsafety.print_with_space(),
848                     print_abi_with_space(decl.abi),
849                     decl.decl.print(cx),
850                 )
851             } else {
852                 write!(
853                     f,
854                     "{}{}{}",
855                     decl.print_hrtb_with_space(cx),
856                     decl.unsafety.print_with_space(),
857                     print_abi_with_space(decl.abi)
858                 )?;
859                 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
860                 write!(f, "{}", decl.decl.print(cx))
861             }
862         }
863         clean::Tuple(ref typs) => {
864             match &typs[..] {
865                 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
866                 &[ref one] => {
867                     primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
868                     // Carry `f.alternate()` into this display w/o branching manually.
869                     fmt::Display::fmt(&one.print(cx), f)?;
870                     primitive_link(f, PrimitiveType::Tuple, ",)", cx)
871                 }
872                 many => {
873                     primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
874                     for (i, item) in many.iter().enumerate() {
875                         if i != 0 {
876                             write!(f, ", ")?;
877                         }
878                         fmt::Display::fmt(&item.print(cx), f)?;
879                     }
880                     primitive_link(f, PrimitiveType::Tuple, ")", cx)
881                 }
882             }
883         }
884         clean::Slice(ref t) => match **t {
885             clean::Generic(name) => {
886                 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
887             }
888             _ => {
889                 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
890                 fmt::Display::fmt(&t.print(cx), f)?;
891                 primitive_link(f, PrimitiveType::Slice, "]", cx)
892             }
893         },
894         clean::Array(ref t, ref n) => {
895             primitive_link(f, PrimitiveType::Array, "[", cx)?;
896             fmt::Display::fmt(&t.print(cx), f)?;
897             if f.alternate() {
898                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
899             } else {
900                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
901             }
902         }
903         clean::RawPointer(m, ref t) => {
904             let m = match m {
905                 hir::Mutability::Mut => "mut",
906                 hir::Mutability::Not => "const",
907             };
908
909             if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
910                 let text = if f.alternate() {
911                     format!("*{} {:#}", m, t.print(cx))
912                 } else {
913                     format!("*{} {}", m, t.print(cx))
914                 };
915                 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
916             } else {
917                 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
918                 fmt::Display::fmt(&t.print(cx), f)
919             }
920         }
921         clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
922             let lt = match l {
923                 Some(l) => format!("{} ", l.print()),
924                 _ => String::new(),
925             };
926             let m = mutability.print_with_space();
927             let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
928             match **ty {
929                 clean::Slice(ref bt) => {
930                     // `BorrowedRef{ ... Slice(T) }` is `&[T]`
931                     match **bt {
932                         clean::Generic(name) => primitive_link(
933                             f,
934                             PrimitiveType::Slice,
935                             &format!("{amp}{lt}{m}[{name}]"),
936                             cx,
937                         ),
938                         _ => {
939                             primitive_link(
940                                 f,
941                                 PrimitiveType::Slice,
942                                 &format!("{}{}{}[", amp, lt, m),
943                                 cx,
944                             )?;
945                             if f.alternate() {
946                                 write!(f, "{:#}", bt.print(cx))?;
947                             } else {
948                                 write!(f, "{}", bt.print(cx))?;
949                             }
950                             primitive_link(f, PrimitiveType::Slice, "]", cx)
951                         }
952                     }
953                 }
954                 clean::DynTrait(ref bounds, ref trait_lt)
955                     if bounds.len() > 1 || trait_lt.is_some() =>
956                 {
957                     write!(f, "{}{}{}(", amp, lt, m)?;
958                     fmt_type(ty, f, use_absolute, cx)?;
959                     write!(f, ")")
960                 }
961                 clean::Generic(..) => {
962                     primitive_link(
963                         f,
964                         PrimitiveType::Reference,
965                         &format!("{}{}{}", amp, lt, m),
966                         cx,
967                     )?;
968                     fmt_type(ty, f, use_absolute, cx)
969                 }
970                 _ => {
971                     write!(f, "{}{}{}", amp, lt, m)?;
972                     fmt_type(ty, f, use_absolute, cx)
973                 }
974             }
975         }
976         clean::ImplTrait(ref bounds) => {
977             if f.alternate() {
978                 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
979             } else {
980                 write!(f, "impl {}", print_generic_bounds(bounds, cx))
981             }
982         }
983         clean::QPath { ref assoc, ref self_type, ref trait_, should_show_cast } => {
984             if f.alternate() {
985                 if should_show_cast {
986                     write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
987                 } else {
988                     write!(f, "{:#}::", self_type.print(cx))?
989                 }
990             } else {
991                 if should_show_cast {
992                     write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
993                 } else {
994                     write!(f, "{}::", self_type.print(cx))?
995                 }
996             };
997             // It's pretty unsightly to look at `<A as B>::C` in output, and
998             // we've got hyperlinking on our side, so try to avoid longer
999             // notation as much as possible by making `C` a hyperlink to trait
1000             // `B` to disambiguate.
1001             //
1002             // FIXME: this is still a lossy conversion and there should probably
1003             //        be a better way of representing this in general? Most of
1004             //        the ugliness comes from inlining across crates where
1005             //        everything comes in as a fully resolved QPath (hard to
1006             //        look at).
1007             match href(trait_.def_id(), cx) {
1008                 Ok((ref url, _, ref path)) if !f.alternate() => {
1009                     write!(
1010                         f,
1011                         "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1012                                     title=\"type {path}::{name}\">{name}</a>{args}",
1013                         url = url,
1014                         shortty = ItemType::AssocType,
1015                         name = assoc.name,
1016                         path = join_with_double_colon(path),
1017                         args = assoc.args.print(cx),
1018                     )?;
1019                 }
1020                 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1021             }
1022             Ok(())
1023         }
1024     }
1025 }
1026
1027 impl clean::Type {
1028     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1029         &'a self,
1030         cx: &'a Context<'tcx>,
1031     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1032         display_fn(move |f| fmt_type(self, f, false, cx))
1033     }
1034 }
1035
1036 impl clean::Path {
1037     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1038         &'a self,
1039         cx: &'a Context<'tcx>,
1040     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1041         display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1042     }
1043 }
1044
1045 impl clean::Impl {
1046     pub(crate) fn print<'a, 'tcx: 'a>(
1047         &'a self,
1048         use_absolute: bool,
1049         cx: &'a Context<'tcx>,
1050     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1051         display_fn(move |f| {
1052             if f.alternate() {
1053                 write!(f, "impl{:#} ", self.generics.print(cx))?;
1054             } else {
1055                 write!(f, "impl{} ", self.generics.print(cx))?;
1056             }
1057
1058             if let Some(ref ty) = self.trait_ {
1059                 match self.polarity {
1060                     ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1061                     ty::ImplPolarity::Negative => write!(f, "!")?,
1062                 }
1063                 fmt::Display::fmt(&ty.print(cx), f)?;
1064                 write!(f, " for ")?;
1065             }
1066
1067             if let Some(ty) = self.kind.as_blanket_ty() {
1068                 fmt_type(ty, f, use_absolute, cx)?;
1069             } else {
1070                 fmt_type(&self.for_, f, use_absolute, cx)?;
1071             }
1072
1073             fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1074             Ok(())
1075         })
1076     }
1077 }
1078
1079 impl clean::Arguments {
1080     pub(crate) fn print<'a, 'tcx: 'a>(
1081         &'a self,
1082         cx: &'a Context<'tcx>,
1083     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1084         display_fn(move |f| {
1085             for (i, input) in self.values.iter().enumerate() {
1086                 if !input.name.is_empty() {
1087                     write!(f, "{}: ", input.name)?;
1088                 }
1089                 if f.alternate() {
1090                     write!(f, "{:#}", input.type_.print(cx))?;
1091                 } else {
1092                     write!(f, "{}", input.type_.print(cx))?;
1093                 }
1094                 if i + 1 < self.values.len() {
1095                     write!(f, ", ")?;
1096                 }
1097             }
1098             Ok(())
1099         })
1100     }
1101 }
1102
1103 impl clean::FnRetTy {
1104     pub(crate) fn print<'a, 'tcx: 'a>(
1105         &'a self,
1106         cx: &'a Context<'tcx>,
1107     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1108         display_fn(move |f| match self {
1109             clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1110             clean::Return(ty) if f.alternate() => {
1111                 write!(f, " -> {:#}", ty.print(cx))
1112             }
1113             clean::Return(ty) => write!(f, " -&gt; {}", ty.print(cx)),
1114             clean::DefaultReturn => Ok(()),
1115         })
1116     }
1117 }
1118
1119 impl clean::BareFunctionDecl {
1120     fn print_hrtb_with_space<'a, 'tcx: 'a>(
1121         &'a self,
1122         cx: &'a Context<'tcx>,
1123     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1124         display_fn(move |f| {
1125             if !self.generic_params.is_empty() {
1126                 write!(
1127                     f,
1128                     "for&lt;{}&gt; ",
1129                     comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1130                 )
1131             } else {
1132                 Ok(())
1133             }
1134         })
1135     }
1136 }
1137
1138 impl clean::FnDecl {
1139     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1140         &'a self,
1141         cx: &'a Context<'tcx>,
1142     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1143         display_fn(move |f| {
1144             let ellipsis = if self.c_variadic { ", ..." } else { "" };
1145             if f.alternate() {
1146                 write!(
1147                     f,
1148                     "({args:#}{ellipsis}){arrow:#}",
1149                     args = self.inputs.print(cx),
1150                     ellipsis = ellipsis,
1151                     arrow = self.output.print(cx)
1152                 )
1153             } else {
1154                 write!(
1155                     f,
1156                     "({args}{ellipsis}){arrow}",
1157                     args = self.inputs.print(cx),
1158                     ellipsis = ellipsis,
1159                     arrow = self.output.print(cx)
1160                 )
1161             }
1162         })
1163     }
1164
1165     /// * `header_len`: The length of the function header and name. In other words, the number of
1166     ///   characters in the function declaration up to but not including the parentheses.
1167     ///   <br>Used to determine line-wrapping.
1168     /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1169     ///   necessary.
1170     /// * `asyncness`: Whether the function is async or not.
1171     pub(crate) fn full_print<'a, 'tcx: 'a>(
1172         &'a self,
1173         header_len: usize,
1174         indent: usize,
1175         asyncness: hir::IsAsync,
1176         cx: &'a Context<'tcx>,
1177     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1178         display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1179     }
1180
1181     fn inner_full_print(
1182         &self,
1183         header_len: usize,
1184         indent: usize,
1185         asyncness: hir::IsAsync,
1186         f: &mut fmt::Formatter<'_>,
1187         cx: &Context<'_>,
1188     ) -> fmt::Result {
1189         let amp = if f.alternate() { "&" } else { "&amp;" };
1190         let mut args = Buffer::html();
1191         let mut args_plain = Buffer::new();
1192         for (i, input) in self.inputs.values.iter().enumerate() {
1193             if i == 0 {
1194                 args.push_str("<br>");
1195             }
1196
1197             if let Some(selfty) = input.to_self() {
1198                 match selfty {
1199                     clean::SelfValue => {
1200                         args.push_str("self");
1201                         args_plain.push_str("self");
1202                     }
1203                     clean::SelfBorrowed(Some(ref lt), mtbl) => {
1204                         write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1205                         write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1206                     }
1207                     clean::SelfBorrowed(None, mtbl) => {
1208                         write!(args, "{}{}self", amp, mtbl.print_with_space());
1209                         write!(args_plain, "&{}self", mtbl.print_with_space());
1210                     }
1211                     clean::SelfExplicit(ref typ) => {
1212                         if f.alternate() {
1213                             write!(args, "self: {:#}", typ.print(cx));
1214                         } else {
1215                             write!(args, "self: {}", typ.print(cx));
1216                         }
1217                         write!(args_plain, "self: {:#}", typ.print(cx));
1218                     }
1219                 }
1220             } else {
1221                 if i > 0 {
1222                     args.push_str(" <br>");
1223                     args_plain.push_str(" ");
1224                 }
1225                 if input.is_const {
1226                     args.push_str("const ");
1227                     args_plain.push_str("const ");
1228                 }
1229                 if !input.name.is_empty() {
1230                     write!(args, "{}: ", input.name);
1231                     write!(args_plain, "{}: ", input.name);
1232                 }
1233
1234                 if f.alternate() {
1235                     write!(args, "{:#}", input.type_.print(cx));
1236                 } else {
1237                     write!(args, "{}", input.type_.print(cx));
1238                 }
1239                 write!(args_plain, "{:#}", input.type_.print(cx));
1240             }
1241             if i + 1 < self.inputs.values.len() {
1242                 args.push_str(",");
1243                 args_plain.push_str(",");
1244             }
1245         }
1246
1247         let mut args_plain = format!("({})", args_plain.into_inner());
1248         let mut args = args.into_inner();
1249
1250         if self.c_variadic {
1251             args.push_str(",<br> ...");
1252             args_plain.push_str(", ...");
1253         }
1254
1255         let arrow_plain;
1256         let arrow = if let hir::IsAsync::Async = asyncness {
1257             let output = self.sugared_async_return_type();
1258             arrow_plain = format!("{:#}", output.print(cx));
1259             if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1260         } else {
1261             arrow_plain = format!("{:#}", self.output.print(cx));
1262             if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1263         };
1264
1265         let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1266         let output = if declaration_len > 80 {
1267             let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1268             let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1269             format!(
1270                 "({args}{close}){arrow}",
1271                 args = args.replace("<br>", &full_pad),
1272                 close = close_pad,
1273                 arrow = arrow
1274             )
1275         } else {
1276             format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1277         };
1278
1279         if f.alternate() {
1280             write!(f, "{}", output.replace("<br>", "\n"))
1281         } else {
1282             write!(f, "{}", output)
1283         }
1284     }
1285 }
1286
1287 impl clean::Visibility {
1288     pub(crate) fn print_with_space<'a, 'tcx: 'a>(
1289         self,
1290         item_did: ItemId,
1291         cx: &'a Context<'tcx>,
1292     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1293         use std::fmt::Write as _;
1294
1295         let to_print: Cow<'static, str> = match self {
1296             clean::Public => "pub ".into(),
1297             clean::Inherited => "".into(),
1298             clean::Visibility::Restricted(vis_did) => {
1299                 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1300                 //                 However, rustdoc currently never displays a module's
1301                 //                 visibility, so it shouldn't matter.
1302                 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1303
1304                 if vis_did.is_crate_root() {
1305                     "pub(crate) ".into()
1306                 } else if parent_module == Some(vis_did) {
1307                     // `pub(in foo)` where `foo` is the parent module
1308                     // is the same as no visibility modifier
1309                     "".into()
1310                 } else if parent_module
1311                     .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1312                     == Some(vis_did)
1313                 {
1314                     "pub(super) ".into()
1315                 } else {
1316                     let path = cx.tcx().def_path(vis_did);
1317                     debug!("path={:?}", path);
1318                     // modified from `resolved_path()` to work with `DefPathData`
1319                     let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1320                     let anchor = anchor(vis_did, last_name, cx).to_string();
1321
1322                     let mut s = "pub(in ".to_owned();
1323                     for seg in &path.data[..path.data.len() - 1] {
1324                         let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1325                     }
1326                     let _ = write!(s, "{}) ", anchor);
1327                     s.into()
1328                 }
1329             }
1330         };
1331         display_fn(move |f| write!(f, "{}", to_print))
1332     }
1333
1334     /// This function is the same as print_with_space, except that it renders no links.
1335     /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1336     /// any HTML in it.
1337     pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
1338         self,
1339         tcx: TyCtxt<'tcx>,
1340         item_did: DefId,
1341     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1342         let to_print = match self {
1343             clean::Public => "pub ".to_owned(),
1344             clean::Inherited => String::new(),
1345             clean::Visibility::Restricted(vis_did) => {
1346                 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1347                 //                 However, rustdoc currently never displays a module's
1348                 //                 visibility, so it shouldn't matter.
1349                 let parent_module = find_nearest_parent_module(tcx, item_did);
1350
1351                 if vis_did.is_crate_root() {
1352                     "pub(crate) ".to_owned()
1353                 } else if parent_module == Some(vis_did) {
1354                     // `pub(in foo)` where `foo` is the parent module
1355                     // is the same as no visibility modifier
1356                     String::new()
1357                 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1358                     == Some(vis_did)
1359                 {
1360                     "pub(super) ".to_owned()
1361                 } else {
1362                     format!("pub(in {}) ", tcx.def_path_str(vis_did))
1363                 }
1364             }
1365         };
1366         display_fn(move |f| f.write_str(&to_print))
1367     }
1368 }
1369
1370 pub(crate) trait PrintWithSpace {
1371     fn print_with_space(&self) -> &str;
1372 }
1373
1374 impl PrintWithSpace for hir::Unsafety {
1375     fn print_with_space(&self) -> &str {
1376         match self {
1377             hir::Unsafety::Unsafe => "unsafe ",
1378             hir::Unsafety::Normal => "",
1379         }
1380     }
1381 }
1382
1383 impl PrintWithSpace for hir::IsAsync {
1384     fn print_with_space(&self) -> &str {
1385         match self {
1386             hir::IsAsync::Async => "async ",
1387             hir::IsAsync::NotAsync => "",
1388         }
1389     }
1390 }
1391
1392 impl PrintWithSpace for hir::Mutability {
1393     fn print_with_space(&self) -> &str {
1394         match self {
1395             hir::Mutability::Not => "",
1396             hir::Mutability::Mut => "mut ",
1397         }
1398     }
1399 }
1400
1401 pub(crate) fn print_constness_with_space(
1402     c: &hir::Constness,
1403     s: Option<ConstStability>,
1404 ) -> &'static str {
1405     match (c, s) {
1406         // const stable or when feature(staged_api) is not set
1407         (
1408             hir::Constness::Const,
1409             Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1410         )
1411         | (hir::Constness::Const, None) => "const ",
1412         // const unstable or not const
1413         _ => "",
1414     }
1415 }
1416
1417 impl clean::Import {
1418     pub(crate) fn print<'a, 'tcx: 'a>(
1419         &'a self,
1420         cx: &'a Context<'tcx>,
1421     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1422         display_fn(move |f| match self.kind {
1423             clean::ImportKind::Simple(name) => {
1424                 if name == self.source.path.last() {
1425                     write!(f, "use {};", self.source.print(cx))
1426                 } else {
1427                     write!(f, "use {} as {};", self.source.print(cx), name)
1428                 }
1429             }
1430             clean::ImportKind::Glob => {
1431                 if self.source.path.segments.is_empty() {
1432                     write!(f, "use *;")
1433                 } else {
1434                     write!(f, "use {}::*;", self.source.print(cx))
1435                 }
1436             }
1437         })
1438     }
1439 }
1440
1441 impl clean::ImportSource {
1442     pub(crate) fn print<'a, 'tcx: 'a>(
1443         &'a self,
1444         cx: &'a Context<'tcx>,
1445     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1446         display_fn(move |f| match self.did {
1447             Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1448             _ => {
1449                 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1450                     write!(f, "{}::", seg.name)?;
1451                 }
1452                 let name = self.path.last();
1453                 if let hir::def::Res::PrimTy(p) = self.path.res {
1454                     primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1455                 } else {
1456                     write!(f, "{}", name)?;
1457                 }
1458                 Ok(())
1459             }
1460         })
1461     }
1462 }
1463
1464 impl clean::TypeBinding {
1465     pub(crate) fn print<'a, 'tcx: 'a>(
1466         &'a self,
1467         cx: &'a Context<'tcx>,
1468     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1469         display_fn(move |f| {
1470             f.write_str(self.assoc.name.as_str())?;
1471             if f.alternate() {
1472                 write!(f, "{:#}", self.assoc.args.print(cx))?;
1473             } else {
1474                 write!(f, "{}", self.assoc.args.print(cx))?;
1475             }
1476             match self.kind {
1477                 clean::TypeBindingKind::Equality { ref term } => {
1478                     if f.alternate() {
1479                         write!(f, " = {:#}", term.print(cx))?;
1480                     } else {
1481                         write!(f, " = {}", term.print(cx))?;
1482                     }
1483                 }
1484                 clean::TypeBindingKind::Constraint { ref bounds } => {
1485                     if !bounds.is_empty() {
1486                         if f.alternate() {
1487                             write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1488                         } else {
1489                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
1490                         }
1491                     }
1492                 }
1493             }
1494             Ok(())
1495         })
1496     }
1497 }
1498
1499 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1500     display_fn(move |f| {
1501         let quot = if f.alternate() { "\"" } else { "&quot;" };
1502         match abi {
1503             Abi::Rust => Ok(()),
1504             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1505         }
1506     })
1507 }
1508
1509 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1510     if v { "default " } else { "" }
1511 }
1512
1513 impl clean::GenericArg {
1514     pub(crate) fn print<'a, 'tcx: 'a>(
1515         &'a self,
1516         cx: &'a Context<'tcx>,
1517     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1518         display_fn(move |f| match self {
1519             clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1520             clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1521             clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1522             clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1523         })
1524     }
1525 }
1526
1527 impl clean::types::Term {
1528     pub(crate) fn print<'a, 'tcx: 'a>(
1529         &'a self,
1530         cx: &'a Context<'tcx>,
1531     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1532         match self {
1533             clean::types::Term::Type(ty) => ty.print(cx),
1534             _ => todo!(),
1535         }
1536     }
1537 }
1538
1539 pub(crate) fn display_fn(
1540     f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1541 ) -> impl fmt::Display {
1542     struct WithFormatter<F>(Cell<Option<F>>);
1543
1544     impl<F> fmt::Display for WithFormatter<F>
1545     where
1546         F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1547     {
1548         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1549             (self.0.take()).unwrap()(f)
1550         }
1551     }
1552
1553     WithFormatter(Cell::new(Some(f)))
1554 }