]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Rollup merge of #64895 - davidtwco:issue-64130-async-error-definition, r=nikomatsakis
[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::RawPointer(m, ref t) => {
661             let m = match m {
662                 clean::Immutable => "const",
663                 clean::Mutable => "mut",
664             };
665             match **t {
666                 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
667                     if f.alternate() {
668                         primitive_link(f, clean::PrimitiveType::RawPointer,
669                                        &format!("*{} {:#}", m, t.print()))
670                     } else {
671                         primitive_link(f, clean::PrimitiveType::RawPointer,
672                                        &format!("*{} {}", m, t.print()))
673                     }
674                 }
675                 _ => {
676                     primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
677                     fmt::Display::fmt(&t.print(), f)
678                 }
679             }
680         }
681         clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
682             let lt = match l {
683                 Some(l) => format!("{} ", l.print()),
684                 _ => String::new()
685             };
686             let m = mutability.print_with_space();
687             let amp = if f.alternate() {
688                 "&".to_string()
689             } else {
690                 "&amp;".to_string()
691             };
692             match **ty {
693                 clean::Slice(ref bt) => { // `BorrowedRef{ ... Slice(T) }` is `&[T]`
694                     match **bt {
695                         clean::Generic(_) => {
696                             if f.alternate() {
697                                 primitive_link(f, PrimitiveType::Slice,
698                                     &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()))
699                             } else {
700                                 primitive_link(f, PrimitiveType::Slice,
701                                     &format!("{}{}{}[{}]", amp, lt, m, bt.print()))
702                             }
703                         }
704                         _ => {
705                             primitive_link(f, PrimitiveType::Slice,
706                                            &format!("{}{}{}[", amp, lt, m))?;
707                             if f.alternate() {
708                                 write!(f, "{:#}", bt.print())?;
709                             } else {
710                                 write!(f, "{}", bt.print())?;
711                             }
712                             primitive_link(f, PrimitiveType::Slice, "]")
713                         }
714                     }
715                 }
716                 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
717                     write!(f, "{}{}{}(", amp, lt, m)?;
718                     fmt_type(&ty, f, use_absolute)?;
719                     write!(f, ")")
720                 }
721                 clean::Generic(..) => {
722                     primitive_link(f, PrimitiveType::Reference,
723                                    &format!("{}{}{}", amp, lt, m))?;
724                     fmt_type(&ty, f, use_absolute)
725                 }
726                 _ => {
727                     write!(f, "{}{}{}", amp, lt, m)?;
728                     fmt_type(&ty, f, use_absolute)
729                 }
730             }
731         }
732         clean::ImplTrait(ref bounds) => {
733             if f.alternate() {
734                 write!(f, "impl {:#}", print_generic_bounds(bounds))
735             } else {
736                 write!(f, "impl {}", print_generic_bounds(bounds))
737             }
738         }
739         clean::QPath { ref name, ref self_type, ref trait_ } => {
740             let should_show_cast = match *trait_ {
741                 box clean::ResolvedPath { ref path, .. } => {
742                     !path.segments.is_empty() && !self_type.is_self_type()
743                 }
744                 _ => true,
745             };
746             if f.alternate() {
747                 if should_show_cast {
748                     write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
749                 } else {
750                     write!(f, "{:#}::", self_type.print())?
751                 }
752             } else {
753                 if should_show_cast {
754                     write!(f, "&lt;{} as {}&gt;::", self_type.print(), trait_.print())?
755                 } else {
756                     write!(f, "{}::", self_type.print())?
757                 }
758             };
759             match *trait_ {
760                 // It's pretty unsightly to look at `<A as B>::C` in output, and
761                 // we've got hyperlinking on our side, so try to avoid longer
762                 // notation as much as possible by making `C` a hyperlink to trait
763                 // `B` to disambiguate.
764                 //
765                 // FIXME: this is still a lossy conversion and there should probably
766                 //        be a better way of representing this in general? Most of
767                 //        the ugliness comes from inlining across crates where
768                 //        everything comes in as a fully resolved QPath (hard to
769                 //        look at).
770                 box clean::ResolvedPath { did, ref param_names, .. } => {
771                     match href(did) {
772                         Some((ref url, _, ref path)) if !f.alternate() => {
773                             write!(f,
774                                    "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
775                                    title=\"type {path}::{name}\">{name}</a>",
776                                    url = url,
777                                    shortty = ItemType::AssocType,
778                                    name = name,
779                                    path = path.join("::"))?;
780                         }
781                         _ => write!(f, "{}", name)?,
782                     }
783
784                     // FIXME: `param_names` are not rendered, and this seems bad?
785                     drop(param_names);
786                     Ok(())
787                 }
788                 _ => {
789                     write!(f, "{}", name)
790                 }
791             }
792         }
793     }
794 }
795
796 impl clean::Type {
797     crate fn print(&self) -> impl fmt::Display + '_ {
798         display_fn(move |f| {
799             fmt_type(self, f, false)
800         })
801     }
802 }
803
804 impl clean::Impl {
805     crate fn print(&self) -> impl fmt::Display + '_ {
806         self.print_inner(true, false)
807     }
808
809     fn print_inner(
810         &self,
811         link_trait: bool,
812         use_absolute: bool,
813     ) -> impl fmt::Display + '_ {
814         display_fn(move |f| {
815             if f.alternate() {
816                 write!(f, "impl{:#} ", self.generics.print())?;
817             } else {
818                 write!(f, "impl{} ", self.generics.print())?;
819             }
820
821             if let Some(ref ty) = self.trait_ {
822                 if self.polarity == Some(clean::ImplPolarity::Negative) {
823                     write!(f, "!")?;
824                 }
825
826                 if link_trait {
827                     fmt::Display::fmt(&ty.print(), f)?;
828                 } else {
829                     match ty {
830                         clean::ResolvedPath { param_names: None, path, is_generic: false, .. } => {
831                             let last = path.segments.last().unwrap();
832                             fmt::Display::fmt(&last.name, f)?;
833                             fmt::Display::fmt(&last.args.print(), f)?;
834                         }
835                         _ => unreachable!(),
836                     }
837                 }
838                 write!(f, " for ")?;
839             }
840
841             if let Some(ref ty) = self.blanket_impl {
842                 fmt_type(ty, f, use_absolute)?;
843             } else {
844                 fmt_type(&self.for_, f, use_absolute)?;
845             }
846
847             fmt::Display::fmt(&WhereClause {
848                 gens: &self.generics,
849                 indent: 0,
850                 end_newline: true,
851             }, f)?;
852             Ok(())
853         })
854     }
855 }
856
857 // The difference from above is that trait is not hyperlinked.
858 pub fn fmt_impl_for_trait_page(i: &clean::Impl,
859                                f: &mut Buffer,
860                                use_absolute: bool) {
861     f.from_display(i.print_inner(false, use_absolute))
862 }
863
864 impl clean::Arguments {
865     crate fn print(&self) -> impl fmt::Display + '_ {
866         display_fn(move |f| {
867             for (i, input) in self.values.iter().enumerate() {
868                 if !input.name.is_empty() {
869                     write!(f, "{}: ", input.name)?;
870                 }
871                 if f.alternate() {
872                     write!(f, "{:#}", input.type_.print())?;
873                 } else {
874                     write!(f, "{}", input.type_.print())?;
875                 }
876                 if i + 1 < self.values.len() { write!(f, ", ")?; }
877             }
878             Ok(())
879         })
880     }
881 }
882
883 impl clean::FunctionRetTy {
884     crate fn print(&self) -> impl fmt::Display + '_ {
885         display_fn(move |f| {
886             match self {
887                 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
888                 clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
889                 clean::Return(ty) => write!(f, " -&gt; {}", ty.print()),
890                 clean::DefaultReturn => Ok(()),
891             }
892         })
893     }
894 }
895
896 impl clean::BareFunctionDecl {
897     fn print_generic_params(&self) -> impl fmt::Display + '_ {
898         comma_sep(self.generic_params.iter().map(|g| g.print()))
899     }
900 }
901
902 impl clean::FnDecl {
903     crate fn print(&self) -> impl fmt::Display + '_ {
904         display_fn(move |f| {
905         let ellipsis = if self.c_variadic { ", ..." } else { "" };
906             if f.alternate() {
907                 write!(f,
908                     "({args:#}{ellipsis}){arrow:#}",
909                     args = self.inputs.print(), ellipsis = ellipsis, arrow = self.output.print())
910             } else {
911                 write!(f,
912                     "({args}{ellipsis}){arrow}",
913                     args = self.inputs.print(), ellipsis = ellipsis, arrow = self.output.print())
914             }
915         })
916     }
917 }
918
919
920 impl Function<'_> {
921     crate fn print(&self) -> impl fmt::Display + '_ {
922         display_fn(move |f| {
923             let &Function { decl, header_len, indent, asyncness } = self;
924             let amp = if f.alternate() { "&" } else { "&amp;" };
925             let mut args = String::new();
926             let mut args_plain = String::new();
927             for (i, input) in decl.inputs.values.iter().enumerate() {
928                 if i == 0 {
929                     args.push_str("<br>");
930                 }
931
932                 if let Some(selfty) = input.to_self() {
933                     match selfty {
934                         clean::SelfValue => {
935                             args.push_str("self");
936                             args_plain.push_str("self");
937                         }
938                         clean::SelfBorrowed(Some(ref lt), mtbl) => {
939                             args.push_str(
940                                 &format!("{}{} {}self", amp, lt.print(), mtbl.print_with_space()));
941                             args_plain.push_str(
942                                 &format!("&{} {}self", lt.print(), mtbl.print_with_space()));
943                         }
944                         clean::SelfBorrowed(None, mtbl) => {
945                             args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
946                             args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
947                         }
948                         clean::SelfExplicit(ref typ) => {
949                             if f.alternate() {
950                                 args.push_str(&format!("self: {:#}", typ.print()));
951                             } else {
952                                 args.push_str(&format!("self: {}", typ.print()));
953                             }
954                             args_plain.push_str(&format!("self: {:#}", typ.print()));
955                         }
956                     }
957                 } else {
958                     if i > 0 {
959                         args.push_str(" <br>");
960                         args_plain.push_str(" ");
961                     }
962                     if !input.name.is_empty() {
963                         args.push_str(&format!("{}: ", input.name));
964                         args_plain.push_str(&format!("{}: ", input.name));
965                     }
966
967                     if f.alternate() {
968                         args.push_str(&format!("{:#}", input.type_.print()));
969                     } else {
970                         args.push_str(&input.type_.print().to_string());
971                     }
972                     args_plain.push_str(&format!("{:#}", input.type_.print()));
973                 }
974                 if i + 1 < decl.inputs.values.len() {
975                     args.push(',');
976                     args_plain.push(',');
977                 }
978             }
979
980             let mut args_plain = format!("({})", args_plain);
981
982             if decl.c_variadic {
983                 args.push_str(",<br> ...");
984                 args_plain.push_str(", ...");
985             }
986
987             let output = if let hir::IsAsync::Async = asyncness {
988                 Cow::Owned(decl.sugared_async_return_type())
989             } else {
990                 Cow::Borrowed(&decl.output)
991             };
992
993             let arrow_plain = format!("{:#}", &output.print());
994             let arrow = if f.alternate() {
995                 format!("{:#}", &output.print())
996             } else {
997                 output.print().to_string()
998             };
999
1000             let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1001             let output = if declaration_len > 80 {
1002                 let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1003                 let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1004                 format!("({args}{close}){arrow}",
1005                         args = args.replace("<br>", &full_pad),
1006                         close = close_pad,
1007                         arrow = arrow)
1008             } else {
1009                 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1010             };
1011
1012             if f.alternate() {
1013                 write!(f, "{}", output.replace("<br>", "\n"))
1014             } else {
1015                 write!(f, "{}", output)
1016             }
1017         })
1018     }
1019 }
1020
1021 impl clean::Visibility {
1022     crate fn print_with_space(&self) -> impl fmt::Display + '_ {
1023         display_fn(move |f| {
1024             match *self {
1025                 clean::Public => f.write_str("pub "),
1026                 clean::Inherited => Ok(()),
1027                 clean::Visibility::Crate => write!(f, "pub(crate) "),
1028                 clean::Visibility::Restricted(did, ref path) => {
1029                     f.write_str("pub(")?;
1030                     if path.segments.len() != 1
1031                         || (path.segments[0].name != "self" && path.segments[0].name != "super")
1032                     {
1033                         f.write_str("in ")?;
1034                     }
1035                     resolved_path(f, did, path, true, false)?;
1036                     f.write_str(") ")
1037                 }
1038             }
1039         })
1040     }
1041 }
1042
1043 crate trait PrintWithSpace {
1044     fn print_with_space(&self) -> &str;
1045 }
1046
1047 impl PrintWithSpace for hir::Unsafety {
1048     fn print_with_space(&self) -> &str {
1049         match self {
1050             hir::Unsafety::Unsafe => "unsafe ",
1051             hir::Unsafety::Normal => ""
1052         }
1053     }
1054 }
1055
1056 impl PrintWithSpace for hir::Constness {
1057     fn print_with_space(&self) -> &str {
1058         match self {
1059             hir::Constness::Const => "const ",
1060             hir::Constness::NotConst => ""
1061         }
1062     }
1063 }
1064
1065 impl PrintWithSpace for hir::IsAsync {
1066     fn print_with_space(&self) -> &str {
1067         match self {
1068             hir::IsAsync::Async => "async ",
1069             hir::IsAsync::NotAsync => "",
1070         }
1071     }
1072 }
1073
1074 impl clean::Import {
1075     crate fn print(&self) -> impl fmt::Display + '_ {
1076         display_fn(move |f| {
1077             match *self {
1078                 clean::Import::Simple(ref name, ref src) => {
1079                     if *name == src.path.last_name() {
1080                         write!(f, "use {};", src.print())
1081                     } else {
1082                         write!(f, "use {} as {};", src.print(), *name)
1083                     }
1084                 }
1085                 clean::Import::Glob(ref src) => {
1086                     if src.path.segments.is_empty() {
1087                         write!(f, "use *;")
1088                     } else {
1089                         write!(f, "use {}::*;", src.print())
1090                     }
1091                 }
1092             }
1093         })
1094     }
1095 }
1096
1097 impl clean::ImportSource {
1098     crate fn print(&self) -> impl fmt::Display + '_ {
1099         display_fn(move |f| {
1100             match self.did {
1101                 Some(did) => resolved_path(f, did, &self.path, true, false),
1102                 _ => {
1103                     for (i, seg) in self.path.segments.iter().enumerate() {
1104                         if i > 0 {
1105                             write!(f, "::")?
1106                         }
1107                         write!(f, "{}", seg.name)?;
1108                     }
1109                     Ok(())
1110                 }
1111             }
1112         })
1113     }
1114 }
1115
1116 impl clean::TypeBinding {
1117     crate fn print(&self) -> impl fmt::Display + '_ {
1118         display_fn(move |f| {
1119             f.write_str(&self.name)?;
1120             match self.kind {
1121                 clean::TypeBindingKind::Equality { ref ty } => {
1122                     if f.alternate() {
1123                         write!(f, " = {:#}", ty.print())?;
1124                     } else {
1125                         write!(f, " = {}", ty.print())?;
1126                     }
1127                 }
1128                 clean::TypeBindingKind::Constraint { ref bounds } => {
1129                     if !bounds.is_empty() {
1130                         if f.alternate() {
1131                             write!(f, ": {:#}", print_generic_bounds(bounds))?;
1132                         } else {
1133                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds))?;
1134                         }
1135                     }
1136                 }
1137             }
1138             Ok(())
1139         })
1140     }
1141 }
1142
1143 impl clean::Mutability {
1144     crate fn print_with_space(&self) -> &str {
1145         match self {
1146             clean::Immutable => "",
1147             clean::Mutable => "mut ",
1148         }
1149     }
1150 }
1151
1152 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1153     display_fn(move |f| {
1154         let quot = if f.alternate() { "\"" } else { "&quot;" };
1155         match abi {
1156             Abi::Rust => Ok(()),
1157             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1158         }
1159     })
1160 }
1161
1162 crate fn print_default_space<'a>(v: bool) -> &'a str {
1163     if v {
1164         "default "
1165     } else {
1166         ""
1167     }
1168 }
1169
1170 impl clean::GenericArg {
1171     crate fn print(&self) -> impl fmt::Display + '_ {
1172         display_fn(move |f| {
1173             match self {
1174                 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1175                 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1176                 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1177             }
1178         })
1179     }
1180 }
1181
1182 crate fn display_fn(
1183     f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1184 ) -> impl fmt::Display {
1185     WithFormatter(Cell::new(Some(f)))
1186 }
1187
1188 struct WithFormatter<F>(Cell<Option<F>>);
1189
1190 impl<F> fmt::Display for WithFormatter<F>
1191     where F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1192 {
1193     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194         (self.0.take()).unwrap()(f)
1195     }
1196 }