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