]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Rollup merge of #69814 - jonas-schievink:gen-ret-unw, r=Zoxc
[rust.git] / src / librustdoc / html / format.rs
1 //! HTML formatting module
2 //!
3 //! This module contains a large number of `fmt::Display` implementations for
4 //! various types in `rustdoc::clean`. These implementations all currently
5 //! assume that HTML output is desired, although it may be possible to redesign
6 //! them in the future to instead emit any format desired.
7
8 use std::borrow::Cow;
9 use std::cell::Cell;
10 use std::fmt;
11
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_hir as hir;
14 use rustc_hir::def_id::DefId;
15 use rustc_target::spec::abi::Abi;
16
17 use crate::clean::{self, PrimitiveType};
18 use crate::html::escape::Escape;
19 use crate::html::item_type::ItemType;
20 use crate::html::render::{self, cache, CURRENT_DEPTH};
21
22 pub trait Print {
23     fn print(self, buffer: &mut Buffer);
24 }
25
26 impl<F> Print for F
27 where
28     F: FnOnce(&mut Buffer),
29 {
30     fn print(self, buffer: &mut Buffer) {
31         (self)(buffer)
32     }
33 }
34
35 impl Print for String {
36     fn print(self, buffer: &mut Buffer) {
37         buffer.write_str(&self);
38     }
39 }
40
41 impl Print for &'_ str {
42     fn print(self, buffer: &mut Buffer) {
43         buffer.write_str(self);
44     }
45 }
46
47 #[derive(Debug, Clone)]
48 pub struct Buffer {
49     for_html: bool,
50     buffer: String,
51 }
52
53 impl Buffer {
54     crate fn empty_from(v: &Buffer) -> Buffer {
55         Buffer { for_html: v.for_html, buffer: String::new() }
56     }
57
58     crate fn html() -> Buffer {
59         Buffer { for_html: true, buffer: String::new() }
60     }
61
62     crate fn new() -> Buffer {
63         Buffer { for_html: false, buffer: String::new() }
64     }
65
66     crate fn into_inner(self) -> String {
67         self.buffer
68     }
69
70     // Intended for consumption by write! and writeln! (std::fmt) but without
71     // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
72     // import).
73     crate fn write_str(&mut self, s: &str) {
74         self.buffer.push_str(s);
75     }
76
77     // Intended for consumption by write! and writeln! (std::fmt) but without
78     // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
79     // import).
80     crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
81         use fmt::Write;
82         self.buffer.write_fmt(v).unwrap();
83     }
84
85     crate fn to_display<T: Print>(mut self, t: T) -> String {
86         t.print(&mut self);
87         self.into_inner()
88     }
89
90     crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
91         if self.for_html {
92             write!(self, "{}", t);
93         } else {
94             write!(self, "{:#}", t);
95         }
96     }
97
98     crate fn is_for_html(&self) -> bool {
99         self.for_html
100     }
101 }
102
103 /// Wrapper struct for properly emitting a function or method declaration.
104 pub struct Function<'a> {
105     /// The declaration to emit.
106     pub decl: &'a clean::FnDecl,
107     /// The length of the function header and name. In other words, the number of characters in the
108     /// function declaration up to but not including the parentheses.
109     ///
110     /// Used to determine line-wrapping.
111     pub header_len: usize,
112     /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
113     pub indent: usize,
114     /// Whether the function is async or not.
115     pub asyncness: hir::IsAsync,
116 }
117
118 /// Wrapper struct for emitting a where-clause from Generics.
119 pub struct WhereClause<'a> {
120     /// The Generics from which to emit a where-clause.
121     pub gens: &'a clean::Generics,
122     /// The number of spaces to indent each line with.
123     pub indent: usize,
124     /// Whether the where-clause needs to add a comma and newline after the last bound.
125     pub end_newline: bool,
126 }
127
128 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
129     display_fn(move |f| {
130         for (i, item) in items.enumerate() {
131             if i != 0 {
132                 write!(f, ", ")?;
133             }
134             fmt::Display::fmt(&item, f)?;
135         }
136         Ok(())
137     })
138 }
139
140 crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
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().to_string())).enumerate()
146         {
147             if i > 0 {
148                 f.write_str(" + ")?;
149             }
150             fmt::Display::fmt(&bound.print(), f)?;
151         }
152         Ok(())
153     })
154 }
155
156 impl clean::GenericParamDef {
157     crate fn print(&self) -> impl fmt::Display + '_ {
158         display_fn(move |f| match self.kind {
159             clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
160             clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
161                 f.write_str(&self.name)?;
162
163                 if !bounds.is_empty() {
164                     if f.alternate() {
165                         write!(f, ": {:#}", print_generic_bounds(bounds))?;
166                     } else {
167                         write!(f, ":&nbsp;{}", print_generic_bounds(bounds))?;
168                     }
169                 }
170
171                 if let Some(ref ty) = default {
172                     if f.alternate() {
173                         write!(f, " = {:#}", ty.print())?;
174                     } else {
175                         write!(f, "&nbsp;=&nbsp;{}", ty.print())?;
176                     }
177                 }
178
179                 Ok(())
180             }
181             clean::GenericParamDefKind::Const { ref ty, .. } => {
182                 f.write_str("const ")?;
183                 f.write_str(&self.name)?;
184
185                 if f.alternate() {
186                     write!(f, ": {:#}", ty.print())
187                 } else {
188                     write!(f, ":&nbsp;{}", ty.print())
189                 }
190             }
191         })
192     }
193 }
194
195 impl clean::Generics {
196     crate fn print(&self) -> impl fmt::Display + '_ {
197         display_fn(move |f| {
198             let real_params =
199                 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
200             if real_params.is_empty() {
201                 return Ok(());
202             }
203             if f.alternate() {
204                 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
205             } else {
206                 write!(f, "&lt;{}&gt;", comma_sep(real_params.iter().map(|g| g.print())))
207             }
208         })
209     }
210 }
211
212 impl<'a> fmt::Display for WhereClause<'a> {
213     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214         let &WhereClause { gens, indent, end_newline } = self;
215         if gens.where_predicates.is_empty() {
216             return Ok(());
217         }
218         let mut clause = String::new();
219         if f.alternate() {
220             clause.push_str(" where");
221         } else {
222             if end_newline {
223                 clause.push_str(" <span class=\"where fmt-newline\">where");
224             } else {
225                 clause.push_str(" <span class=\"where\">where");
226             }
227         }
228         for (i, pred) in gens.where_predicates.iter().enumerate() {
229             if f.alternate() {
230                 clause.push(' ');
231             } else {
232                 clause.push_str("<br>");
233             }
234
235             match pred {
236                 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
237                     let bounds = bounds;
238                     if f.alternate() {
239                         clause.push_str(&format!(
240                             "{:#}: {:#}",
241                             ty.print(),
242                             print_generic_bounds(bounds)
243                         ));
244                     } else {
245                         clause.push_str(&format!(
246                             "{}: {}",
247                             ty.print(),
248                             print_generic_bounds(bounds)
249                         ));
250                     }
251                 }
252                 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
253                     clause.push_str(&format!(
254                         "{}: {}",
255                         lifetime.print(),
256                         bounds
257                             .iter()
258                             .map(|b| b.print().to_string())
259                             .collect::<Vec<_>>()
260                             .join(" + ")
261                     ));
262                 }
263                 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
264                     if f.alternate() {
265                         clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
266                     } else {
267                         clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
268                     }
269                 }
270             }
271
272             if i < gens.where_predicates.len() - 1 || end_newline {
273                 clause.push(',');
274             }
275         }
276
277         if end_newline {
278             // add a space so stripping <br> tags and breaking spaces still renders properly
279             if f.alternate() {
280                 clause.push(' ');
281             } else {
282                 clause.push_str("&nbsp;");
283             }
284         }
285
286         if !f.alternate() {
287             clause.push_str("</span>");
288             let padding = "&nbsp;".repeat(indent + 4);
289             clause = clause.replace("<br>", &format!("<br>{}", padding));
290             clause.insert_str(0, &"&nbsp;".repeat(indent.saturating_sub(1)));
291             if !end_newline {
292                 clause.insert_str(0, "<br>");
293             }
294         }
295         write!(f, "{}", clause)
296     }
297 }
298
299 impl clean::Lifetime {
300     crate fn print(&self) -> &str {
301         self.get_ref()
302     }
303 }
304
305 impl clean::Constant {
306     crate fn print(&self) -> impl fmt::Display + '_ {
307         display_fn(move |f| {
308             if f.alternate() {
309                 f.write_str(&self.expr)
310             } else {
311                 write!(f, "{}", Escape(&self.expr))
312             }
313         })
314     }
315 }
316
317 impl clean::PolyTrait {
318     fn print(&self) -> impl fmt::Display + '_ {
319         display_fn(move |f| {
320             if !self.generic_params.is_empty() {
321                 if f.alternate() {
322                     write!(
323                         f,
324                         "for<{:#}> ",
325                         comma_sep(self.generic_params.iter().map(|g| g.print()))
326                     )?;
327                 } else {
328                     write!(
329                         f,
330                         "for&lt;{}&gt; ",
331                         comma_sep(self.generic_params.iter().map(|g| g.print()))
332                     )?;
333                 }
334             }
335             if f.alternate() {
336                 write!(f, "{:#}", self.trait_.print())
337             } else {
338                 write!(f, "{}", self.trait_.print())
339             }
340         })
341     }
342 }
343
344 impl clean::GenericBound {
345     crate fn print(&self) -> impl fmt::Display + '_ {
346         display_fn(move |f| match self {
347             clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
348             clean::GenericBound::TraitBound(ty, modifier) => {
349                 let modifier_str = match modifier {
350                     hir::TraitBoundModifier::None => "",
351                     hir::TraitBoundModifier::Maybe => "?",
352                     hir::TraitBoundModifier::MaybeConst => "?const",
353                 };
354                 if f.alternate() {
355                     write!(f, "{}{:#}", modifier_str, ty.print())
356                 } else {
357                     write!(f, "{}{}", modifier_str, ty.print())
358                 }
359             }
360         })
361     }
362 }
363
364 impl clean::GenericArgs {
365     fn print(&self) -> impl fmt::Display + '_ {
366         display_fn(move |f| {
367             match *self {
368                 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
369                     if !args.is_empty() || !bindings.is_empty() {
370                         if f.alternate() {
371                             f.write_str("<")?;
372                         } else {
373                             f.write_str("&lt;")?;
374                         }
375                         let mut comma = false;
376                         for arg in args {
377                             if comma {
378                                 f.write_str(", ")?;
379                             }
380                             comma = true;
381                             if f.alternate() {
382                                 write!(f, "{:#}", arg.print())?;
383                             } else {
384                                 write!(f, "{}", arg.print())?;
385                             }
386                         }
387                         for binding in bindings {
388                             if comma {
389                                 f.write_str(", ")?;
390                             }
391                             comma = true;
392                             if f.alternate() {
393                                 write!(f, "{:#}", binding.print())?;
394                             } else {
395                                 write!(f, "{}", binding.print())?;
396                             }
397                         }
398                         if f.alternate() {
399                             f.write_str(">")?;
400                         } else {
401                             f.write_str("&gt;")?;
402                         }
403                     }
404                 }
405                 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
406                     f.write_str("(")?;
407                     let mut comma = false;
408                     for ty in inputs {
409                         if comma {
410                             f.write_str(", ")?;
411                         }
412                         comma = true;
413                         if f.alternate() {
414                             write!(f, "{:#}", ty.print())?;
415                         } else {
416                             write!(f, "{}", ty.print())?;
417                         }
418                     }
419                     f.write_str(")")?;
420                     if let Some(ref ty) = *output {
421                         if f.alternate() {
422                             write!(f, " -> {:#}", ty.print())?;
423                         } else {
424                             write!(f, " -&gt; {}", ty.print())?;
425                         }
426                     }
427                 }
428             }
429             Ok(())
430         })
431     }
432 }
433
434 impl clean::PathSegment {
435     crate fn print(&self) -> impl fmt::Display + '_ {
436         display_fn(move |f| {
437             f.write_str(&self.name)?;
438             if f.alternate() {
439                 write!(f, "{:#}", self.args.print())
440             } else {
441                 write!(f, "{}", self.args.print())
442             }
443         })
444     }
445 }
446
447 impl clean::Path {
448     crate fn print(&self) -> impl fmt::Display + '_ {
449         display_fn(move |f| {
450             if self.global {
451                 f.write_str("::")?
452             }
453
454             for (i, seg) in self.segments.iter().enumerate() {
455                 if i > 0 {
456                     f.write_str("::")?
457                 }
458                 if f.alternate() {
459                     write!(f, "{:#}", seg.print())?;
460                 } else {
461                     write!(f, "{}", seg.print())?;
462                 }
463             }
464             Ok(())
465         })
466     }
467 }
468
469 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
470     let cache = cache();
471     if !did.is_local() && !cache.access_levels.is_public(did) {
472         return None;
473     }
474
475     let depth = CURRENT_DEPTH.with(|l| l.get());
476     let (fqp, shortty, mut url) = match cache.paths.get(&did) {
477         Some(&(ref fqp, shortty)) => (fqp, shortty, "../".repeat(depth)),
478         None => {
479             let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
480             (
481                 fqp,
482                 shortty,
483                 match cache.extern_locations[&did.krate] {
484                     (.., render::Remote(ref s)) => s.to_string(),
485                     (.., render::Local) => "../".repeat(depth),
486                     (.., render::Unknown) => return None,
487                 },
488             )
489         }
490     };
491     for component in &fqp[..fqp.len() - 1] {
492         url.push_str(component);
493         url.push_str("/");
494     }
495     match shortty {
496         ItemType::Module => {
497             url.push_str(fqp.last().unwrap());
498             url.push_str("/index.html");
499         }
500         _ => {
501             url.push_str(shortty.as_str());
502             url.push_str(".");
503             url.push_str(fqp.last().unwrap());
504             url.push_str(".html");
505         }
506     }
507     Some((url, shortty, fqp.to_vec()))
508 }
509
510 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
511 /// rendering function with the necessary arguments for linking to a local path.
512 fn resolved_path(
513     w: &mut fmt::Formatter<'_>,
514     did: DefId,
515     path: &clean::Path,
516     print_all: bool,
517     use_absolute: bool,
518 ) -> fmt::Result {
519     let last = path.segments.last().unwrap();
520
521     if print_all {
522         for seg in &path.segments[..path.segments.len() - 1] {
523             write!(w, "{}::", seg.name)?;
524         }
525     }
526     if w.alternate() {
527         write!(w, "{}{:#}", &last.name, last.args.print())?;
528     } else {
529         let path = if use_absolute {
530             if let Some((_, _, fqp)) = href(did) {
531                 format!("{}::{}", fqp[..fqp.len() - 1].join("::"), anchor(did, fqp.last().unwrap()))
532             } else {
533                 last.name.to_string()
534             }
535         } else {
536             anchor(did, &last.name).to_string()
537         };
538         write!(w, "{}{}", path, last.args.print())?;
539     }
540     Ok(())
541 }
542
543 fn primitive_link(
544     f: &mut fmt::Formatter<'_>,
545     prim: clean::PrimitiveType,
546     name: &str,
547 ) -> fmt::Result {
548     let m = cache();
549     let mut needs_termination = false;
550     if !f.alternate() {
551         match m.primitive_locations.get(&prim) {
552             Some(&def_id) if def_id.is_local() => {
553                 let len = CURRENT_DEPTH.with(|s| s.get());
554                 let len = if len == 0 { 0 } else { len - 1 };
555                 write!(
556                     f,
557                     "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
558                     "../".repeat(len),
559                     prim.to_url_str()
560                 )?;
561                 needs_termination = true;
562             }
563             Some(&def_id) => {
564                 let loc = match m.extern_locations[&def_id.krate] {
565                     (ref cname, _, render::Remote(ref s)) => Some((cname, s.to_string())),
566                     (ref cname, _, render::Local) => {
567                         let len = CURRENT_DEPTH.with(|s| s.get());
568                         Some((cname, "../".repeat(len)))
569                     }
570                     (.., render::Unknown) => None,
571                 };
572                 if let Some((cname, root)) = loc {
573                     write!(
574                         f,
575                         "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
576                         root,
577                         cname,
578                         prim.to_url_str()
579                     )?;
580                     needs_termination = true;
581                 }
582             }
583             None => {}
584         }
585     }
586     write!(f, "{}", name)?;
587     if needs_termination {
588         write!(f, "</a>")?;
589     }
590     Ok(())
591 }
592
593 /// Helper to render type parameters
594 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
595     display_fn(move |f| match *param_names {
596         Some(ref params) => {
597             for param in params {
598                 write!(f, " + ")?;
599                 fmt::Display::fmt(&param.print(), f)?;
600             }
601             Ok(())
602         }
603         None => Ok(()),
604     })
605 }
606
607 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
608     display_fn(move |f| {
609         if let Some((url, short_ty, fqp)) = href(did) {
610             write!(
611                 f,
612                 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
613                 short_ty,
614                 url,
615                 short_ty,
616                 fqp.join("::"),
617                 text
618             )
619         } else {
620             write!(f, "{}", text)
621         }
622     })
623 }
624
625 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
626     match *t {
627         clean::Generic(ref name) => f.write_str(name),
628         clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
629             if param_names.is_some() {
630                 f.write_str("dyn ")?;
631             }
632             // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
633             resolved_path(f, did, path, is_generic, use_absolute)?;
634             fmt::Display::fmt(&tybounds(param_names), f)
635         }
636         clean::Infer => write!(f, "_"),
637         clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
638         clean::BareFunction(ref decl) => {
639             if f.alternate() {
640                 write!(
641                     f,
642                     "{}{:#}fn{:#}{:#}",
643                     decl.unsafety.print_with_space(),
644                     print_abi_with_space(decl.abi),
645                     decl.print_generic_params(),
646                     decl.decl.print()
647                 )
648             } else {
649                 write!(
650                     f,
651                     "{}{}",
652                     decl.unsafety.print_with_space(),
653                     print_abi_with_space(decl.abi)
654                 )?;
655                 primitive_link(f, PrimitiveType::Fn, "fn")?;
656                 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
657             }
658         }
659         clean::Tuple(ref typs) => {
660             match &typs[..] {
661                 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
662                 &[ref one] => {
663                     primitive_link(f, PrimitiveType::Tuple, "(")?;
664                     // Carry `f.alternate()` into this display w/o branching manually.
665                     fmt::Display::fmt(&one.print(), f)?;
666                     primitive_link(f, PrimitiveType::Tuple, ",)")
667                 }
668                 many => {
669                     primitive_link(f, PrimitiveType::Tuple, "(")?;
670                     for (i, item) in many.iter().enumerate() {
671                         if i != 0 {
672                             write!(f, ", ")?;
673                         }
674                         fmt::Display::fmt(&item.print(), f)?;
675                     }
676                     primitive_link(f, PrimitiveType::Tuple, ")")
677                 }
678             }
679         }
680         clean::Slice(ref t) => {
681             primitive_link(f, PrimitiveType::Slice, "[")?;
682             fmt::Display::fmt(&t.print(), f)?;
683             primitive_link(f, PrimitiveType::Slice, "]")
684         }
685         clean::Array(ref t, ref n) => {
686             primitive_link(f, PrimitiveType::Array, "[")?;
687             fmt::Display::fmt(&t.print(), f)?;
688             if f.alternate() {
689                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
690             } else {
691                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)))
692             }
693         }
694         clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
695         clean::RawPointer(m, ref t) => {
696             let m = match m {
697                 hir::Mutability::Mut => "mut",
698                 hir::Mutability::Not => "const",
699             };
700             match **t {
701                 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
702                     if f.alternate() {
703                         primitive_link(
704                             f,
705                             clean::PrimitiveType::RawPointer,
706                             &format!("*{} {:#}", m, t.print()),
707                         )
708                     } else {
709                         primitive_link(
710                             f,
711                             clean::PrimitiveType::RawPointer,
712                             &format!("*{} {}", m, t.print()),
713                         )
714                     }
715                 }
716                 _ => {
717                     primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
718                     fmt::Display::fmt(&t.print(), f)
719                 }
720             }
721         }
722         clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
723             let lt = match l {
724                 Some(l) => format!("{} ", l.print()),
725                 _ => String::new(),
726             };
727             let m = mutability.print_with_space();
728             let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
729             match **ty {
730                 clean::Slice(ref bt) => {
731                     // `BorrowedRef{ ... Slice(T) }` is `&[T]`
732                     match **bt {
733                         clean::Generic(_) => {
734                             if f.alternate() {
735                                 primitive_link(
736                                     f,
737                                     PrimitiveType::Slice,
738                                     &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()),
739                                 )
740                             } else {
741                                 primitive_link(
742                                     f,
743                                     PrimitiveType::Slice,
744                                     &format!("{}{}{}[{}]", amp, lt, m, bt.print()),
745                                 )
746                             }
747                         }
748                         _ => {
749                             primitive_link(
750                                 f,
751                                 PrimitiveType::Slice,
752                                 &format!("{}{}{}[", amp, lt, m),
753                             )?;
754                             if f.alternate() {
755                                 write!(f, "{:#}", bt.print())?;
756                             } else {
757                                 write!(f, "{}", bt.print())?;
758                             }
759                             primitive_link(f, PrimitiveType::Slice, "]")
760                         }
761                     }
762                 }
763                 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
764                     write!(f, "{}{}{}(", amp, lt, m)?;
765                     fmt_type(&ty, f, use_absolute)?;
766                     write!(f, ")")
767                 }
768                 clean::Generic(..) => {
769                     primitive_link(f, PrimitiveType::Reference, &format!("{}{}{}", amp, lt, m))?;
770                     fmt_type(&ty, f, use_absolute)
771                 }
772                 _ => {
773                     write!(f, "{}{}{}", amp, lt, m)?;
774                     fmt_type(&ty, f, use_absolute)
775                 }
776             }
777         }
778         clean::ImplTrait(ref bounds) => {
779             if f.alternate() {
780                 write!(f, "impl {:#}", print_generic_bounds(bounds))
781             } else {
782                 write!(f, "impl {}", print_generic_bounds(bounds))
783             }
784         }
785         clean::QPath { ref name, ref self_type, ref trait_ } => {
786             let should_show_cast = match *trait_ {
787                 box clean::ResolvedPath { ref path, .. } => {
788                     !path.segments.is_empty() && !self_type.is_self_type()
789                 }
790                 _ => true,
791             };
792             if f.alternate() {
793                 if should_show_cast {
794                     write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
795                 } else {
796                     write!(f, "{:#}::", self_type.print())?
797                 }
798             } else {
799                 if should_show_cast {
800                     write!(f, "&lt;{} as {}&gt;::", self_type.print(), trait_.print())?
801                 } else {
802                     write!(f, "{}::", self_type.print())?
803                 }
804             };
805             match *trait_ {
806                 // It's pretty unsightly to look at `<A as B>::C` in output, and
807                 // we've got hyperlinking on our side, so try to avoid longer
808                 // notation as much as possible by making `C` a hyperlink to trait
809                 // `B` to disambiguate.
810                 //
811                 // FIXME: this is still a lossy conversion and there should probably
812                 //        be a better way of representing this in general? Most of
813                 //        the ugliness comes from inlining across crates where
814                 //        everything comes in as a fully resolved QPath (hard to
815                 //        look at).
816                 box clean::ResolvedPath { did, ref param_names, .. } => {
817                     match href(did) {
818                         Some((ref url, _, ref path)) if !f.alternate() => {
819                             write!(
820                                 f,
821                                 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
822                                    title=\"type {path}::{name}\">{name}</a>",
823                                 url = url,
824                                 shortty = ItemType::AssocType,
825                                 name = name,
826                                 path = path.join("::")
827                             )?;
828                         }
829                         _ => write!(f, "{}", name)?,
830                     }
831
832                     // FIXME: `param_names` are not rendered, and this seems bad?
833                     drop(param_names);
834                     Ok(())
835                 }
836                 _ => write!(f, "{}", name),
837             }
838         }
839     }
840 }
841
842 impl clean::Type {
843     crate fn print(&self) -> impl fmt::Display + '_ {
844         display_fn(move |f| fmt_type(self, f, false))
845     }
846 }
847
848 impl clean::Impl {
849     crate fn print(&self) -> impl fmt::Display + '_ {
850         self.print_inner(true, false)
851     }
852
853     fn print_inner(&self, link_trait: bool, use_absolute: bool) -> impl fmt::Display + '_ {
854         display_fn(move |f| {
855             if f.alternate() {
856                 write!(f, "impl{:#} ", self.generics.print())?;
857             } else {
858                 write!(f, "impl{} ", self.generics.print())?;
859             }
860
861             if let Some(ref ty) = self.trait_ {
862                 if self.polarity == Some(clean::ImplPolarity::Negative) {
863                     write!(f, "!")?;
864                 }
865
866                 if link_trait {
867                     fmt::Display::fmt(&ty.print(), f)?;
868                 } else {
869                     match ty {
870                         clean::ResolvedPath {
871                             param_names: None, path, is_generic: false, ..
872                         } => {
873                             let last = path.segments.last().unwrap();
874                             fmt::Display::fmt(&last.name, f)?;
875                             fmt::Display::fmt(&last.args.print(), f)?;
876                         }
877                         _ => unreachable!(),
878                     }
879                 }
880                 write!(f, " for ")?;
881             }
882
883             if let Some(ref ty) = self.blanket_impl {
884                 fmt_type(ty, f, use_absolute)?;
885             } else {
886                 fmt_type(&self.for_, f, use_absolute)?;
887             }
888
889             fmt::Display::fmt(
890                 &WhereClause { gens: &self.generics, indent: 0, end_newline: true },
891                 f,
892             )?;
893             Ok(())
894         })
895     }
896 }
897
898 // The difference from above is that trait is not hyperlinked.
899 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) {
900     f.from_display(i.print_inner(false, use_absolute))
901 }
902
903 impl clean::Arguments {
904     crate fn print(&self) -> impl fmt::Display + '_ {
905         display_fn(move |f| {
906             for (i, input) in self.values.iter().enumerate() {
907                 if !input.name.is_empty() {
908                     write!(f, "{}: ", input.name)?;
909                 }
910                 if f.alternate() {
911                     write!(f, "{:#}", input.type_.print())?;
912                 } else {
913                     write!(f, "{}", input.type_.print())?;
914                 }
915                 if i + 1 < self.values.len() {
916                     write!(f, ", ")?;
917                 }
918             }
919             Ok(())
920         })
921     }
922 }
923
924 impl clean::FnRetTy {
925     crate fn print(&self) -> impl fmt::Display + '_ {
926         display_fn(move |f| match self {
927             clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
928             clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
929             clean::Return(ty) => write!(f, " -&gt; {}", ty.print()),
930             clean::DefaultReturn => Ok(()),
931         })
932     }
933 }
934
935 impl clean::BareFunctionDecl {
936     fn print_generic_params(&self) -> impl fmt::Display + '_ {
937         comma_sep(self.generic_params.iter().map(|g| g.print()))
938     }
939 }
940
941 impl clean::FnDecl {
942     crate fn print(&self) -> impl fmt::Display + '_ {
943         display_fn(move |f| {
944             let ellipsis = if self.c_variadic { ", ..." } else { "" };
945             if f.alternate() {
946                 write!(
947                     f,
948                     "({args:#}{ellipsis}){arrow:#}",
949                     args = self.inputs.print(),
950                     ellipsis = ellipsis,
951                     arrow = self.output.print()
952                 )
953             } else {
954                 write!(
955                     f,
956                     "({args}{ellipsis}){arrow}",
957                     args = self.inputs.print(),
958                     ellipsis = ellipsis,
959                     arrow = self.output.print()
960                 )
961             }
962         })
963     }
964 }
965
966 impl Function<'_> {
967     crate fn print(&self) -> impl fmt::Display + '_ {
968         display_fn(move |f| {
969             let &Function { decl, header_len, indent, asyncness } = self;
970             let amp = if f.alternate() { "&" } else { "&amp;" };
971             let mut args = String::new();
972             let mut args_plain = String::new();
973             for (i, input) in decl.inputs.values.iter().enumerate() {
974                 if i == 0 {
975                     args.push_str("<br>");
976                 }
977
978                 if let Some(selfty) = input.to_self() {
979                     match selfty {
980                         clean::SelfValue => {
981                             args.push_str("self");
982                             args_plain.push_str("self");
983                         }
984                         clean::SelfBorrowed(Some(ref lt), mtbl) => {
985                             args.push_str(&format!(
986                                 "{}{} {}self",
987                                 amp,
988                                 lt.print(),
989                                 mtbl.print_with_space()
990                             ));
991                             args_plain.push_str(&format!(
992                                 "&{} {}self",
993                                 lt.print(),
994                                 mtbl.print_with_space()
995                             ));
996                         }
997                         clean::SelfBorrowed(None, mtbl) => {
998                             args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
999                             args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1000                         }
1001                         clean::SelfExplicit(ref typ) => {
1002                             if f.alternate() {
1003                                 args.push_str(&format!("self: {:#}", typ.print()));
1004                             } else {
1005                                 args.push_str(&format!("self: {}", typ.print()));
1006                             }
1007                             args_plain.push_str(&format!("self: {:#}", typ.print()));
1008                         }
1009                     }
1010                 } else {
1011                     if i > 0 {
1012                         args.push_str(" <br>");
1013                         args_plain.push_str(" ");
1014                     }
1015                     if !input.name.is_empty() {
1016                         args.push_str(&format!("{}: ", input.name));
1017                         args_plain.push_str(&format!("{}: ", input.name));
1018                     }
1019
1020                     if f.alternate() {
1021                         args.push_str(&format!("{:#}", input.type_.print()));
1022                     } else {
1023                         args.push_str(&input.type_.print().to_string());
1024                     }
1025                     args_plain.push_str(&format!("{:#}", input.type_.print()));
1026                 }
1027                 if i + 1 < decl.inputs.values.len() {
1028                     args.push(',');
1029                     args_plain.push(',');
1030                 }
1031             }
1032
1033             let mut args_plain = format!("({})", args_plain);
1034
1035             if decl.c_variadic {
1036                 args.push_str(",<br> ...");
1037                 args_plain.push_str(", ...");
1038             }
1039
1040             let output = if let hir::IsAsync::Async = asyncness {
1041                 Cow::Owned(decl.sugared_async_return_type())
1042             } else {
1043                 Cow::Borrowed(&decl.output)
1044             };
1045
1046             let arrow_plain = format!("{:#}", &output.print());
1047             let arrow = if f.alternate() {
1048                 format!("{:#}", &output.print())
1049             } else {
1050                 output.print().to_string()
1051             };
1052
1053             let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1054             let output = if declaration_len > 80 {
1055                 let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1056                 let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1057                 format!(
1058                     "({args}{close}){arrow}",
1059                     args = args.replace("<br>", &full_pad),
1060                     close = close_pad,
1061                     arrow = arrow
1062                 )
1063             } else {
1064                 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1065             };
1066
1067             if f.alternate() {
1068                 write!(f, "{}", output.replace("<br>", "\n"))
1069             } else {
1070                 write!(f, "{}", output)
1071             }
1072         })
1073     }
1074 }
1075
1076 impl clean::Visibility {
1077     crate fn print_with_space(&self) -> impl fmt::Display + '_ {
1078         display_fn(move |f| match *self {
1079             clean::Public => f.write_str("pub "),
1080             clean::Inherited => Ok(()),
1081             clean::Visibility::Crate => write!(f, "pub(crate) "),
1082             clean::Visibility::Restricted(did, ref path) => {
1083                 f.write_str("pub(")?;
1084                 if path.segments.len() != 1
1085                     || (path.segments[0].name != "self" && path.segments[0].name != "super")
1086                 {
1087                     f.write_str("in ")?;
1088                 }
1089                 resolved_path(f, did, path, true, false)?;
1090                 f.write_str(") ")
1091             }
1092         })
1093     }
1094 }
1095
1096 crate trait PrintWithSpace {
1097     fn print_with_space(&self) -> &str;
1098 }
1099
1100 impl PrintWithSpace for hir::Unsafety {
1101     fn print_with_space(&self) -> &str {
1102         match self {
1103             hir::Unsafety::Unsafe => "unsafe ",
1104             hir::Unsafety::Normal => "",
1105         }
1106     }
1107 }
1108
1109 impl PrintWithSpace for hir::Constness {
1110     fn print_with_space(&self) -> &str {
1111         match self {
1112             hir::Constness::Const => "const ",
1113             hir::Constness::NotConst => "",
1114         }
1115     }
1116 }
1117
1118 impl PrintWithSpace for hir::IsAsync {
1119     fn print_with_space(&self) -> &str {
1120         match self {
1121             hir::IsAsync::Async => "async ",
1122             hir::IsAsync::NotAsync => "",
1123         }
1124     }
1125 }
1126
1127 impl PrintWithSpace for hir::Mutability {
1128     fn print_with_space(&self) -> &str {
1129         match self {
1130             hir::Mutability::Not => "",
1131             hir::Mutability::Mut => "mut ",
1132         }
1133     }
1134 }
1135
1136 impl clean::Import {
1137     crate fn print(&self) -> impl fmt::Display + '_ {
1138         display_fn(move |f| match *self {
1139             clean::Import::Simple(ref name, ref src) => {
1140                 if *name == src.path.last_name() {
1141                     write!(f, "use {};", src.print())
1142                 } else {
1143                     write!(f, "use {} as {};", src.print(), *name)
1144                 }
1145             }
1146             clean::Import::Glob(ref src) => {
1147                 if src.path.segments.is_empty() {
1148                     write!(f, "use *;")
1149                 } else {
1150                     write!(f, "use {}::*;", src.print())
1151                 }
1152             }
1153         })
1154     }
1155 }
1156
1157 impl clean::ImportSource {
1158     crate fn print(&self) -> impl fmt::Display + '_ {
1159         display_fn(move |f| match self.did {
1160             Some(did) => resolved_path(f, did, &self.path, true, false),
1161             _ => {
1162                 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1163                     write!(f, "{}::", seg.name)?;
1164                 }
1165                 let name = self.path.last_name();
1166                 if let hir::def::Res::PrimTy(p) = self.path.res {
1167                     primitive_link(f, PrimitiveType::from(p), name)?;
1168                 } else {
1169                     write!(f, "{}", name)?;
1170                 }
1171                 Ok(())
1172             }
1173         })
1174     }
1175 }
1176
1177 impl clean::TypeBinding {
1178     crate fn print(&self) -> impl fmt::Display + '_ {
1179         display_fn(move |f| {
1180             f.write_str(&self.name)?;
1181             match self.kind {
1182                 clean::TypeBindingKind::Equality { ref ty } => {
1183                     if f.alternate() {
1184                         write!(f, " = {:#}", ty.print())?;
1185                     } else {
1186                         write!(f, " = {}", ty.print())?;
1187                     }
1188                 }
1189                 clean::TypeBindingKind::Constraint { ref bounds } => {
1190                     if !bounds.is_empty() {
1191                         if f.alternate() {
1192                             write!(f, ": {:#}", print_generic_bounds(bounds))?;
1193                         } else {
1194                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds))?;
1195                         }
1196                     }
1197                 }
1198             }
1199             Ok(())
1200         })
1201     }
1202 }
1203
1204 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1205     display_fn(move |f| {
1206         let quot = if f.alternate() { "\"" } else { "&quot;" };
1207         match abi {
1208             Abi::Rust => Ok(()),
1209             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1210         }
1211     })
1212 }
1213
1214 crate fn print_default_space<'a>(v: bool) -> &'a str {
1215     if v { "default " } else { "" }
1216 }
1217
1218 impl clean::GenericArg {
1219     crate fn print(&self) -> impl fmt::Display + '_ {
1220         display_fn(move |f| match self {
1221             clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1222             clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1223             clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1224         })
1225     }
1226 }
1227
1228 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1229     WithFormatter(Cell::new(Some(f)))
1230 }
1231
1232 struct WithFormatter<F>(Cell<Option<F>>);
1233
1234 impl<F> fmt::Display for WithFormatter<F>
1235 where
1236     F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1237 {
1238     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1239         (self.0.take()).unwrap()(f)
1240     }
1241 }