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