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