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