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