]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Rollup merge of #96334 - devnexen:socket_mark, r=dtolnay
[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 use std::iter::{self, once};
12
13 use rustc_ast as ast;
14 use rustc_attr::{ConstStability, StabilityLevel};
15 use rustc_data_structures::captures::Captures;
16 use rustc_data_structures::fx::FxHashSet;
17 use rustc_hir as hir;
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_metadata::creader::{CStore, LoadedMacro};
21 use rustc_middle::ty;
22 use rustc_middle::ty::DefIdTree;
23 use rustc_middle::ty::TyCtxt;
24 use rustc_span::symbol::kw;
25 use rustc_span::{sym, Symbol};
26 use rustc_target::spec::abi::Abi;
27
28 use itertools::Itertools;
29
30 use crate::clean::{
31     self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
32     PrimitiveType,
33 };
34 use crate::formats::item_type::ItemType;
35 use crate::html::escape::Escape;
36 use crate::html::render::Context;
37
38 use super::url_parts_builder::estimate_item_path_byte_length;
39 use super::url_parts_builder::UrlPartsBuilder;
40
41 pub(crate) trait Print {
42     fn print(self, buffer: &mut Buffer);
43 }
44
45 impl<F> Print for F
46 where
47     F: FnOnce(&mut Buffer),
48 {
49     fn print(self, buffer: &mut Buffer) {
50         (self)(buffer)
51     }
52 }
53
54 impl Print for String {
55     fn print(self, buffer: &mut Buffer) {
56         buffer.write_str(&self);
57     }
58 }
59
60 impl Print for &'_ str {
61     fn print(self, buffer: &mut Buffer) {
62         buffer.write_str(self);
63     }
64 }
65
66 #[derive(Debug, Clone)]
67 pub(crate) struct Buffer {
68     for_html: bool,
69     buffer: String,
70 }
71
72 impl core::fmt::Write for Buffer {
73     #[inline]
74     fn write_str(&mut self, s: &str) -> fmt::Result {
75         self.buffer.write_str(s)
76     }
77
78     #[inline]
79     fn write_char(&mut self, c: char) -> fmt::Result {
80         self.buffer.write_char(c)
81     }
82
83     #[inline]
84     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
85         self.buffer.write_fmt(args)
86     }
87 }
88
89 impl Buffer {
90     pub(crate) fn empty_from(v: &Buffer) -> Buffer {
91         Buffer { for_html: v.for_html, buffer: String::new() }
92     }
93
94     pub(crate) fn html() -> Buffer {
95         Buffer { for_html: true, buffer: String::new() }
96     }
97
98     pub(crate) fn new() -> Buffer {
99         Buffer { for_html: false, buffer: String::new() }
100     }
101
102     pub(crate) fn is_empty(&self) -> bool {
103         self.buffer.is_empty()
104     }
105
106     pub(crate) fn into_inner(self) -> String {
107         self.buffer
108     }
109
110     pub(crate) fn insert_str(&mut self, idx: usize, s: &str) {
111         self.buffer.insert_str(idx, s);
112     }
113
114     pub(crate) fn push_str(&mut self, s: &str) {
115         self.buffer.push_str(s);
116     }
117
118     pub(crate) fn push_buffer(&mut self, other: Buffer) {
119         self.buffer.push_str(&other.buffer);
120     }
121
122     // Intended for consumption by write! and writeln! (std::fmt) but without
123     // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
124     // import).
125     pub(crate) fn write_str(&mut self, s: &str) {
126         self.buffer.push_str(s);
127     }
128
129     // Intended for consumption by write! and writeln! (std::fmt) but without
130     // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
131     // import).
132     pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
133         use fmt::Write;
134         self.buffer.write_fmt(v).unwrap();
135     }
136
137     pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
138         t.print(&mut self);
139         self.into_inner()
140     }
141
142     pub(crate) fn is_for_html(&self) -> bool {
143         self.for_html
144     }
145
146     pub(crate) fn reserve(&mut self, additional: usize) {
147         self.buffer.reserve(additional)
148     }
149
150     pub(crate) fn len(&self) -> usize {
151         self.buffer.len()
152     }
153 }
154
155 pub(crate) fn comma_sep<T: fmt::Display>(
156     items: impl Iterator<Item = T>,
157     space_after_comma: bool,
158 ) -> impl fmt::Display {
159     display_fn(move |f| {
160         for (i, item) in items.enumerate() {
161             if i != 0 {
162                 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
163             }
164             fmt::Display::fmt(&item, f)?;
165         }
166         Ok(())
167     })
168 }
169
170 pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
171     bounds: &'a [clean::GenericBound],
172     cx: &'a Context<'tcx>,
173 ) -> impl fmt::Display + 'a + Captures<'tcx> {
174     display_fn(move |f| {
175         let mut bounds_dup = FxHashSet::default();
176
177         for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
178             if i > 0 {
179                 f.write_str(" + ")?;
180             }
181             fmt::Display::fmt(&bound.print(cx), f)?;
182         }
183         Ok(())
184     })
185 }
186
187 impl clean::GenericParamDef {
188     pub(crate) fn print<'a, 'tcx: 'a>(
189         &'a self,
190         cx: &'a Context<'tcx>,
191     ) -> impl fmt::Display + 'a + Captures<'tcx> {
192         display_fn(move |f| match &self.kind {
193             clean::GenericParamDefKind::Lifetime { outlives } => {
194                 write!(f, "{}", self.name)?;
195
196                 if !outlives.is_empty() {
197                     f.write_str(": ")?;
198                     for (i, lt) in outlives.iter().enumerate() {
199                         if i != 0 {
200                             f.write_str(" + ")?;
201                         }
202                         write!(f, "{}", lt.print())?;
203                     }
204                 }
205
206                 Ok(())
207             }
208             clean::GenericParamDefKind::Type { bounds, default, .. } => {
209                 f.write_str(self.name.as_str())?;
210
211                 if !bounds.is_empty() {
212                     if f.alternate() {
213                         write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
214                     } else {
215                         write!(f, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
216                     }
217                 }
218
219                 if let Some(ref ty) = default {
220                     if f.alternate() {
221                         write!(f, " = {:#}", ty.print(cx))?;
222                     } else {
223                         write!(f, "&nbsp;=&nbsp;{}", ty.print(cx))?;
224                     }
225                 }
226
227                 Ok(())
228             }
229             clean::GenericParamDefKind::Const { ty, default, .. } => {
230                 if f.alternate() {
231                     write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
232                 } else {
233                     write!(f, "const {}:&nbsp;{}", self.name, ty.print(cx))?;
234                 }
235
236                 if let Some(default) = default {
237                     if f.alternate() {
238                         write!(f, " = {:#}", default)?;
239                     } else {
240                         write!(f, "&nbsp;=&nbsp;{}", default)?;
241                     }
242                 }
243
244                 Ok(())
245             }
246         })
247     }
248 }
249
250 impl clean::Generics {
251     pub(crate) fn print<'a, 'tcx: 'a>(
252         &'a self,
253         cx: &'a Context<'tcx>,
254     ) -> impl fmt::Display + 'a + Captures<'tcx> {
255         display_fn(move |f| {
256             let mut real_params =
257                 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
258             if real_params.peek().is_none() {
259                 return Ok(());
260             }
261
262             if f.alternate() {
263                 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
264             } else {
265                 write!(f, "&lt;{}&gt;", comma_sep(real_params.map(|g| g.print(cx)), true))
266             }
267         })
268     }
269 }
270
271 #[derive(Clone, Copy, PartialEq, Eq)]
272 pub(crate) enum Ending {
273     Newline,
274     NoNewline,
275 }
276
277 /// * The Generics from which to emit a where-clause.
278 /// * The number of spaces to indent each line with.
279 /// * Whether the where-clause needs to add a comma and newline after the last bound.
280 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
281     gens: &'a clean::Generics,
282     cx: &'a Context<'tcx>,
283     indent: usize,
284     ending: Ending,
285 ) -> impl fmt::Display + 'a + Captures<'tcx> {
286     use fmt::Write;
287
288     display_fn(move |f| {
289         let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
290             !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
291         }).map(|pred| {
292             display_fn(move |f| {
293                 if f.alternate() {
294                     f.write_str(" ")?;
295                 } else {
296                     f.write_str("<br>")?;
297                 }
298
299                 match pred {
300                     clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
301                         let ty_cx = ty.print(cx);
302                         let generic_bounds = print_generic_bounds(bounds, cx);
303
304                         if bound_params.is_empty() {
305                             if f.alternate() {
306                                 write!(f, "{ty_cx:#}: {generic_bounds:#}")
307                             } else {
308                                 write!(f, "{ty_cx}: {generic_bounds}")
309                             }
310                         } else {
311                             if f.alternate() {
312                                 write!(
313                                     f,
314                                     "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
315                                     comma_sep(bound_params.iter().map(|lt| lt.print()), true)
316                                 )
317                             } else {
318                                 write!(
319                                     f,
320                                     "for&lt;{}&gt; {ty_cx}: {generic_bounds}",
321                                     comma_sep(bound_params.iter().map(|lt| lt.print()), true)
322                                 )
323                             }
324                         }
325                     }
326                     clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
327                         let mut bounds_display = String::new();
328                         for bound in bounds.iter().map(|b| b.print(cx)) {
329                             write!(bounds_display, "{bound} + ")?;
330                         }
331                         bounds_display.truncate(bounds_display.len() - " + ".len());
332                         write!(f, "{}: {bounds_display}", lifetime.print())
333                     }
334                     clean::WherePredicate::EqPredicate { lhs, rhs } => {
335                         if f.alternate() {
336                             write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
337                         } else {
338                             write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
339                         }
340                     }
341                 }
342             })
343         }).peekable();
344
345         if where_predicates.peek().is_none() {
346             return Ok(());
347         }
348
349         let where_preds = comma_sep(where_predicates, false);
350         let clause = if f.alternate() {
351             if ending == Ending::Newline {
352                 // add a space so stripping <br> tags and breaking spaces still renders properly
353                 format!(" where{where_preds}, ")
354             } else {
355                 format!(" where{where_preds}")
356             }
357         } else {
358             let mut br_with_padding = String::with_capacity(6 * indent + 28);
359             br_with_padding.push_str("<br>");
360             for _ in 0..indent + 4 {
361                 br_with_padding.push_str("&nbsp;");
362             }
363             let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
364
365             if ending == Ending::Newline {
366                 let mut clause = "&nbsp;".repeat(indent.saturating_sub(1));
367                 // add a space so stripping <br> tags and breaking spaces still renders properly
368                 write!(
369                     clause,
370                     " <span class=\"where fmt-newline\">where{where_preds},&nbsp;</span>"
371                 )?;
372                 clause
373             } else {
374                 // insert a <br> tag after a single space but before multiple spaces at the start
375                 if indent == 0 {
376                     format!(" <br><span class=\"where\">where{where_preds}</span>")
377                 } else {
378                     let mut clause = br_with_padding;
379                     clause.truncate(clause.len() - 5 * "&nbsp;".len());
380                     write!(clause, " <span class=\"where\">where{where_preds}</span>")?;
381                     clause
382                 }
383             }
384         };
385         write!(f, "{clause}")
386     })
387 }
388
389 impl clean::Lifetime {
390     pub(crate) fn print(&self) -> impl fmt::Display + '_ {
391         self.0.as_str()
392     }
393 }
394
395 impl clean::Constant {
396     pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
397         let expr = self.expr(tcx);
398         display_fn(
399             move |f| {
400                 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
401             },
402         )
403     }
404 }
405
406 impl clean::PolyTrait {
407     fn print<'a, 'tcx: 'a>(
408         &'a self,
409         cx: &'a Context<'tcx>,
410     ) -> impl fmt::Display + 'a + Captures<'tcx> {
411         display_fn(move |f| {
412             if !self.generic_params.is_empty() {
413                 if f.alternate() {
414                     write!(
415                         f,
416                         "for<{:#}> ",
417                         comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
418                     )?;
419                 } else {
420                     write!(
421                         f,
422                         "for&lt;{}&gt; ",
423                         comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
424                     )?;
425                 }
426             }
427             if f.alternate() {
428                 write!(f, "{:#}", self.trait_.print(cx))
429             } else {
430                 write!(f, "{}", self.trait_.print(cx))
431             }
432         })
433     }
434 }
435
436 impl clean::GenericBound {
437     pub(crate) fn print<'a, 'tcx: 'a>(
438         &'a self,
439         cx: &'a Context<'tcx>,
440     ) -> impl fmt::Display + 'a + Captures<'tcx> {
441         display_fn(move |f| match self {
442             clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
443             clean::GenericBound::TraitBound(ty, modifier) => {
444                 let modifier_str = match modifier {
445                     hir::TraitBoundModifier::None => "",
446                     hir::TraitBoundModifier::Maybe => "?",
447                     // ~const is experimental; do not display those bounds in rustdoc
448                     hir::TraitBoundModifier::MaybeConst => "",
449                 };
450                 if f.alternate() {
451                     write!(f, "{}{:#}", modifier_str, ty.print(cx))
452                 } else {
453                     write!(f, "{}{}", modifier_str, ty.print(cx))
454                 }
455             }
456         })
457     }
458 }
459
460 impl clean::GenericArgs {
461     fn print<'a, 'tcx: 'a>(
462         &'a self,
463         cx: &'a Context<'tcx>,
464     ) -> impl fmt::Display + 'a + Captures<'tcx> {
465         display_fn(move |f| {
466             match self {
467                 clean::GenericArgs::AngleBracketed { args, bindings } => {
468                     if !args.is_empty() || !bindings.is_empty() {
469                         if f.alternate() {
470                             f.write_str("<")?;
471                         } else {
472                             f.write_str("&lt;")?;
473                         }
474                         let mut comma = false;
475                         for arg in args.iter() {
476                             if comma {
477                                 f.write_str(", ")?;
478                             }
479                             comma = true;
480                             if f.alternate() {
481                                 write!(f, "{:#}", arg.print(cx))?;
482                             } else {
483                                 write!(f, "{}", arg.print(cx))?;
484                             }
485                         }
486                         for binding in bindings.iter() {
487                             if comma {
488                                 f.write_str(", ")?;
489                             }
490                             comma = true;
491                             if f.alternate() {
492                                 write!(f, "{:#}", binding.print(cx))?;
493                             } else {
494                                 write!(f, "{}", binding.print(cx))?;
495                             }
496                         }
497                         if f.alternate() {
498                             f.write_str(">")?;
499                         } else {
500                             f.write_str("&gt;")?;
501                         }
502                     }
503                 }
504                 clean::GenericArgs::Parenthesized { inputs, output } => {
505                     f.write_str("(")?;
506                     let mut comma = false;
507                     for ty in inputs.iter() {
508                         if comma {
509                             f.write_str(", ")?;
510                         }
511                         comma = true;
512                         if f.alternate() {
513                             write!(f, "{:#}", ty.print(cx))?;
514                         } else {
515                             write!(f, "{}", ty.print(cx))?;
516                         }
517                     }
518                     f.write_str(")")?;
519                     if let Some(ref ty) = *output {
520                         if f.alternate() {
521                             write!(f, " -> {:#}", ty.print(cx))?;
522                         } else {
523                             write!(f, " -&gt; {}", ty.print(cx))?;
524                         }
525                     }
526                 }
527             }
528             Ok(())
529         })
530     }
531 }
532
533 // Possible errors when computing href link source for a `DefId`
534 #[derive(PartialEq, Eq)]
535 pub(crate) enum HrefError {
536     /// This item is known to rustdoc, but from a crate that does not have documentation generated.
537     ///
538     /// This can only happen for non-local items.
539     ///
540     /// # Example
541     ///
542     /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
543     /// implements it for a local type.
544     /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
545     ///
546     /// ```sh
547     /// rustc a.rs --crate-type=lib
548     /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
549     /// ```
550     ///
551     /// Now, the associated items in the trait impl want to link to the corresponding item in the
552     /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
553     /// *documentation (was) not built*.
554     DocumentationNotBuilt,
555     /// This can only happen for non-local items when `--document-private-items` is not passed.
556     Private,
557     // Not in external cache, href link should be in same page
558     NotInExternalCache,
559 }
560
561 // Panics if `syms` is empty.
562 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
563     let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
564     s.push_str(syms[0].as_str());
565     for sym in &syms[1..] {
566         s.push_str("::");
567         s.push_str(sym.as_str());
568     }
569     s
570 }
571
572 /// This function is to get the external macro path because they are not in the cache used in
573 /// `href_with_root_path`.
574 fn generate_macro_def_id_path(
575     def_id: DefId,
576     cx: &Context<'_>,
577     root_path: Option<&str>,
578 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
579     let tcx = cx.shared.tcx;
580     let crate_name = tcx.crate_name(def_id.krate).to_string();
581     let cache = cx.cache();
582
583     let fqp: Vec<Symbol> = tcx
584         .def_path(def_id)
585         .data
586         .into_iter()
587         .filter_map(|elem| {
588             // extern blocks (and a few others things) have an empty name.
589             match elem.data.get_opt_name() {
590                 Some(s) if !s.is_empty() => Some(s),
591                 _ => None,
592             }
593         })
594         .collect();
595     let relative = fqp.iter().map(|elem| elem.to_string());
596     let cstore = CStore::from_tcx(tcx);
597     // We need this to prevent a `panic` when this function is used from intra doc links...
598     if !cstore.has_crate_data(def_id.krate) {
599         debug!("No data for crate {}", crate_name);
600         return Err(HrefError::NotInExternalCache);
601     }
602     // Check to see if it is a macro 2.0 or built-in macro.
603     // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
604     let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
605         LoadedMacro::MacroDef(def, _) => {
606             // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
607             matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
608         }
609         _ => false,
610     };
611
612     let mut path = if is_macro_2 {
613         once(crate_name.clone()).chain(relative).collect()
614     } else {
615         vec![crate_name.clone(), relative.last().unwrap()]
616     };
617     if path.len() < 2 {
618         // The minimum we can have is the crate name followed by the macro name. If shorter, then
619         // it means that that `relative` was empty, which is an error.
620         debug!("macro path cannot be empty!");
621         return Err(HrefError::NotInExternalCache);
622     }
623
624     if let Some(last) = path.last_mut() {
625         *last = format!("macro.{}.html", last);
626     }
627
628     let url = match cache.extern_locations[&def_id.krate] {
629         ExternalLocation::Remote(ref s) => {
630             // `ExternalLocation::Remote` always end with a `/`.
631             format!("{}{}", s, path.join("/"))
632         }
633         ExternalLocation::Local => {
634             // `root_path` always end with a `/`.
635             format!("{}{}/{}", root_path.unwrap_or(""), crate_name, path.join("/"))
636         }
637         ExternalLocation::Unknown => {
638             debug!("crate {} not in cache when linkifying macros", crate_name);
639             return Err(HrefError::NotInExternalCache);
640         }
641     };
642     Ok((url, ItemType::Macro, fqp))
643 }
644
645 pub(crate) fn href_with_root_path(
646     did: DefId,
647     cx: &Context<'_>,
648     root_path: Option<&str>,
649 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
650     let tcx = cx.tcx();
651     let def_kind = tcx.def_kind(did);
652     let did = match def_kind {
653         DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
654             // documented on their parent's page
655             tcx.parent(did)
656         }
657         _ => did,
658     };
659     let cache = cx.cache();
660     let relative_to = &cx.current;
661     fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
662         if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
663     }
664
665     if !did.is_local()
666         && !cache.access_levels.is_public(did)
667         && !cache.document_private
668         && !cache.primitive_locations.values().any(|&id| id == did)
669     {
670         return Err(HrefError::Private);
671     }
672
673     let mut is_remote = false;
674     let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
675         Some(&(ref fqp, shortty)) => (fqp, shortty, {
676             let module_fqp = to_module_fqp(shortty, fqp.as_slice());
677             debug!(?fqp, ?shortty, ?module_fqp);
678             href_relative_parts(module_fqp, relative_to).collect()
679         }),
680         None => {
681             if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
682                 let module_fqp = to_module_fqp(shortty, fqp);
683                 (
684                     fqp,
685                     shortty,
686                     match cache.extern_locations[&did.krate] {
687                         ExternalLocation::Remote(ref s) => {
688                             is_remote = true;
689                             let s = s.trim_end_matches('/');
690                             let mut builder = UrlPartsBuilder::singleton(s);
691                             builder.extend(module_fqp.iter().copied());
692                             builder
693                         }
694                         ExternalLocation::Local => {
695                             href_relative_parts(module_fqp, relative_to).collect()
696                         }
697                         ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
698                     },
699                 )
700             } else if matches!(def_kind, DefKind::Macro(_)) {
701                 return generate_macro_def_id_path(did, cx, root_path);
702             } else {
703                 return Err(HrefError::NotInExternalCache);
704             }
705         }
706     };
707     if !is_remote {
708         if let Some(root_path) = root_path {
709             let root = root_path.trim_end_matches('/');
710             url_parts.push_front(root);
711         }
712     }
713     debug!(?url_parts);
714     match shortty {
715         ItemType::Module => {
716             url_parts.push("index.html");
717         }
718         _ => {
719             let prefix = shortty.as_str();
720             let last = fqp.last().unwrap();
721             url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
722         }
723     }
724     Ok((url_parts.finish(), shortty, fqp.to_vec()))
725 }
726
727 pub(crate) fn href(
728     did: DefId,
729     cx: &Context<'_>,
730 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
731     href_with_root_path(did, cx, None)
732 }
733
734 /// Both paths should only be modules.
735 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
736 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
737 pub(crate) fn href_relative_parts<'fqp>(
738     fqp: &'fqp [Symbol],
739     relative_to_fqp: &[Symbol],
740 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
741     for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
742         // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
743         if f != r {
744             let dissimilar_part_count = relative_to_fqp.len() - i;
745             let fqp_module = &fqp[i..fqp.len()];
746             return Box::new(
747                 iter::repeat(sym::dotdot)
748                     .take(dissimilar_part_count)
749                     .chain(fqp_module.iter().copied()),
750             );
751         }
752     }
753     // e.g. linking to std::sync::atomic from std::sync
754     if relative_to_fqp.len() < fqp.len() {
755         Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
756     // e.g. linking to std::sync from std::sync::atomic
757     } else if fqp.len() < relative_to_fqp.len() {
758         let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
759         Box::new(iter::repeat(sym::dotdot).take(dissimilar_part_count))
760     // linking to the same module
761     } else {
762         Box::new(iter::empty())
763     }
764 }
765
766 /// Used to render a [`clean::Path`].
767 fn resolved_path<'cx>(
768     w: &mut fmt::Formatter<'_>,
769     did: DefId,
770     path: &clean::Path,
771     print_all: bool,
772     use_absolute: bool,
773     cx: &'cx Context<'_>,
774 ) -> fmt::Result {
775     let last = path.segments.last().unwrap();
776
777     if print_all {
778         for seg in &path.segments[..path.segments.len() - 1] {
779             write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
780         }
781     }
782     if w.alternate() {
783         write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
784     } else {
785         let path = if use_absolute {
786             if let Ok((_, _, fqp)) = href(did, cx) {
787                 format!(
788                     "{}::{}",
789                     join_with_double_colon(&fqp[..fqp.len() - 1]),
790                     anchor(did, *fqp.last().unwrap(), cx)
791                 )
792             } else {
793                 last.name.to_string()
794             }
795         } else {
796             anchor(did, last.name, cx).to_string()
797         };
798         write!(w, "{}{}", path, last.args.print(cx))?;
799     }
800     Ok(())
801 }
802
803 fn primitive_link(
804     f: &mut fmt::Formatter<'_>,
805     prim: clean::PrimitiveType,
806     name: &str,
807     cx: &Context<'_>,
808 ) -> fmt::Result {
809     primitive_link_fragment(f, prim, name, "", cx)
810 }
811
812 fn primitive_link_fragment(
813     f: &mut fmt::Formatter<'_>,
814     prim: clean::PrimitiveType,
815     name: &str,
816     fragment: &str,
817     cx: &Context<'_>,
818 ) -> fmt::Result {
819     let m = &cx.cache();
820     let mut needs_termination = false;
821     if !f.alternate() {
822         match m.primitive_locations.get(&prim) {
823             Some(&def_id) if def_id.is_local() => {
824                 let len = cx.current.len();
825                 let len = if len == 0 { 0 } else { len - 1 };
826                 write!(
827                     f,
828                     "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
829                     "../".repeat(len),
830                     prim.as_sym()
831                 )?;
832                 needs_termination = true;
833             }
834             Some(&def_id) => {
835                 let loc = match m.extern_locations[&def_id.krate] {
836                     ExternalLocation::Remote(ref s) => {
837                         let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
838                         let builder: UrlPartsBuilder =
839                             [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
840                                 .into_iter()
841                                 .collect();
842                         Some(builder)
843                     }
844                     ExternalLocation::Local => {
845                         let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
846                         Some(if cx.current.first() == Some(&cname_sym) {
847                             iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
848                         } else {
849                             iter::repeat(sym::dotdot)
850                                 .take(cx.current.len())
851                                 .chain(iter::once(cname_sym))
852                                 .collect()
853                         })
854                     }
855                     ExternalLocation::Unknown => None,
856                 };
857                 if let Some(mut loc) = loc {
858                     loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
859                     write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
860                     needs_termination = true;
861                 }
862             }
863             None => {}
864         }
865     }
866     write!(f, "{}", name)?;
867     if needs_termination {
868         write!(f, "</a>")?;
869     }
870     Ok(())
871 }
872
873 /// Helper to render type parameters
874 fn tybounds<'a, 'tcx: 'a>(
875     bounds: &'a [clean::PolyTrait],
876     lt: &'a Option<clean::Lifetime>,
877     cx: &'a Context<'tcx>,
878 ) -> impl fmt::Display + 'a + Captures<'tcx> {
879     display_fn(move |f| {
880         for (i, bound) in bounds.iter().enumerate() {
881             if i > 0 {
882                 write!(f, " + ")?;
883             }
884
885             fmt::Display::fmt(&bound.print(cx), f)?;
886         }
887
888         if let Some(lt) = lt {
889             write!(f, " + ")?;
890             fmt::Display::fmt(&lt.print(), f)?;
891         }
892         Ok(())
893     })
894 }
895
896 pub(crate) fn anchor<'a, 'cx: 'a>(
897     did: DefId,
898     text: Symbol,
899     cx: &'cx Context<'_>,
900 ) -> impl fmt::Display + 'a {
901     let parts = href(did, cx);
902     display_fn(move |f| {
903         if let Ok((url, short_ty, fqp)) = parts {
904             write!(
905                 f,
906                 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
907                 short_ty,
908                 url,
909                 short_ty,
910                 join_with_double_colon(&fqp),
911                 text.as_str()
912             )
913         } else {
914             write!(f, "{}", text)
915         }
916     })
917 }
918
919 fn fmt_type<'cx>(
920     t: &clean::Type,
921     f: &mut fmt::Formatter<'_>,
922     use_absolute: bool,
923     cx: &'cx Context<'_>,
924 ) -> fmt::Result {
925     trace!("fmt_type(t = {:?})", t);
926
927     match *t {
928         clean::Generic(name) => write!(f, "{}", name),
929         clean::Type::Path { ref path } => {
930             // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
931             let did = path.def_id();
932             resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
933         }
934         clean::DynTrait(ref bounds, ref lt) => {
935             f.write_str("dyn ")?;
936             fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
937         }
938         clean::Infer => write!(f, "_"),
939         clean::Primitive(clean::PrimitiveType::Never) => {
940             primitive_link(f, PrimitiveType::Never, "!", cx)
941         }
942         clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
943         clean::BareFunction(ref decl) => {
944             if f.alternate() {
945                 write!(
946                     f,
947                     "{:#}{}{:#}fn{:#}",
948                     decl.print_hrtb_with_space(cx),
949                     decl.unsafety.print_with_space(),
950                     print_abi_with_space(decl.abi),
951                     decl.decl.print(cx),
952                 )
953             } else {
954                 write!(
955                     f,
956                     "{}{}{}",
957                     decl.print_hrtb_with_space(cx),
958                     decl.unsafety.print_with_space(),
959                     print_abi_with_space(decl.abi)
960                 )?;
961                 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
962                 write!(f, "{}", decl.decl.print(cx))
963             }
964         }
965         clean::Tuple(ref typs) => {
966             match &typs[..] {
967                 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
968                 &[ref one] => {
969                     if let clean::Generic(name) = one {
970                         primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
971                     } else {
972                         write!(f, "(")?;
973                         // Carry `f.alternate()` into this display w/o branching manually.
974                         fmt::Display::fmt(&one.print(cx), f)?;
975                         write!(f, ",)")
976                     }
977                 }
978                 many => {
979                     let generic_names: Vec<Symbol> = many
980                         .iter()
981                         .filter_map(|t| match t {
982                             clean::Generic(name) => Some(*name),
983                             _ => None,
984                         })
985                         .collect();
986                     let is_generic = generic_names.len() == many.len();
987                     if is_generic {
988                         primitive_link(
989                             f,
990                             PrimitiveType::Tuple,
991                             &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
992                             cx,
993                         )
994                     } else {
995                         write!(f, "(")?;
996                         for (i, item) in many.iter().enumerate() {
997                             if i != 0 {
998                                 write!(f, ", ")?;
999                             }
1000                             // Carry `f.alternate()` into this display w/o branching manually.
1001                             fmt::Display::fmt(&item.print(cx), f)?;
1002                         }
1003                         write!(f, ")")
1004                     }
1005                 }
1006             }
1007         }
1008         clean::Slice(ref t) => match **t {
1009             clean::Generic(name) => {
1010                 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1011             }
1012             _ => {
1013                 write!(f, "[")?;
1014                 fmt::Display::fmt(&t.print(cx), f)?;
1015                 write!(f, "]")
1016             }
1017         },
1018         clean::Array(ref t, ref n) => {
1019             primitive_link(f, PrimitiveType::Array, "[", cx)?;
1020             fmt::Display::fmt(&t.print(cx), f)?;
1021             if f.alternate() {
1022                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
1023             } else {
1024                 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
1025             }
1026         }
1027         clean::RawPointer(m, ref t) => {
1028             let m = match m {
1029                 hir::Mutability::Mut => "mut",
1030                 hir::Mutability::Not => "const",
1031             };
1032
1033             if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1034                 let text = if f.alternate() {
1035                     format!("*{} {:#}", m, t.print(cx))
1036                 } else {
1037                     format!("*{} {}", m, t.print(cx))
1038                 };
1039                 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1040             } else {
1041                 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1042                 fmt::Display::fmt(&t.print(cx), f)
1043             }
1044         }
1045         clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1046             let lt = match l {
1047                 Some(l) => format!("{} ", l.print()),
1048                 _ => String::new(),
1049             };
1050             let m = mutability.print_with_space();
1051             let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
1052             match **ty {
1053                 clean::DynTrait(ref bounds, ref trait_lt)
1054                     if bounds.len() > 1 || trait_lt.is_some() =>
1055                 {
1056                     write!(f, "{}{}{}(", amp, lt, m)?;
1057                     fmt_type(ty, f, use_absolute, cx)?;
1058                     write!(f, ")")
1059                 }
1060                 clean::Generic(..) => {
1061                     primitive_link(
1062                         f,
1063                         PrimitiveType::Reference,
1064                         &format!("{}{}{}", amp, lt, m),
1065                         cx,
1066                     )?;
1067                     fmt_type(ty, f, use_absolute, cx)
1068                 }
1069                 _ => {
1070                     write!(f, "{}{}{}", amp, lt, m)?;
1071                     fmt_type(ty, f, use_absolute, cx)
1072                 }
1073             }
1074         }
1075         clean::ImplTrait(ref bounds) => {
1076             if f.alternate() {
1077                 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
1078             } else {
1079                 write!(f, "impl {}", print_generic_bounds(bounds, cx))
1080             }
1081         }
1082         clean::QPath(box clean::QPathData {
1083             ref assoc,
1084             ref self_type,
1085             ref trait_,
1086             should_show_cast,
1087         }) => {
1088             if f.alternate() {
1089                 if should_show_cast {
1090                     write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
1091                 } else {
1092                     write!(f, "{:#}::", self_type.print(cx))?
1093                 }
1094             } else {
1095                 if should_show_cast {
1096                     write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
1097                 } else {
1098                     write!(f, "{}::", self_type.print(cx))?
1099                 }
1100             };
1101             // It's pretty unsightly to look at `<A as B>::C` in output, and
1102             // we've got hyperlinking on our side, so try to avoid longer
1103             // notation as much as possible by making `C` a hyperlink to trait
1104             // `B` to disambiguate.
1105             //
1106             // FIXME: this is still a lossy conversion and there should probably
1107             //        be a better way of representing this in general? Most of
1108             //        the ugliness comes from inlining across crates where
1109             //        everything comes in as a fully resolved QPath (hard to
1110             //        look at).
1111             match href(trait_.def_id(), cx) {
1112                 Ok((ref url, _, ref path)) if !f.alternate() => {
1113                     write!(
1114                         f,
1115                         "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1116                                     title=\"type {path}::{name}\">{name}</a>{args}",
1117                         url = url,
1118                         shortty = ItemType::AssocType,
1119                         name = assoc.name,
1120                         path = join_with_double_colon(path),
1121                         args = assoc.args.print(cx),
1122                     )?;
1123                 }
1124                 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1125             }
1126             Ok(())
1127         }
1128     }
1129 }
1130
1131 impl clean::Type {
1132     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1133         &'a self,
1134         cx: &'a Context<'tcx>,
1135     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1136         display_fn(move |f| fmt_type(self, f, false, cx))
1137     }
1138 }
1139
1140 impl clean::Path {
1141     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1142         &'a self,
1143         cx: &'a Context<'tcx>,
1144     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1145         display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1146     }
1147 }
1148
1149 impl clean::Impl {
1150     pub(crate) fn print<'a, 'tcx: 'a>(
1151         &'a self,
1152         use_absolute: bool,
1153         cx: &'a Context<'tcx>,
1154     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1155         display_fn(move |f| {
1156             if f.alternate() {
1157                 write!(f, "impl{:#} ", self.generics.print(cx))?;
1158             } else {
1159                 write!(f, "impl{} ", self.generics.print(cx))?;
1160             }
1161
1162             if let Some(ref ty) = self.trait_ {
1163                 match self.polarity {
1164                     ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1165                     ty::ImplPolarity::Negative => write!(f, "!")?,
1166                 }
1167                 fmt::Display::fmt(&ty.print(cx), f)?;
1168                 write!(f, " for ")?;
1169             }
1170
1171             if let clean::Type::Tuple(types) = &self.for_ &&
1172                 let [clean::Type::Generic(name)] = &types[..] &&
1173                 (self.kind.is_fake_variadic() || self.kind.is_auto())
1174             {
1175                 // Hardcoded anchor library/core/src/primitive_docs.rs
1176                 // Link should match `# Trait implementations`
1177                 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1178             } else if let clean::BareFunction(bare_fn) = &self.for_ &&
1179                 let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
1180                 (self.kind.is_fake_variadic() || self.kind.is_auto())
1181             {
1182                 // Hardcoded anchor library/core/src/primitive_docs.rs
1183                 // Link should match `# Trait implementations`
1184
1185                 let hrtb = bare_fn.print_hrtb_with_space(cx);
1186                 let unsafety = bare_fn.unsafety.print_with_space();
1187                 let abi = print_abi_with_space(bare_fn.abi);
1188                 if f.alternate() {
1189                     write!(
1190                         f,
1191                         "{hrtb:#}{unsafety}{abi:#}",
1192                     )?;
1193                 } else {
1194                     write!(
1195                         f,
1196                         "{hrtb}{unsafety}{abi}",
1197                     )?;
1198                 }
1199                 let ellipsis = if bare_fn.decl.c_variadic {
1200                     ", ..."
1201                 } else {
1202                     ""
1203                 };
1204                 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
1205                 // Write output.
1206                 if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
1207                     write!(f, " -> ")?;
1208                     fmt_type(ty, f, use_absolute, cx)?;
1209                 }
1210             } else if let Some(ty) = self.kind.as_blanket_ty() {
1211                 fmt_type(ty, f, use_absolute, cx)?;
1212             } else {
1213                 fmt_type(&self.for_, f, use_absolute, cx)?;
1214             }
1215
1216             fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
1217             Ok(())
1218         })
1219     }
1220 }
1221
1222 impl clean::Arguments {
1223     pub(crate) fn print<'a, 'tcx: 'a>(
1224         &'a self,
1225         cx: &'a Context<'tcx>,
1226     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1227         display_fn(move |f| {
1228             for (i, input) in self.values.iter().enumerate() {
1229                 if !input.name.is_empty() {
1230                     write!(f, "{}: ", input.name)?;
1231                 }
1232                 if f.alternate() {
1233                     write!(f, "{:#}", input.type_.print(cx))?;
1234                 } else {
1235                     write!(f, "{}", input.type_.print(cx))?;
1236                 }
1237                 if i + 1 < self.values.len() {
1238                     write!(f, ", ")?;
1239                 }
1240             }
1241             Ok(())
1242         })
1243     }
1244 }
1245
1246 impl clean::FnRetTy {
1247     pub(crate) fn print<'a, 'tcx: 'a>(
1248         &'a self,
1249         cx: &'a Context<'tcx>,
1250     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1251         display_fn(move |f| match self {
1252             clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1253             clean::Return(ty) if f.alternate() => {
1254                 write!(f, " -> {:#}", ty.print(cx))
1255             }
1256             clean::Return(ty) => write!(f, " -&gt; {}", ty.print(cx)),
1257             clean::DefaultReturn => Ok(()),
1258         })
1259     }
1260 }
1261
1262 impl clean::BareFunctionDecl {
1263     fn print_hrtb_with_space<'a, 'tcx: 'a>(
1264         &'a self,
1265         cx: &'a Context<'tcx>,
1266     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1267         display_fn(move |f| {
1268             if !self.generic_params.is_empty() {
1269                 write!(
1270                     f,
1271                     "for&lt;{}&gt; ",
1272                     comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1273                 )
1274             } else {
1275                 Ok(())
1276             }
1277         })
1278     }
1279 }
1280
1281 impl clean::FnDecl {
1282     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1283         &'a self,
1284         cx: &'a Context<'tcx>,
1285     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1286         display_fn(move |f| {
1287             let ellipsis = if self.c_variadic { ", ..." } else { "" };
1288             if f.alternate() {
1289                 write!(
1290                     f,
1291                     "({args:#}{ellipsis}){arrow:#}",
1292                     args = self.inputs.print(cx),
1293                     ellipsis = ellipsis,
1294                     arrow = self.output.print(cx)
1295                 )
1296             } else {
1297                 write!(
1298                     f,
1299                     "({args}{ellipsis}){arrow}",
1300                     args = self.inputs.print(cx),
1301                     ellipsis = ellipsis,
1302                     arrow = self.output.print(cx)
1303                 )
1304             }
1305         })
1306     }
1307
1308     /// * `header_len`: The length of the function header and name. In other words, the number of
1309     ///   characters in the function declaration up to but not including the parentheses.
1310     ///   <br>Used to determine line-wrapping.
1311     /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1312     ///   necessary.
1313     /// * `asyncness`: Whether the function is async or not.
1314     pub(crate) fn full_print<'a, 'tcx: 'a>(
1315         &'a self,
1316         header_len: usize,
1317         indent: usize,
1318         asyncness: hir::IsAsync,
1319         cx: &'a Context<'tcx>,
1320     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1321         display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1322     }
1323
1324     fn inner_full_print(
1325         &self,
1326         header_len: usize,
1327         indent: usize,
1328         asyncness: hir::IsAsync,
1329         f: &mut fmt::Formatter<'_>,
1330         cx: &Context<'_>,
1331     ) -> fmt::Result {
1332         let amp = if f.alternate() { "&" } else { "&amp;" };
1333         let mut args = Buffer::html();
1334         let mut args_plain = Buffer::new();
1335         for (i, input) in self.inputs.values.iter().enumerate() {
1336             if let Some(selfty) = input.to_self() {
1337                 match selfty {
1338                     clean::SelfValue => {
1339                         args.push_str("self");
1340                         args_plain.push_str("self");
1341                     }
1342                     clean::SelfBorrowed(Some(ref lt), mtbl) => {
1343                         write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1344                         write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1345                     }
1346                     clean::SelfBorrowed(None, mtbl) => {
1347                         write!(args, "{}{}self", amp, mtbl.print_with_space());
1348                         write!(args_plain, "&{}self", mtbl.print_with_space());
1349                     }
1350                     clean::SelfExplicit(ref typ) => {
1351                         if f.alternate() {
1352                             write!(args, "self: {:#}", typ.print(cx));
1353                         } else {
1354                             write!(args, "self: {}", typ.print(cx));
1355                         }
1356                         write!(args_plain, "self: {:#}", typ.print(cx));
1357                     }
1358                 }
1359             } else {
1360                 if i > 0 {
1361                     args.push_str("<br>");
1362                 }
1363                 if input.is_const {
1364                     args.push_str("const ");
1365                     args_plain.push_str("const ");
1366                 }
1367                 if !input.name.is_empty() {
1368                     write!(args, "{}: ", input.name);
1369                     write!(args_plain, "{}: ", input.name);
1370                 }
1371
1372                 if f.alternate() {
1373                     write!(args, "{:#}", input.type_.print(cx));
1374                 } else {
1375                     write!(args, "{}", input.type_.print(cx));
1376                 }
1377                 write!(args_plain, "{:#}", input.type_.print(cx));
1378             }
1379             if i + 1 < self.inputs.values.len() {
1380                 args.push_str(",");
1381                 args_plain.push_str(",");
1382             }
1383         }
1384
1385         let mut args_plain = format!("({})", args_plain.into_inner());
1386         let mut args = args.into_inner();
1387
1388         if self.c_variadic {
1389             args.push_str(",<br> ...");
1390             args_plain.push_str(", ...");
1391         }
1392
1393         let arrow_plain;
1394         let arrow = if let hir::IsAsync::Async = asyncness {
1395             let output = self.sugared_async_return_type();
1396             arrow_plain = format!("{:#}", output.print(cx));
1397             if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1398         } else {
1399             arrow_plain = format!("{:#}", self.output.print(cx));
1400             if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1401         };
1402
1403         let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1404         let output = if declaration_len > 80 {
1405             let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1406             let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1407             format!(
1408                 "({pad}{args}{close}){arrow}",
1409                 pad = if self.inputs.values.is_empty() { "" } else { &full_pad },
1410                 args = args.replace("<br>", &full_pad),
1411                 close = close_pad,
1412                 arrow = arrow
1413             )
1414         } else {
1415             format!("({args}){arrow}", args = args.replace("<br>", " "), arrow = arrow)
1416         };
1417
1418         if f.alternate() {
1419             write!(f, "{}", output.replace("<br>", "\n"))
1420         } else {
1421             write!(f, "{}", output)
1422         }
1423     }
1424 }
1425
1426 impl clean::Visibility {
1427     pub(crate) fn print_with_space<'a, 'tcx: 'a>(
1428         self,
1429         item_did: ItemId,
1430         cx: &'a Context<'tcx>,
1431     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1432         use std::fmt::Write as _;
1433
1434         let to_print: Cow<'static, str> = match self {
1435             clean::Public => "pub ".into(),
1436             clean::Inherited => "".into(),
1437             clean::Visibility::Restricted(vis_did) => {
1438                 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1439                 //                 However, rustdoc currently never displays a module's
1440                 //                 visibility, so it shouldn't matter.
1441                 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1442
1443                 if vis_did.is_crate_root() {
1444                     "pub(crate) ".into()
1445                 } else if parent_module == Some(vis_did) {
1446                     // `pub(in foo)` where `foo` is the parent module
1447                     // is the same as no visibility modifier
1448                     "".into()
1449                 } else if parent_module
1450                     .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1451                     == Some(vis_did)
1452                 {
1453                     "pub(super) ".into()
1454                 } else {
1455                     let path = cx.tcx().def_path(vis_did);
1456                     debug!("path={:?}", path);
1457                     // modified from `resolved_path()` to work with `DefPathData`
1458                     let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1459                     let anchor = anchor(vis_did, last_name, cx).to_string();
1460
1461                     let mut s = "pub(in ".to_owned();
1462                     for seg in &path.data[..path.data.len() - 1] {
1463                         let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1464                     }
1465                     let _ = write!(s, "{}) ", anchor);
1466                     s.into()
1467                 }
1468             }
1469         };
1470         display_fn(move |f| write!(f, "{}", to_print))
1471     }
1472
1473     /// This function is the same as print_with_space, except that it renders no links.
1474     /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1475     /// any HTML in it.
1476     pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
1477         self,
1478         tcx: TyCtxt<'tcx>,
1479         item_did: DefId,
1480     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1481         let to_print = match self {
1482             clean::Public => "pub ".to_owned(),
1483             clean::Inherited => String::new(),
1484             clean::Visibility::Restricted(vis_did) => {
1485                 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1486                 //                 However, rustdoc currently never displays a module's
1487                 //                 visibility, so it shouldn't matter.
1488                 let parent_module = find_nearest_parent_module(tcx, item_did);
1489
1490                 if vis_did.is_crate_root() {
1491                     "pub(crate) ".to_owned()
1492                 } else if parent_module == Some(vis_did) {
1493                     // `pub(in foo)` where `foo` is the parent module
1494                     // is the same as no visibility modifier
1495                     String::new()
1496                 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1497                     == Some(vis_did)
1498                 {
1499                     "pub(super) ".to_owned()
1500                 } else {
1501                     format!("pub(in {}) ", tcx.def_path_str(vis_did))
1502                 }
1503             }
1504         };
1505         display_fn(move |f| f.write_str(&to_print))
1506     }
1507 }
1508
1509 pub(crate) trait PrintWithSpace {
1510     fn print_with_space(&self) -> &str;
1511 }
1512
1513 impl PrintWithSpace for hir::Unsafety {
1514     fn print_with_space(&self) -> &str {
1515         match self {
1516             hir::Unsafety::Unsafe => "unsafe ",
1517             hir::Unsafety::Normal => "",
1518         }
1519     }
1520 }
1521
1522 impl PrintWithSpace for hir::IsAsync {
1523     fn print_with_space(&self) -> &str {
1524         match self {
1525             hir::IsAsync::Async => "async ",
1526             hir::IsAsync::NotAsync => "",
1527         }
1528     }
1529 }
1530
1531 impl PrintWithSpace for hir::Mutability {
1532     fn print_with_space(&self) -> &str {
1533         match self {
1534             hir::Mutability::Not => "",
1535             hir::Mutability::Mut => "mut ",
1536         }
1537     }
1538 }
1539
1540 pub(crate) fn print_constness_with_space(
1541     c: &hir::Constness,
1542     s: Option<ConstStability>,
1543 ) -> &'static str {
1544     match (c, s) {
1545         // const stable or when feature(staged_api) is not set
1546         (
1547             hir::Constness::Const,
1548             Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1549         )
1550         | (hir::Constness::Const, None) => "const ",
1551         // const unstable or not const
1552         _ => "",
1553     }
1554 }
1555
1556 impl clean::Import {
1557     pub(crate) fn print<'a, 'tcx: 'a>(
1558         &'a self,
1559         cx: &'a Context<'tcx>,
1560     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1561         display_fn(move |f| match self.kind {
1562             clean::ImportKind::Simple(name) => {
1563                 if name == self.source.path.last() {
1564                     write!(f, "use {};", self.source.print(cx))
1565                 } else {
1566                     write!(f, "use {} as {};", self.source.print(cx), name)
1567                 }
1568             }
1569             clean::ImportKind::Glob => {
1570                 if self.source.path.segments.is_empty() {
1571                     write!(f, "use *;")
1572                 } else {
1573                     write!(f, "use {}::*;", self.source.print(cx))
1574                 }
1575             }
1576         })
1577     }
1578 }
1579
1580 impl clean::ImportSource {
1581     pub(crate) fn print<'a, 'tcx: 'a>(
1582         &'a self,
1583         cx: &'a Context<'tcx>,
1584     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1585         display_fn(move |f| match self.did {
1586             Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1587             _ => {
1588                 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1589                     write!(f, "{}::", seg.name)?;
1590                 }
1591                 let name = self.path.last();
1592                 if let hir::def::Res::PrimTy(p) = self.path.res {
1593                     primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1594                 } else {
1595                     write!(f, "{}", name)?;
1596                 }
1597                 Ok(())
1598             }
1599         })
1600     }
1601 }
1602
1603 impl clean::TypeBinding {
1604     pub(crate) fn print<'a, 'tcx: 'a>(
1605         &'a self,
1606         cx: &'a Context<'tcx>,
1607     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1608         display_fn(move |f| {
1609             f.write_str(self.assoc.name.as_str())?;
1610             if f.alternate() {
1611                 write!(f, "{:#}", self.assoc.args.print(cx))?;
1612             } else {
1613                 write!(f, "{}", self.assoc.args.print(cx))?;
1614             }
1615             match self.kind {
1616                 clean::TypeBindingKind::Equality { ref term } => {
1617                     if f.alternate() {
1618                         write!(f, " = {:#}", term.print(cx))?;
1619                     } else {
1620                         write!(f, " = {}", term.print(cx))?;
1621                     }
1622                 }
1623                 clean::TypeBindingKind::Constraint { ref bounds } => {
1624                     if !bounds.is_empty() {
1625                         if f.alternate() {
1626                             write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1627                         } else {
1628                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
1629                         }
1630                     }
1631                 }
1632             }
1633             Ok(())
1634         })
1635     }
1636 }
1637
1638 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1639     display_fn(move |f| {
1640         let quot = if f.alternate() { "\"" } else { "&quot;" };
1641         match abi {
1642             Abi::Rust => Ok(()),
1643             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1644         }
1645     })
1646 }
1647
1648 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1649     if v { "default " } else { "" }
1650 }
1651
1652 impl clean::GenericArg {
1653     pub(crate) fn print<'a, 'tcx: 'a>(
1654         &'a self,
1655         cx: &'a Context<'tcx>,
1656     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1657         display_fn(move |f| match self {
1658             clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1659             clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1660             clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1661             clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1662         })
1663     }
1664 }
1665
1666 impl clean::types::Term {
1667     pub(crate) fn print<'a, 'tcx: 'a>(
1668         &'a self,
1669         cx: &'a Context<'tcx>,
1670     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1671         match self {
1672             clean::types::Term::Type(ty) => ty.print(cx),
1673             _ => todo!(),
1674         }
1675     }
1676 }
1677
1678 pub(crate) fn display_fn(
1679     f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1680 ) -> impl fmt::Display {
1681     struct WithFormatter<F>(Cell<Option<F>>);
1682
1683     impl<F> fmt::Display for WithFormatter<F>
1684     where
1685         F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1686     {
1687         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1688             (self.0.take()).unwrap()(f)
1689         }
1690     }
1691
1692     WithFormatter(Cell::new(Some(f)))
1693 }