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