]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Rollup merge of #97616 - TaKO8Ki:remove-unnecessary-option, r=Dylan-DPC
[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) => {
885             primitive_link(f, PrimitiveType::Slice, "[", cx)?;
886             fmt::Display::fmt(&t.print(cx), f)?;
887             primitive_link(f, PrimitiveType::Slice, "]", cx)
888         }
889         clean::Array(ref t, ref n) => {
890             primitive_link(f, PrimitiveType::Array, "[", cx)?;
891             fmt::Display::fmt(&t.print(cx), f)?;
892             if f.alternate() {
893                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
894             } else {
895                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
896             }
897         }
898         clean::RawPointer(m, ref t) => {
899             let m = match m {
900                 hir::Mutability::Mut => "mut",
901                 hir::Mutability::Not => "const",
902             };
903
904             if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
905                 let text = if f.alternate() {
906                     format!("*{} {:#}", m, t.print(cx))
907                 } else {
908                     format!("*{} {}", m, t.print(cx))
909                 };
910                 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
911             } else {
912                 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
913                 fmt::Display::fmt(&t.print(cx), f)
914             }
915         }
916         clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
917             let lt = match l {
918                 Some(l) => format!("{} ", l.print()),
919                 _ => String::new(),
920             };
921             let m = mutability.print_with_space();
922             let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
923             match **ty {
924                 clean::Slice(ref bt) => {
925                     // `BorrowedRef{ ... Slice(T) }` is `&[T]`
926                     match **bt {
927                         clean::Generic(_) => {
928                             if f.alternate() {
929                                 primitive_link(
930                                     f,
931                                     PrimitiveType::Slice,
932                                     &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
933                                     cx,
934                                 )
935                             } else {
936                                 primitive_link(
937                                     f,
938                                     PrimitiveType::Slice,
939                                     &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
940                                     cx,
941                                 )
942                             }
943                         }
944                         _ => {
945                             primitive_link(
946                                 f,
947                                 PrimitiveType::Slice,
948                                 &format!("{}{}{}[", amp, lt, m),
949                                 cx,
950                             )?;
951                             if f.alternate() {
952                                 write!(f, "{:#}", bt.print(cx))?;
953                             } else {
954                                 write!(f, "{}", bt.print(cx))?;
955                             }
956                             primitive_link(f, PrimitiveType::Slice, "]", cx)
957                         }
958                     }
959                 }
960                 clean::DynTrait(ref bounds, ref trait_lt)
961                     if bounds.len() > 1 || trait_lt.is_some() =>
962                 {
963                     write!(f, "{}{}{}(", amp, lt, m)?;
964                     fmt_type(ty, f, use_absolute, cx)?;
965                     write!(f, ")")
966                 }
967                 clean::Generic(..) => {
968                     primitive_link(
969                         f,
970                         PrimitiveType::Reference,
971                         &format!("{}{}{}", amp, lt, m),
972                         cx,
973                     )?;
974                     fmt_type(ty, f, use_absolute, cx)
975                 }
976                 _ => {
977                     write!(f, "{}{}{}", amp, lt, m)?;
978                     fmt_type(ty, f, use_absolute, cx)
979                 }
980             }
981         }
982         clean::ImplTrait(ref bounds) => {
983             if f.alternate() {
984                 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
985             } else {
986                 write!(f, "impl {}", print_generic_bounds(bounds, cx))
987             }
988         }
989         clean::QPath { ref assoc, ref self_type, ref trait_, should_show_cast } => {
990             if f.alternate() {
991                 if should_show_cast {
992                     write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
993                 } else {
994                     write!(f, "{:#}::", self_type.print(cx))?
995                 }
996             } else {
997                 if should_show_cast {
998                     write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
999                 } else {
1000                     write!(f, "{}::", self_type.print(cx))?
1001                 }
1002             };
1003             // It's pretty unsightly to look at `<A as B>::C` in output, and
1004             // we've got hyperlinking on our side, so try to avoid longer
1005             // notation as much as possible by making `C` a hyperlink to trait
1006             // `B` to disambiguate.
1007             //
1008             // FIXME: this is still a lossy conversion and there should probably
1009             //        be a better way of representing this in general? Most of
1010             //        the ugliness comes from inlining across crates where
1011             //        everything comes in as a fully resolved QPath (hard to
1012             //        look at).
1013             match href(trait_.def_id(), cx) {
1014                 Ok((ref url, _, ref path)) if !f.alternate() => {
1015                     write!(
1016                         f,
1017                         "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1018                                     title=\"type {path}::{name}\">{name}</a>{args}",
1019                         url = url,
1020                         shortty = ItemType::AssocType,
1021                         name = assoc.name,
1022                         path = join_with_double_colon(path),
1023                         args = assoc.args.print(cx),
1024                     )?;
1025                 }
1026                 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1027             }
1028             Ok(())
1029         }
1030     }
1031 }
1032
1033 impl clean::Type {
1034     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1035         &'a self,
1036         cx: &'a Context<'tcx>,
1037     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1038         display_fn(move |f| fmt_type(self, f, false, cx))
1039     }
1040 }
1041
1042 impl clean::Path {
1043     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1044         &'a self,
1045         cx: &'a Context<'tcx>,
1046     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1047         display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1048     }
1049 }
1050
1051 impl clean::Impl {
1052     pub(crate) fn print<'a, 'tcx: 'a>(
1053         &'a self,
1054         use_absolute: bool,
1055         cx: &'a Context<'tcx>,
1056     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1057         display_fn(move |f| {
1058             if f.alternate() {
1059                 write!(f, "impl{:#} ", self.generics.print(cx))?;
1060             } else {
1061                 write!(f, "impl{} ", self.generics.print(cx))?;
1062             }
1063
1064             if let Some(ref ty) = self.trait_ {
1065                 match self.polarity {
1066                     ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1067                     ty::ImplPolarity::Negative => write!(f, "!")?,
1068                 }
1069                 fmt::Display::fmt(&ty.print(cx), f)?;
1070                 write!(f, " for ")?;
1071             }
1072
1073             if let Some(ty) = self.kind.as_blanket_ty() {
1074                 fmt_type(ty, f, use_absolute, cx)?;
1075             } else {
1076                 fmt_type(&self.for_, f, use_absolute, cx)?;
1077             }
1078
1079             fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1080             Ok(())
1081         })
1082     }
1083 }
1084
1085 impl clean::Arguments {
1086     pub(crate) fn print<'a, 'tcx: 'a>(
1087         &'a self,
1088         cx: &'a Context<'tcx>,
1089     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1090         display_fn(move |f| {
1091             for (i, input) in self.values.iter().enumerate() {
1092                 if !input.name.is_empty() {
1093                     write!(f, "{}: ", input.name)?;
1094                 }
1095                 if f.alternate() {
1096                     write!(f, "{:#}", input.type_.print(cx))?;
1097                 } else {
1098                     write!(f, "{}", input.type_.print(cx))?;
1099                 }
1100                 if i + 1 < self.values.len() {
1101                     write!(f, ", ")?;
1102                 }
1103             }
1104             Ok(())
1105         })
1106     }
1107 }
1108
1109 impl clean::FnRetTy {
1110     pub(crate) fn print<'a, 'tcx: 'a>(
1111         &'a self,
1112         cx: &'a Context<'tcx>,
1113     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1114         display_fn(move |f| match self {
1115             clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1116             clean::Return(ty) if f.alternate() => {
1117                 write!(f, " -> {:#}", ty.print(cx))
1118             }
1119             clean::Return(ty) => write!(f, " -&gt; {}", ty.print(cx)),
1120             clean::DefaultReturn => Ok(()),
1121         })
1122     }
1123 }
1124
1125 impl clean::BareFunctionDecl {
1126     fn print_hrtb_with_space<'a, 'tcx: 'a>(
1127         &'a self,
1128         cx: &'a Context<'tcx>,
1129     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1130         display_fn(move |f| {
1131             if !self.generic_params.is_empty() {
1132                 write!(
1133                     f,
1134                     "for&lt;{}&gt; ",
1135                     comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1136                 )
1137             } else {
1138                 Ok(())
1139             }
1140         })
1141     }
1142 }
1143
1144 impl clean::FnDecl {
1145     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1146         &'a self,
1147         cx: &'a Context<'tcx>,
1148     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1149         display_fn(move |f| {
1150             let ellipsis = if self.c_variadic { ", ..." } else { "" };
1151             if f.alternate() {
1152                 write!(
1153                     f,
1154                     "({args:#}{ellipsis}){arrow:#}",
1155                     args = self.inputs.print(cx),
1156                     ellipsis = ellipsis,
1157                     arrow = self.output.print(cx)
1158                 )
1159             } else {
1160                 write!(
1161                     f,
1162                     "({args}{ellipsis}){arrow}",
1163                     args = self.inputs.print(cx),
1164                     ellipsis = ellipsis,
1165                     arrow = self.output.print(cx)
1166                 )
1167             }
1168         })
1169     }
1170
1171     /// * `header_len`: The length of the function header and name. In other words, the number of
1172     ///   characters in the function declaration up to but not including the parentheses.
1173     ///   <br>Used to determine line-wrapping.
1174     /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1175     ///   necessary.
1176     /// * `asyncness`: Whether the function is async or not.
1177     pub(crate) fn full_print<'a, 'tcx: 'a>(
1178         &'a self,
1179         header_len: usize,
1180         indent: usize,
1181         asyncness: hir::IsAsync,
1182         cx: &'a Context<'tcx>,
1183     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1184         display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1185     }
1186
1187     fn inner_full_print(
1188         &self,
1189         header_len: usize,
1190         indent: usize,
1191         asyncness: hir::IsAsync,
1192         f: &mut fmt::Formatter<'_>,
1193         cx: &Context<'_>,
1194     ) -> fmt::Result {
1195         let amp = if f.alternate() { "&" } else { "&amp;" };
1196         let mut args = Buffer::html();
1197         let mut args_plain = Buffer::new();
1198         for (i, input) in self.inputs.values.iter().enumerate() {
1199             if i == 0 {
1200                 args.push_str("<br>");
1201             }
1202
1203             if let Some(selfty) = input.to_self() {
1204                 match selfty {
1205                     clean::SelfValue => {
1206                         args.push_str("self");
1207                         args_plain.push_str("self");
1208                     }
1209                     clean::SelfBorrowed(Some(ref lt), mtbl) => {
1210                         write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1211                         write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1212                     }
1213                     clean::SelfBorrowed(None, mtbl) => {
1214                         write!(args, "{}{}self", amp, mtbl.print_with_space());
1215                         write!(args_plain, "&{}self", mtbl.print_with_space());
1216                     }
1217                     clean::SelfExplicit(ref typ) => {
1218                         if f.alternate() {
1219                             write!(args, "self: {:#}", typ.print(cx));
1220                         } else {
1221                             write!(args, "self: {}", typ.print(cx));
1222                         }
1223                         write!(args_plain, "self: {:#}", typ.print(cx));
1224                     }
1225                 }
1226             } else {
1227                 if i > 0 {
1228                     args.push_str(" <br>");
1229                     args_plain.push_str(" ");
1230                 }
1231                 if input.is_const {
1232                     args.push_str("const ");
1233                     args_plain.push_str("const ");
1234                 }
1235                 if !input.name.is_empty() {
1236                     write!(args, "{}: ", input.name);
1237                     write!(args_plain, "{}: ", input.name);
1238                 }
1239
1240                 if f.alternate() {
1241                     write!(args, "{:#}", input.type_.print(cx));
1242                 } else {
1243                     write!(args, "{}", input.type_.print(cx));
1244                 }
1245                 write!(args_plain, "{:#}", input.type_.print(cx));
1246             }
1247             if i + 1 < self.inputs.values.len() {
1248                 args.push_str(",");
1249                 args_plain.push_str(",");
1250             }
1251         }
1252
1253         let mut args_plain = format!("({})", args_plain.into_inner());
1254         let mut args = args.into_inner();
1255
1256         if self.c_variadic {
1257             args.push_str(",<br> ...");
1258             args_plain.push_str(", ...");
1259         }
1260
1261         let arrow_plain;
1262         let arrow = if let hir::IsAsync::Async = asyncness {
1263             let output = self.sugared_async_return_type();
1264             arrow_plain = format!("{:#}", output.print(cx));
1265             if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1266         } else {
1267             arrow_plain = format!("{:#}", self.output.print(cx));
1268             if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1269         };
1270
1271         let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1272         let output = if declaration_len > 80 {
1273             let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1274             let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1275             format!(
1276                 "({args}{close}){arrow}",
1277                 args = args.replace("<br>", &full_pad),
1278                 close = close_pad,
1279                 arrow = arrow
1280             )
1281         } else {
1282             format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1283         };
1284
1285         if f.alternate() {
1286             write!(f, "{}", output.replace("<br>", "\n"))
1287         } else {
1288             write!(f, "{}", output)
1289         }
1290     }
1291 }
1292
1293 impl clean::Visibility {
1294     pub(crate) fn print_with_space<'a, 'tcx: 'a>(
1295         self,
1296         item_did: ItemId,
1297         cx: &'a Context<'tcx>,
1298     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1299         use std::fmt::Write as _;
1300
1301         let to_print: Cow<'static, str> = match self {
1302             clean::Public => "pub ".into(),
1303             clean::Inherited => "".into(),
1304             clean::Visibility::Restricted(vis_did) => {
1305                 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1306                 //                 However, rustdoc currently never displays a module's
1307                 //                 visibility, so it shouldn't matter.
1308                 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1309
1310                 if vis_did.is_crate_root() {
1311                     "pub(crate) ".into()
1312                 } else if parent_module == Some(vis_did) {
1313                     // `pub(in foo)` where `foo` is the parent module
1314                     // is the same as no visibility modifier
1315                     "".into()
1316                 } else if parent_module
1317                     .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1318                     == Some(vis_did)
1319                 {
1320                     "pub(super) ".into()
1321                 } else {
1322                     let path = cx.tcx().def_path(vis_did);
1323                     debug!("path={:?}", path);
1324                     // modified from `resolved_path()` to work with `DefPathData`
1325                     let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1326                     let anchor = anchor(vis_did, last_name, cx).to_string();
1327
1328                     let mut s = "pub(in ".to_owned();
1329                     for seg in &path.data[..path.data.len() - 1] {
1330                         let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1331                     }
1332                     let _ = write!(s, "{}) ", anchor);
1333                     s.into()
1334                 }
1335             }
1336         };
1337         display_fn(move |f| write!(f, "{}", to_print))
1338     }
1339
1340     /// This function is the same as print_with_space, except that it renders no links.
1341     /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1342     /// any HTML in it.
1343     pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
1344         self,
1345         tcx: TyCtxt<'tcx>,
1346         item_did: DefId,
1347     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1348         let to_print = match self {
1349             clean::Public => "pub ".to_owned(),
1350             clean::Inherited => String::new(),
1351             clean::Visibility::Restricted(vis_did) => {
1352                 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1353                 //                 However, rustdoc currently never displays a module's
1354                 //                 visibility, so it shouldn't matter.
1355                 let parent_module = find_nearest_parent_module(tcx, item_did);
1356
1357                 if vis_did.is_crate_root() {
1358                     "pub(crate) ".to_owned()
1359                 } else if parent_module == Some(vis_did) {
1360                     // `pub(in foo)` where `foo` is the parent module
1361                     // is the same as no visibility modifier
1362                     String::new()
1363                 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1364                     == Some(vis_did)
1365                 {
1366                     "pub(super) ".to_owned()
1367                 } else {
1368                     format!("pub(in {}) ", tcx.def_path_str(vis_did))
1369                 }
1370             }
1371         };
1372         display_fn(move |f| f.write_str(&to_print))
1373     }
1374 }
1375
1376 pub(crate) trait PrintWithSpace {
1377     fn print_with_space(&self) -> &str;
1378 }
1379
1380 impl PrintWithSpace for hir::Unsafety {
1381     fn print_with_space(&self) -> &str {
1382         match self {
1383             hir::Unsafety::Unsafe => "unsafe ",
1384             hir::Unsafety::Normal => "",
1385         }
1386     }
1387 }
1388
1389 impl PrintWithSpace for hir::IsAsync {
1390     fn print_with_space(&self) -> &str {
1391         match self {
1392             hir::IsAsync::Async => "async ",
1393             hir::IsAsync::NotAsync => "",
1394         }
1395     }
1396 }
1397
1398 impl PrintWithSpace for hir::Mutability {
1399     fn print_with_space(&self) -> &str {
1400         match self {
1401             hir::Mutability::Not => "",
1402             hir::Mutability::Mut => "mut ",
1403         }
1404     }
1405 }
1406
1407 pub(crate) fn print_constness_with_space(
1408     c: &hir::Constness,
1409     s: Option<ConstStability>,
1410 ) -> &'static str {
1411     match (c, s) {
1412         // const stable or when feature(staged_api) is not set
1413         (
1414             hir::Constness::Const,
1415             Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1416         )
1417         | (hir::Constness::Const, None) => "const ",
1418         // const unstable or not const
1419         _ => "",
1420     }
1421 }
1422
1423 impl clean::Import {
1424     pub(crate) fn print<'a, 'tcx: 'a>(
1425         &'a self,
1426         cx: &'a Context<'tcx>,
1427     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1428         display_fn(move |f| match self.kind {
1429             clean::ImportKind::Simple(name) => {
1430                 if name == self.source.path.last() {
1431                     write!(f, "use {};", self.source.print(cx))
1432                 } else {
1433                     write!(f, "use {} as {};", self.source.print(cx), name)
1434                 }
1435             }
1436             clean::ImportKind::Glob => {
1437                 if self.source.path.segments.is_empty() {
1438                     write!(f, "use *;")
1439                 } else {
1440                     write!(f, "use {}::*;", self.source.print(cx))
1441                 }
1442             }
1443         })
1444     }
1445 }
1446
1447 impl clean::ImportSource {
1448     pub(crate) fn print<'a, 'tcx: 'a>(
1449         &'a self,
1450         cx: &'a Context<'tcx>,
1451     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1452         display_fn(move |f| match self.did {
1453             Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1454             _ => {
1455                 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1456                     write!(f, "{}::", seg.name)?;
1457                 }
1458                 let name = self.path.last();
1459                 if let hir::def::Res::PrimTy(p) = self.path.res {
1460                     primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1461                 } else {
1462                     write!(f, "{}", name)?;
1463                 }
1464                 Ok(())
1465             }
1466         })
1467     }
1468 }
1469
1470 impl clean::TypeBinding {
1471     pub(crate) fn print<'a, 'tcx: 'a>(
1472         &'a self,
1473         cx: &'a Context<'tcx>,
1474     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1475         display_fn(move |f| {
1476             f.write_str(self.assoc.name.as_str())?;
1477             if f.alternate() {
1478                 write!(f, "{:#}", self.assoc.args.print(cx))?;
1479             } else {
1480                 write!(f, "{}", self.assoc.args.print(cx))?;
1481             }
1482             match self.kind {
1483                 clean::TypeBindingKind::Equality { ref term } => {
1484                     if f.alternate() {
1485                         write!(f, " = {:#}", term.print(cx))?;
1486                     } else {
1487                         write!(f, " = {}", term.print(cx))?;
1488                     }
1489                 }
1490                 clean::TypeBindingKind::Constraint { ref bounds } => {
1491                     if !bounds.is_empty() {
1492                         if f.alternate() {
1493                             write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1494                         } else {
1495                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
1496                         }
1497                     }
1498                 }
1499             }
1500             Ok(())
1501         })
1502     }
1503 }
1504
1505 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1506     display_fn(move |f| {
1507         let quot = if f.alternate() { "\"" } else { "&quot;" };
1508         match abi {
1509             Abi::Rust => Ok(()),
1510             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1511         }
1512     })
1513 }
1514
1515 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1516     if v { "default " } else { "" }
1517 }
1518
1519 impl clean::GenericArg {
1520     pub(crate) fn print<'a, 'tcx: 'a>(
1521         &'a self,
1522         cx: &'a Context<'tcx>,
1523     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1524         display_fn(move |f| match self {
1525             clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1526             clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1527             clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1528             clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1529         })
1530     }
1531 }
1532
1533 impl clean::types::Term {
1534     pub(crate) fn print<'a, 'tcx: 'a>(
1535         &'a self,
1536         cx: &'a Context<'tcx>,
1537     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1538         match self {
1539             clean::types::Term::Type(ty) => ty.print(cx),
1540             _ => todo!(),
1541         }
1542     }
1543 }
1544
1545 pub(crate) fn display_fn(
1546     f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1547 ) -> impl fmt::Display {
1548     struct WithFormatter<F>(Cell<Option<F>>);
1549
1550     impl<F> fmt::Display for WithFormatter<F>
1551     where
1552         F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1553     {
1554         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1555             (self.0.take()).unwrap()(f)
1556         }
1557     }
1558
1559     WithFormatter(Cell::new(Some(f)))
1560 }