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