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