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