]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Auto merge of #69295 - ecstatic-morse:unified-dataflow-generators, r=tmandry
[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                     hir::TraitBoundModifier::MaybeConst => "?const",
365                 };
366                 if f.alternate() {
367                     write!(f, "{}{:#}", modifier_str, ty.print())
368                 } else {
369                     write!(f, "{}{}", modifier_str, ty.print())
370                 }
371             }
372         })
373     }
374 }
375
376 impl clean::GenericArgs {
377     fn print(&self) -> impl fmt::Display + '_ {
378         display_fn(move |f| {
379             match *self {
380                 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
381                     if !args.is_empty() || !bindings.is_empty() {
382                         if f.alternate() {
383                             f.write_str("<")?;
384                         } else {
385                             f.write_str("&lt;")?;
386                         }
387                         let mut comma = false;
388                         for arg in args {
389                             if comma {
390                                 f.write_str(", ")?;
391                             }
392                             comma = true;
393                             if f.alternate() {
394                                 write!(f, "{:#}", arg.print())?;
395                             } else {
396                                 write!(f, "{}", arg.print())?;
397                             }
398                         }
399                         for binding in bindings {
400                             if comma {
401                                 f.write_str(", ")?;
402                             }
403                             comma = true;
404                             if f.alternate() {
405                                 write!(f, "{:#}", binding.print())?;
406                             } else {
407                                 write!(f, "{}", binding.print())?;
408                             }
409                         }
410                         if f.alternate() {
411                             f.write_str(">")?;
412                         } else {
413                             f.write_str("&gt;")?;
414                         }
415                     }
416                 }
417                 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
418                     f.write_str("(")?;
419                     let mut comma = false;
420                     for ty in inputs {
421                         if comma {
422                             f.write_str(", ")?;
423                         }
424                         comma = true;
425                         if f.alternate() {
426                             write!(f, "{:#}", ty.print())?;
427                         } else {
428                             write!(f, "{}", ty.print())?;
429                         }
430                     }
431                     f.write_str(")")?;
432                     if let Some(ref ty) = *output {
433                         if f.alternate() {
434                             write!(f, " -> {:#}", ty.print())?;
435                         } else {
436                             write!(f, " -&gt; {}", ty.print())?;
437                         }
438                     }
439                 }
440             }
441             Ok(())
442         })
443     }
444 }
445
446 impl clean::PathSegment {
447     crate fn print(&self) -> impl fmt::Display + '_ {
448         display_fn(move |f| {
449             f.write_str(&self.name)?;
450             if f.alternate() {
451                 write!(f, "{:#}", self.args.print())
452             } else {
453                 write!(f, "{}", self.args.print())
454             }
455         })
456     }
457 }
458
459 impl clean::Path {
460     crate fn print(&self) -> impl fmt::Display + '_ {
461         display_fn(move |f| {
462             if self.global {
463                 f.write_str("::")?
464             }
465
466             for (i, seg) in self.segments.iter().enumerate() {
467                 if i > 0 {
468                     f.write_str("::")?
469                 }
470                 if f.alternate() {
471                     write!(f, "{:#}", seg.print())?;
472                 } else {
473                     write!(f, "{}", seg.print())?;
474                 }
475             }
476             Ok(())
477         })
478     }
479 }
480
481 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
482     let cache = cache();
483     if !did.is_local() && !cache.access_levels.is_public(did) {
484         return None;
485     }
486
487     let depth = CURRENT_DEPTH.with(|l| l.get());
488     let (fqp, shortty, mut url) = match cache.paths.get(&did) {
489         Some(&(ref fqp, shortty)) => (fqp, shortty, "../".repeat(depth)),
490         None => {
491             let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
492             (
493                 fqp,
494                 shortty,
495                 match cache.extern_locations[&did.krate] {
496                     (.., render::Remote(ref s)) => s.to_string(),
497                     (.., render::Local) => "../".repeat(depth),
498                     (.., render::Unknown) => return None,
499                 },
500             )
501         }
502     };
503     for component in &fqp[..fqp.len() - 1] {
504         url.push_str(component);
505         url.push_str("/");
506     }
507     match shortty {
508         ItemType::Module => {
509             url.push_str(fqp.last().unwrap());
510             url.push_str("/index.html");
511         }
512         _ => {
513             url.push_str(shortty.as_str());
514             url.push_str(".");
515             url.push_str(fqp.last().unwrap());
516             url.push_str(".html");
517         }
518     }
519     Some((url, shortty, fqp.to_vec()))
520 }
521
522 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
523 /// rendering function with the necessary arguments for linking to a local path.
524 fn resolved_path(
525     w: &mut fmt::Formatter<'_>,
526     did: DefId,
527     path: &clean::Path,
528     print_all: bool,
529     use_absolute: bool,
530 ) -> fmt::Result {
531     let last = path.segments.last().unwrap();
532
533     if print_all {
534         for seg in &path.segments[..path.segments.len() - 1] {
535             write!(w, "{}::", seg.name)?;
536         }
537     }
538     if w.alternate() {
539         write!(w, "{}{:#}", &last.name, last.args.print())?;
540     } else {
541         let path = if use_absolute {
542             if let Some((_, _, fqp)) = href(did) {
543                 format!("{}::{}", fqp[..fqp.len() - 1].join("::"), anchor(did, fqp.last().unwrap()))
544             } else {
545                 last.name.to_string()
546             }
547         } else {
548             anchor(did, &last.name).to_string()
549         };
550         write!(w, "{}{}", path, last.args.print())?;
551     }
552     Ok(())
553 }
554
555 fn primitive_link(
556     f: &mut fmt::Formatter<'_>,
557     prim: clean::PrimitiveType,
558     name: &str,
559 ) -> fmt::Result {
560     let m = cache();
561     let mut needs_termination = false;
562     if !f.alternate() {
563         match m.primitive_locations.get(&prim) {
564             Some(&def_id) if def_id.is_local() => {
565                 let len = CURRENT_DEPTH.with(|s| s.get());
566                 let len = if len == 0 { 0 } else { len - 1 };
567                 write!(
568                     f,
569                     "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
570                     "../".repeat(len),
571                     prim.to_url_str()
572                 )?;
573                 needs_termination = true;
574             }
575             Some(&def_id) => {
576                 let loc = match m.extern_locations[&def_id.krate] {
577                     (ref cname, _, render::Remote(ref s)) => Some((cname, s.to_string())),
578                     (ref cname, _, render::Local) => {
579                         let len = CURRENT_DEPTH.with(|s| s.get());
580                         Some((cname, "../".repeat(len)))
581                     }
582                     (.., render::Unknown) => None,
583                 };
584                 if let Some((cname, root)) = loc {
585                     write!(
586                         f,
587                         "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
588                         root,
589                         cname,
590                         prim.to_url_str()
591                     )?;
592                     needs_termination = true;
593                 }
594             }
595             None => {}
596         }
597     }
598     write!(f, "{}", name)?;
599     if needs_termination {
600         write!(f, "</a>")?;
601     }
602     Ok(())
603 }
604
605 /// Helper to render type parameters
606 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
607     display_fn(move |f| match *param_names {
608         Some(ref params) => {
609             for param in params {
610                 write!(f, " + ")?;
611                 fmt::Display::fmt(&param.print(), f)?;
612             }
613             Ok(())
614         }
615         None => Ok(()),
616     })
617 }
618
619 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
620     display_fn(move |f| {
621         if let Some((url, short_ty, fqp)) = href(did) {
622             write!(
623                 f,
624                 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
625                 short_ty,
626                 url,
627                 short_ty,
628                 fqp.join("::"),
629                 text
630             )
631         } else {
632             write!(f, "{}", text)
633         }
634     })
635 }
636
637 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
638     match *t {
639         clean::Generic(ref name) => f.write_str(name),
640         clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
641             if param_names.is_some() {
642                 f.write_str("dyn ")?;
643             }
644             // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
645             resolved_path(f, did, path, is_generic, use_absolute)?;
646             fmt::Display::fmt(&tybounds(param_names), f)
647         }
648         clean::Infer => write!(f, "_"),
649         clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
650         clean::BareFunction(ref decl) => {
651             if f.alternate() {
652                 write!(
653                     f,
654                     "{}{:#}fn{:#}{:#}",
655                     decl.unsafety.print_with_space(),
656                     print_abi_with_space(decl.abi),
657                     decl.print_generic_params(),
658                     decl.decl.print()
659                 )
660             } else {
661                 write!(
662                     f,
663                     "{}{}",
664                     decl.unsafety.print_with_space(),
665                     print_abi_with_space(decl.abi)
666                 )?;
667                 primitive_link(f, PrimitiveType::Fn, "fn")?;
668                 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
669             }
670         }
671         clean::Tuple(ref typs) => {
672             match &typs[..] {
673                 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
674                 &[ref one] => {
675                     primitive_link(f, PrimitiveType::Tuple, "(")?;
676                     // Carry `f.alternate()` into this display w/o branching manually.
677                     fmt::Display::fmt(&one.print(), f)?;
678                     primitive_link(f, PrimitiveType::Tuple, ",)")
679                 }
680                 many => {
681                     primitive_link(f, PrimitiveType::Tuple, "(")?;
682                     for (i, item) in many.iter().enumerate() {
683                         if i != 0 {
684                             write!(f, ", ")?;
685                         }
686                         fmt::Display::fmt(&item.print(), f)?;
687                     }
688                     primitive_link(f, PrimitiveType::Tuple, ")")
689                 }
690             }
691         }
692         clean::Slice(ref t) => {
693             primitive_link(f, PrimitiveType::Slice, "[")?;
694             fmt::Display::fmt(&t.print(), f)?;
695             primitive_link(f, PrimitiveType::Slice, "]")
696         }
697         clean::Array(ref t, ref n) => {
698             primitive_link(f, PrimitiveType::Array, "[")?;
699             fmt::Display::fmt(&t.print(), f)?;
700             if f.alternate() {
701                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
702             } else {
703                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)))
704             }
705         }
706         clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
707         clean::RawPointer(m, ref t) => {
708             let m = match m {
709                 hir::Mutability::Mut => "mut",
710                 hir::Mutability::Not => "const",
711             };
712             match **t {
713                 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
714                     if f.alternate() {
715                         primitive_link(
716                             f,
717                             clean::PrimitiveType::RawPointer,
718                             &format!("*{} {:#}", m, t.print()),
719                         )
720                     } else {
721                         primitive_link(
722                             f,
723                             clean::PrimitiveType::RawPointer,
724                             &format!("*{} {}", m, t.print()),
725                         )
726                     }
727                 }
728                 _ => {
729                     primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
730                     fmt::Display::fmt(&t.print(), f)
731                 }
732             }
733         }
734         clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
735             let lt = match l {
736                 Some(l) => format!("{} ", l.print()),
737                 _ => String::new(),
738             };
739             let m = mutability.print_with_space();
740             let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
741             match **ty {
742                 clean::Slice(ref bt) => {
743                     // `BorrowedRef{ ... Slice(T) }` is `&[T]`
744                     match **bt {
745                         clean::Generic(_) => {
746                             if f.alternate() {
747                                 primitive_link(
748                                     f,
749                                     PrimitiveType::Slice,
750                                     &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()),
751                                 )
752                             } else {
753                                 primitive_link(
754                                     f,
755                                     PrimitiveType::Slice,
756                                     &format!("{}{}{}[{}]", amp, lt, m, bt.print()),
757                                 )
758                             }
759                         }
760                         _ => {
761                             primitive_link(
762                                 f,
763                                 PrimitiveType::Slice,
764                                 &format!("{}{}{}[", amp, lt, m),
765                             )?;
766                             if f.alternate() {
767                                 write!(f, "{:#}", bt.print())?;
768                             } else {
769                                 write!(f, "{}", bt.print())?;
770                             }
771                             primitive_link(f, PrimitiveType::Slice, "]")
772                         }
773                     }
774                 }
775                 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
776                     write!(f, "{}{}{}(", amp, lt, m)?;
777                     fmt_type(&ty, f, use_absolute)?;
778                     write!(f, ")")
779                 }
780                 clean::Generic(..) => {
781                     primitive_link(f, PrimitiveType::Reference, &format!("{}{}{}", amp, lt, m))?;
782                     fmt_type(&ty, f, use_absolute)
783                 }
784                 _ => {
785                     write!(f, "{}{}{}", amp, lt, m)?;
786                     fmt_type(&ty, f, use_absolute)
787                 }
788             }
789         }
790         clean::ImplTrait(ref bounds) => {
791             if f.alternate() {
792                 write!(f, "impl {:#}", print_generic_bounds(bounds))
793             } else {
794                 write!(f, "impl {}", print_generic_bounds(bounds))
795             }
796         }
797         clean::QPath { ref name, ref self_type, ref trait_ } => {
798             let should_show_cast = match *trait_ {
799                 box clean::ResolvedPath { ref path, .. } => {
800                     !path.segments.is_empty() && !self_type.is_self_type()
801                 }
802                 _ => true,
803             };
804             if f.alternate() {
805                 if should_show_cast {
806                     write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
807                 } else {
808                     write!(f, "{:#}::", self_type.print())?
809                 }
810             } else {
811                 if should_show_cast {
812                     write!(f, "&lt;{} as {}&gt;::", self_type.print(), trait_.print())?
813                 } else {
814                     write!(f, "{}::", self_type.print())?
815                 }
816             };
817             match *trait_ {
818                 // It's pretty unsightly to look at `<A as B>::C` in output, and
819                 // we've got hyperlinking on our side, so try to avoid longer
820                 // notation as much as possible by making `C` a hyperlink to trait
821                 // `B` to disambiguate.
822                 //
823                 // FIXME: this is still a lossy conversion and there should probably
824                 //        be a better way of representing this in general? Most of
825                 //        the ugliness comes from inlining across crates where
826                 //        everything comes in as a fully resolved QPath (hard to
827                 //        look at).
828                 box clean::ResolvedPath { did, ref param_names, .. } => {
829                     match href(did) {
830                         Some((ref url, _, ref path)) if !f.alternate() => {
831                             write!(
832                                 f,
833                                 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
834                                    title=\"type {path}::{name}\">{name}</a>",
835                                 url = url,
836                                 shortty = ItemType::AssocType,
837                                 name = name,
838                                 path = path.join("::")
839                             )?;
840                         }
841                         _ => write!(f, "{}", name)?,
842                     }
843
844                     // FIXME: `param_names` are not rendered, and this seems bad?
845                     drop(param_names);
846                     Ok(())
847                 }
848                 _ => write!(f, "{}", name),
849             }
850         }
851     }
852 }
853
854 impl clean::Type {
855     crate fn print(&self) -> impl fmt::Display + '_ {
856         display_fn(move |f| fmt_type(self, f, false))
857     }
858 }
859
860 impl clean::Impl {
861     crate fn print(&self) -> impl fmt::Display + '_ {
862         self.print_inner(true, false)
863     }
864
865     fn print_inner(&self, link_trait: bool, use_absolute: bool) -> impl fmt::Display + '_ {
866         display_fn(move |f| {
867             if f.alternate() {
868                 write!(f, "impl{:#} ", self.generics.print())?;
869             } else {
870                 write!(f, "impl{} ", self.generics.print())?;
871             }
872
873             if let Some(ref ty) = self.trait_ {
874                 if self.polarity == Some(clean::ImplPolarity::Negative) {
875                     write!(f, "!")?;
876                 }
877
878                 if link_trait {
879                     fmt::Display::fmt(&ty.print(), f)?;
880                 } else {
881                     match ty {
882                         clean::ResolvedPath {
883                             param_names: None, path, is_generic: false, ..
884                         } => {
885                             let last = path.segments.last().unwrap();
886                             fmt::Display::fmt(&last.name, f)?;
887                             fmt::Display::fmt(&last.args.print(), f)?;
888                         }
889                         _ => unreachable!(),
890                     }
891                 }
892                 write!(f, " for ")?;
893             }
894
895             if let Some(ref ty) = self.blanket_impl {
896                 fmt_type(ty, f, use_absolute)?;
897             } else {
898                 fmt_type(&self.for_, f, use_absolute)?;
899             }
900
901             fmt::Display::fmt(
902                 &WhereClause { gens: &self.generics, indent: 0, end_newline: true },
903                 f,
904             )?;
905             Ok(())
906         })
907     }
908 }
909
910 // The difference from above is that trait is not hyperlinked.
911 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) {
912     f.from_display(i.print_inner(false, use_absolute))
913 }
914
915 impl clean::Arguments {
916     crate fn print(&self) -> impl fmt::Display + '_ {
917         display_fn(move |f| {
918             for (i, input) in self.values.iter().enumerate() {
919                 if !input.name.is_empty() {
920                     write!(f, "{}: ", input.name)?;
921                 }
922                 if f.alternate() {
923                     write!(f, "{:#}", input.type_.print())?;
924                 } else {
925                     write!(f, "{}", input.type_.print())?;
926                 }
927                 if i + 1 < self.values.len() {
928                     write!(f, ", ")?;
929                 }
930             }
931             Ok(())
932         })
933     }
934 }
935
936 impl clean::FnRetTy {
937     crate fn print(&self) -> impl fmt::Display + '_ {
938         display_fn(move |f| match self {
939             clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
940             clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
941             clean::Return(ty) => write!(f, " -&gt; {}", ty.print()),
942             clean::DefaultReturn => Ok(()),
943         })
944     }
945 }
946
947 impl clean::BareFunctionDecl {
948     fn print_generic_params(&self) -> impl fmt::Display + '_ {
949         comma_sep(self.generic_params.iter().map(|g| g.print()))
950     }
951 }
952
953 impl clean::FnDecl {
954     crate fn print(&self) -> impl fmt::Display + '_ {
955         display_fn(move |f| {
956             let ellipsis = if self.c_variadic { ", ..." } else { "" };
957             if f.alternate() {
958                 write!(
959                     f,
960                     "({args:#}{ellipsis}){arrow:#}",
961                     args = self.inputs.print(),
962                     ellipsis = ellipsis,
963                     arrow = self.output.print()
964                 )
965             } else {
966                 write!(
967                     f,
968                     "({args}{ellipsis}){arrow}",
969                     args = self.inputs.print(),
970                     ellipsis = ellipsis,
971                     arrow = self.output.print()
972                 )
973             }
974         })
975     }
976 }
977
978 impl Function<'_> {
979     crate fn print(&self) -> impl fmt::Display + '_ {
980         display_fn(move |f| {
981             let &Function { decl, header_len, indent, asyncness } = self;
982             let amp = if f.alternate() { "&" } else { "&amp;" };
983             let mut args = String::new();
984             let mut args_plain = String::new();
985             for (i, input) in decl.inputs.values.iter().enumerate() {
986                 if i == 0 {
987                     args.push_str("<br>");
988                 }
989
990                 if let Some(selfty) = input.to_self() {
991                     match selfty {
992                         clean::SelfValue => {
993                             args.push_str("self");
994                             args_plain.push_str("self");
995                         }
996                         clean::SelfBorrowed(Some(ref lt), mtbl) => {
997                             args.push_str(&format!(
998                                 "{}{} {}self",
999                                 amp,
1000                                 lt.print(),
1001                                 mtbl.print_with_space()
1002                             ));
1003                             args_plain.push_str(&format!(
1004                                 "&{} {}self",
1005                                 lt.print(),
1006                                 mtbl.print_with_space()
1007                             ));
1008                         }
1009                         clean::SelfBorrowed(None, mtbl) => {
1010                             args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1011                             args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1012                         }
1013                         clean::SelfExplicit(ref typ) => {
1014                             if f.alternate() {
1015                                 args.push_str(&format!("self: {:#}", typ.print()));
1016                             } else {
1017                                 args.push_str(&format!("self: {}", typ.print()));
1018                             }
1019                             args_plain.push_str(&format!("self: {:#}", typ.print()));
1020                         }
1021                     }
1022                 } else {
1023                     if i > 0 {
1024                         args.push_str(" <br>");
1025                         args_plain.push_str(" ");
1026                     }
1027                     if !input.name.is_empty() {
1028                         args.push_str(&format!("{}: ", input.name));
1029                         args_plain.push_str(&format!("{}: ", input.name));
1030                     }
1031
1032                     if f.alternate() {
1033                         args.push_str(&format!("{:#}", input.type_.print()));
1034                     } else {
1035                         args.push_str(&input.type_.print().to_string());
1036                     }
1037                     args_plain.push_str(&format!("{:#}", input.type_.print()));
1038                 }
1039                 if i + 1 < decl.inputs.values.len() {
1040                     args.push(',');
1041                     args_plain.push(',');
1042                 }
1043             }
1044
1045             let mut args_plain = format!("({})", args_plain);
1046
1047             if decl.c_variadic {
1048                 args.push_str(",<br> ...");
1049                 args_plain.push_str(", ...");
1050             }
1051
1052             let output = if let hir::IsAsync::Async = asyncness {
1053                 Cow::Owned(decl.sugared_async_return_type())
1054             } else {
1055                 Cow::Borrowed(&decl.output)
1056             };
1057
1058             let arrow_plain = format!("{:#}", &output.print());
1059             let arrow = if f.alternate() {
1060                 format!("{:#}", &output.print())
1061             } else {
1062                 output.print().to_string()
1063             };
1064
1065             let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1066             let output = if declaration_len > 80 {
1067                 let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1068                 let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1069                 format!(
1070                     "({args}{close}){arrow}",
1071                     args = args.replace("<br>", &full_pad),
1072                     close = close_pad,
1073                     arrow = arrow
1074                 )
1075             } else {
1076                 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1077             };
1078
1079             if f.alternate() {
1080                 write!(f, "{}", output.replace("<br>", "\n"))
1081             } else {
1082                 write!(f, "{}", output)
1083             }
1084         })
1085     }
1086 }
1087
1088 impl clean::Visibility {
1089     crate fn print_with_space(&self) -> impl fmt::Display + '_ {
1090         display_fn(move |f| match *self {
1091             clean::Public => f.write_str("pub "),
1092             clean::Inherited => Ok(()),
1093             clean::Visibility::Crate => write!(f, "pub(crate) "),
1094             clean::Visibility::Restricted(did, ref path) => {
1095                 f.write_str("pub(")?;
1096                 if path.segments.len() != 1
1097                     || (path.segments[0].name != "self" && path.segments[0].name != "super")
1098                 {
1099                     f.write_str("in ")?;
1100                 }
1101                 resolved_path(f, did, path, true, false)?;
1102                 f.write_str(") ")
1103             }
1104         })
1105     }
1106 }
1107
1108 crate trait PrintWithSpace {
1109     fn print_with_space(&self) -> &str;
1110 }
1111
1112 impl PrintWithSpace for hir::Unsafety {
1113     fn print_with_space(&self) -> &str {
1114         match self {
1115             hir::Unsafety::Unsafe => "unsafe ",
1116             hir::Unsafety::Normal => "",
1117         }
1118     }
1119 }
1120
1121 impl PrintWithSpace for hir::Constness {
1122     fn print_with_space(&self) -> &str {
1123         match self {
1124             hir::Constness::Const => "const ",
1125             hir::Constness::NotConst => "",
1126         }
1127     }
1128 }
1129
1130 impl PrintWithSpace for hir::IsAsync {
1131     fn print_with_space(&self) -> &str {
1132         match self {
1133             hir::IsAsync::Async => "async ",
1134             hir::IsAsync::NotAsync => "",
1135         }
1136     }
1137 }
1138
1139 impl PrintWithSpace for hir::Mutability {
1140     fn print_with_space(&self) -> &str {
1141         match self {
1142             hir::Mutability::Not => "",
1143             hir::Mutability::Mut => "mut ",
1144         }
1145     }
1146 }
1147
1148 impl clean::Import {
1149     crate fn print(&self) -> impl fmt::Display + '_ {
1150         display_fn(move |f| match *self {
1151             clean::Import::Simple(ref name, ref src) => {
1152                 if *name == src.path.last_name() {
1153                     write!(f, "use {};", src.print())
1154                 } else {
1155                     write!(f, "use {} as {};", src.print(), *name)
1156                 }
1157             }
1158             clean::Import::Glob(ref src) => {
1159                 if src.path.segments.is_empty() {
1160                     write!(f, "use *;")
1161                 } else {
1162                     write!(f, "use {}::*;", src.print())
1163                 }
1164             }
1165         })
1166     }
1167 }
1168
1169 impl clean::ImportSource {
1170     crate fn print(&self) -> impl fmt::Display + '_ {
1171         display_fn(move |f| match self.did {
1172             Some(did) => resolved_path(f, did, &self.path, true, false),
1173             _ => {
1174                 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1175                     write!(f, "{}::", seg.name)?;
1176                 }
1177                 let name = self.path.last_name();
1178                 if let hir::def::Res::PrimTy(p) = self.path.res {
1179                     primitive_link(f, PrimitiveType::from(p), name)?;
1180                 } else {
1181                     write!(f, "{}", name)?;
1182                 }
1183                 Ok(())
1184             }
1185         })
1186     }
1187 }
1188
1189 impl clean::TypeBinding {
1190     crate fn print(&self) -> impl fmt::Display + '_ {
1191         display_fn(move |f| {
1192             f.write_str(&self.name)?;
1193             match self.kind {
1194                 clean::TypeBindingKind::Equality { ref ty } => {
1195                     if f.alternate() {
1196                         write!(f, " = {:#}", ty.print())?;
1197                     } else {
1198                         write!(f, " = {}", ty.print())?;
1199                     }
1200                 }
1201                 clean::TypeBindingKind::Constraint { ref bounds } => {
1202                     if !bounds.is_empty() {
1203                         if f.alternate() {
1204                             write!(f, ": {:#}", print_generic_bounds(bounds))?;
1205                         } else {
1206                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds))?;
1207                         }
1208                     }
1209                 }
1210             }
1211             Ok(())
1212         })
1213     }
1214 }
1215
1216 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1217     display_fn(move |f| {
1218         let quot = if f.alternate() { "\"" } else { "&quot;" };
1219         match abi {
1220             Abi::Rust => Ok(()),
1221             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1222         }
1223     })
1224 }
1225
1226 crate fn print_default_space<'a>(v: bool) -> &'a str {
1227     if v { "default " } else { "" }
1228 }
1229
1230 impl clean::GenericArg {
1231     crate fn print(&self) -> impl fmt::Display + '_ {
1232         display_fn(move |f| match self {
1233             clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1234             clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1235             clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1236         })
1237     }
1238 }
1239
1240 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1241     WithFormatter(Cell::new(Some(f)))
1242 }
1243
1244 struct WithFormatter<F>(Cell<Option<F>>);
1245
1246 impl<F> fmt::Display for WithFormatter<F>
1247 where
1248     F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1249 {
1250     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251         (self.0.take()).unwrap()(f)
1252     }
1253 }