]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Rollup merge of #104024 - noeddl:unused-must-use, r=compiler-errors
[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, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
212                     }
213                 }
214
215                 if let Some(ref ty) = default {
216                     if f.alternate() {
217                         write!(f, " = {:#}", ty.print(cx))?;
218                     } else {
219                         write!(f, "&nbsp;=&nbsp;{}", ty.print(cx))?;
220                     }
221                 }
222
223                 Ok(())
224             }
225             clean::GenericParamDefKind::Const { ty, default, .. } => {
226                 if f.alternate() {
227                     write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
228                 } else {
229                     write!(f, "const {}:&nbsp;{}", self.name, ty.print(cx))?;
230                 }
231
232                 if let Some(default) = default {
233                     if f.alternate() {
234                         write!(f, " = {:#}", default)?;
235                     } else {
236                         write!(f, "&nbsp;=&nbsp;{}", default)?;
237                     }
238                 }
239
240                 Ok(())
241             }
242         })
243     }
244 }
245
246 impl clean::Generics {
247     pub(crate) fn print<'a, 'tcx: 'a>(
248         &'a self,
249         cx: &'a Context<'tcx>,
250     ) -> impl fmt::Display + 'a + Captures<'tcx> {
251         display_fn(move |f| {
252             let mut real_params =
253                 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
254             if real_params.peek().is_none() {
255                 return Ok(());
256             }
257
258             if f.alternate() {
259                 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
260             } else {
261                 write!(f, "&lt;{}&gt;", comma_sep(real_params.map(|g| g.print(cx)), true))
262             }
263         })
264     }
265 }
266
267 #[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("&nbsp;");
358             }
359             let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
360
361             if ending == Ending::Newline {
362                 let mut clause = "&nbsp;".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 * "&nbsp;".len());
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).to_string();
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().map(|elem| elem.to_string());
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.clone()).chain(relative).collect()
606     } else {
607         vec![crate_name.clone(), 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 = format!("macro.{}.html", last);
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.join("/"))
624         }
625         ExternalLocation::Local => {
626             // `root_path` always end with a `/`.
627             format!("{}{}/{}", root_path.unwrap_or(""), crate_name, path.join("/"))
628         }
629         ExternalLocation::Unknown => {
630             debug!("crate {} not in cache when linkifying macros", crate_name);
631             return Err(HrefError::NotInExternalCache);
632         }
633     };
634     Ok((url, ItemType::Macro, fqp))
635 }
636
637 pub(crate) fn href_with_root_path(
638     did: DefId,
639     cx: &Context<'_>,
640     root_path: Option<&str>,
641 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
642     let tcx = cx.tcx();
643     let def_kind = tcx.def_kind(did);
644     let did = match def_kind {
645         DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
646             // documented on their parent's page
647             tcx.parent(did)
648         }
649         _ => did,
650     };
651     let cache = cx.cache();
652     let relative_to = &cx.current;
653     fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
654         if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
655     }
656
657     if !did.is_local()
658         && !cache.effective_visibilities.is_directly_public(tcx, did)
659         && !cache.document_private
660         && !cache.primitive_locations.values().any(|&id| id == did)
661     {
662         return Err(HrefError::Private);
663     }
664
665     let mut is_remote = false;
666     let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
667         Some(&(ref fqp, shortty)) => (fqp, shortty, {
668             let module_fqp = to_module_fqp(shortty, fqp.as_slice());
669             debug!(?fqp, ?shortty, ?module_fqp);
670             href_relative_parts(module_fqp, relative_to).collect()
671         }),
672         None => {
673             if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
674                 let module_fqp = to_module_fqp(shortty, fqp);
675                 (
676                     fqp,
677                     shortty,
678                     match cache.extern_locations[&did.krate] {
679                         ExternalLocation::Remote(ref s) => {
680                             is_remote = true;
681                             let s = s.trim_end_matches('/');
682                             let mut builder = UrlPartsBuilder::singleton(s);
683                             builder.extend(module_fqp.iter().copied());
684                             builder
685                         }
686                         ExternalLocation::Local => {
687                             href_relative_parts(module_fqp, relative_to).collect()
688                         }
689                         ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
690                     },
691                 )
692             } else if matches!(def_kind, DefKind::Macro(_)) {
693                 return generate_macro_def_id_path(did, cx, root_path);
694             } else {
695                 return Err(HrefError::NotInExternalCache);
696             }
697         }
698     };
699     if !is_remote {
700         if let Some(root_path) = root_path {
701             let root = root_path.trim_end_matches('/');
702             url_parts.push_front(root);
703         }
704     }
705     debug!(?url_parts);
706     match shortty {
707         ItemType::Module => {
708             url_parts.push("index.html");
709         }
710         _ => {
711             let prefix = shortty.as_str();
712             let last = fqp.last().unwrap();
713             url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
714         }
715     }
716     Ok((url_parts.finish(), shortty, fqp.to_vec()))
717 }
718
719 pub(crate) fn href(
720     did: DefId,
721     cx: &Context<'_>,
722 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
723     href_with_root_path(did, cx, None)
724 }
725
726 /// Both paths should only be modules.
727 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
728 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
729 pub(crate) fn href_relative_parts<'fqp>(
730     fqp: &'fqp [Symbol],
731     relative_to_fqp: &[Symbol],
732 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
733     for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
734         // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
735         if f != r {
736             let dissimilar_part_count = relative_to_fqp.len() - i;
737             let fqp_module = &fqp[i..fqp.len()];
738             return Box::new(
739                 iter::repeat(sym::dotdot)
740                     .take(dissimilar_part_count)
741                     .chain(fqp_module.iter().copied()),
742             );
743         }
744     }
745     // e.g. linking to std::sync::atomic from std::sync
746     if relative_to_fqp.len() < fqp.len() {
747         Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
748     // e.g. linking to std::sync from std::sync::atomic
749     } else if fqp.len() < relative_to_fqp.len() {
750         let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
751         Box::new(iter::repeat(sym::dotdot).take(dissimilar_part_count))
752     // linking to the same module
753     } else {
754         Box::new(iter::empty())
755     }
756 }
757
758 /// Used to render a [`clean::Path`].
759 fn resolved_path<'cx>(
760     w: &mut fmt::Formatter<'_>,
761     did: DefId,
762     path: &clean::Path,
763     print_all: bool,
764     use_absolute: bool,
765     cx: &'cx Context<'_>,
766 ) -> fmt::Result {
767     let last = path.segments.last().unwrap();
768
769     if print_all {
770         for seg in &path.segments[..path.segments.len() - 1] {
771             write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
772         }
773     }
774     if w.alternate() {
775         write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
776     } else {
777         let path = if use_absolute {
778             if let Ok((_, _, fqp)) = href(did, cx) {
779                 format!(
780                     "{}::{}",
781                     join_with_double_colon(&fqp[..fqp.len() - 1]),
782                     anchor(did, *fqp.last().unwrap(), cx)
783                 )
784             } else {
785                 last.name.to_string()
786             }
787         } else {
788             anchor(did, last.name, cx).to_string()
789         };
790         write!(w, "{}{}", path, last.args.print(cx))?;
791     }
792     Ok(())
793 }
794
795 fn primitive_link(
796     f: &mut fmt::Formatter<'_>,
797     prim: clean::PrimitiveType,
798     name: &str,
799     cx: &Context<'_>,
800 ) -> fmt::Result {
801     primitive_link_fragment(f, prim, name, "", cx)
802 }
803
804 fn primitive_link_fragment(
805     f: &mut fmt::Formatter<'_>,
806     prim: clean::PrimitiveType,
807     name: &str,
808     fragment: &str,
809     cx: &Context<'_>,
810 ) -> fmt::Result {
811     let m = &cx.cache();
812     let mut needs_termination = false;
813     if !f.alternate() {
814         match m.primitive_locations.get(&prim) {
815             Some(&def_id) if def_id.is_local() => {
816                 let len = cx.current.len();
817                 let len = if len == 0 { 0 } else { len - 1 };
818                 write!(
819                     f,
820                     "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
821                     "../".repeat(len),
822                     prim.as_sym()
823                 )?;
824                 needs_termination = true;
825             }
826             Some(&def_id) => {
827                 let loc = match m.extern_locations[&def_id.krate] {
828                     ExternalLocation::Remote(ref s) => {
829                         let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
830                         let builder: UrlPartsBuilder =
831                             [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
832                                 .into_iter()
833                                 .collect();
834                         Some(builder)
835                     }
836                     ExternalLocation::Local => {
837                         let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
838                         Some(if cx.current.first() == Some(&cname_sym) {
839                             iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
840                         } else {
841                             iter::repeat(sym::dotdot)
842                                 .take(cx.current.len())
843                                 .chain(iter::once(cname_sym))
844                                 .collect()
845                         })
846                     }
847                     ExternalLocation::Unknown => None,
848                 };
849                 if let Some(mut loc) = loc {
850                     loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
851                     write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
852                     needs_termination = true;
853                 }
854             }
855             None => {}
856         }
857     }
858     write!(f, "{}", name)?;
859     if needs_termination {
860         write!(f, "</a>")?;
861     }
862     Ok(())
863 }
864
865 /// Helper to render type parameters
866 fn tybounds<'a, 'tcx: 'a>(
867     bounds: &'a [clean::PolyTrait],
868     lt: &'a Option<clean::Lifetime>,
869     cx: &'a Context<'tcx>,
870 ) -> impl fmt::Display + 'a + Captures<'tcx> {
871     display_fn(move |f| {
872         for (i, bound) in bounds.iter().enumerate() {
873             if i > 0 {
874                 write!(f, " + ")?;
875             }
876
877             fmt::Display::fmt(&bound.print(cx), f)?;
878         }
879
880         if let Some(lt) = lt {
881             write!(f, " + ")?;
882             fmt::Display::fmt(&lt.print(), f)?;
883         }
884         Ok(())
885     })
886 }
887
888 pub(crate) fn anchor<'a, 'cx: 'a>(
889     did: DefId,
890     text: Symbol,
891     cx: &'cx Context<'_>,
892 ) -> impl fmt::Display + 'a {
893     let parts = href(did, cx);
894     display_fn(move |f| {
895         if let Ok((url, short_ty, fqp)) = parts {
896             write!(
897                 f,
898                 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
899                 short_ty,
900                 url,
901                 short_ty,
902                 join_with_double_colon(&fqp),
903                 text.as_str()
904             )
905         } else {
906             write!(f, "{}", text)
907         }
908     })
909 }
910
911 fn fmt_type<'cx>(
912     t: &clean::Type,
913     f: &mut fmt::Formatter<'_>,
914     use_absolute: bool,
915     cx: &'cx Context<'_>,
916 ) -> fmt::Result {
917     trace!("fmt_type(t = {:?})", t);
918
919     match *t {
920         clean::Generic(name) => write!(f, "{}", name),
921         clean::Type::Path { ref path } => {
922             // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
923             let did = path.def_id();
924             resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
925         }
926         clean::DynTrait(ref bounds, ref lt) => {
927             f.write_str("dyn ")?;
928             fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
929         }
930         clean::Infer => write!(f, "_"),
931         clean::Primitive(clean::PrimitiveType::Never) => {
932             primitive_link(f, PrimitiveType::Never, "!", cx)
933         }
934         clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
935         clean::BareFunction(ref decl) => {
936             if f.alternate() {
937                 write!(
938                     f,
939                     "{:#}{}{:#}fn{:#}",
940                     decl.print_hrtb_with_space(cx),
941                     decl.unsafety.print_with_space(),
942                     print_abi_with_space(decl.abi),
943                     decl.decl.print(cx),
944                 )
945             } else {
946                 write!(
947                     f,
948                     "{}{}{}",
949                     decl.print_hrtb_with_space(cx),
950                     decl.unsafety.print_with_space(),
951                     print_abi_with_space(decl.abi)
952                 )?;
953                 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
954                 write!(f, "{}", decl.decl.print(cx))
955             }
956         }
957         clean::Tuple(ref typs) => {
958             match &typs[..] {
959                 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
960                 &[ref one] => {
961                     if let clean::Generic(name) = one {
962                         primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
963                     } else {
964                         write!(f, "(")?;
965                         // Carry `f.alternate()` into this display w/o branching manually.
966                         fmt::Display::fmt(&one.print(cx), f)?;
967                         write!(f, ",)")
968                     }
969                 }
970                 many => {
971                     let generic_names: Vec<Symbol> = many
972                         .iter()
973                         .filter_map(|t| match t {
974                             clean::Generic(name) => Some(*name),
975                             _ => None,
976                         })
977                         .collect();
978                     let is_generic = generic_names.len() == many.len();
979                     if is_generic {
980                         primitive_link(
981                             f,
982                             PrimitiveType::Tuple,
983                             &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
984                             cx,
985                         )
986                     } else {
987                         write!(f, "(")?;
988                         for (i, item) in many.iter().enumerate() {
989                             if i != 0 {
990                                 write!(f, ", ")?;
991                             }
992                             // Carry `f.alternate()` into this display w/o branching manually.
993                             fmt::Display::fmt(&item.print(cx), f)?;
994                         }
995                         write!(f, ")")
996                     }
997                 }
998             }
999         }
1000         clean::Slice(ref t) => match **t {
1001             clean::Generic(name) => {
1002                 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1003             }
1004             _ => {
1005                 write!(f, "[")?;
1006                 fmt::Display::fmt(&t.print(cx), f)?;
1007                 write!(f, "]")
1008             }
1009         },
1010         clean::Array(ref t, ref n) => match **t {
1011             clean::Generic(name) if !f.alternate() => primitive_link(
1012                 f,
1013                 PrimitiveType::Array,
1014                 &format!("[{name}; {n}]", n = Escape(n)),
1015                 cx,
1016             ),
1017             _ => {
1018                 write!(f, "[")?;
1019                 fmt::Display::fmt(&t.print(cx), f)?;
1020                 if f.alternate() {
1021                     write!(f, "; {n}")?;
1022                 } else {
1023                     write!(f, "; ")?;
1024                     primitive_link(f, PrimitiveType::Array, &format!("{n}", n = Escape(n)), cx)?;
1025                 }
1026                 write!(f, "]")
1027             }
1028         },
1029         clean::RawPointer(m, ref t) => {
1030             let m = match m {
1031                 hir::Mutability::Mut => "mut",
1032                 hir::Mutability::Not => "const",
1033             };
1034
1035             if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1036                 let text = if f.alternate() {
1037                     format!("*{} {:#}", m, t.print(cx))
1038                 } else {
1039                     format!("*{} {}", m, t.print(cx))
1040                 };
1041                 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1042             } else {
1043                 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1044                 fmt::Display::fmt(&t.print(cx), f)
1045             }
1046         }
1047         clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1048             let lt = match l {
1049                 Some(l) => format!("{} ", l.print()),
1050                 _ => String::new(),
1051             };
1052             let m = mutability.print_with_space();
1053             let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
1054             match **ty {
1055                 clean::DynTrait(ref bounds, ref trait_lt)
1056                     if bounds.len() > 1 || trait_lt.is_some() =>
1057                 {
1058                     write!(f, "{}{}{}(", amp, lt, m)?;
1059                     fmt_type(ty, f, use_absolute, cx)?;
1060                     write!(f, ")")
1061                 }
1062                 clean::Generic(..) => {
1063                     primitive_link(
1064                         f,
1065                         PrimitiveType::Reference,
1066                         &format!("{}{}{}", amp, lt, m),
1067                         cx,
1068                     )?;
1069                     fmt_type(ty, f, use_absolute, cx)
1070                 }
1071                 _ => {
1072                     write!(f, "{}{}{}", amp, lt, m)?;
1073                     fmt_type(ty, f, use_absolute, cx)
1074                 }
1075             }
1076         }
1077         clean::ImplTrait(ref bounds) => {
1078             if f.alternate() {
1079                 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
1080             } else {
1081                 write!(f, "impl {}", print_generic_bounds(bounds, cx))
1082             }
1083         }
1084         clean::QPath(box clean::QPathData {
1085             ref assoc,
1086             ref self_type,
1087             ref trait_,
1088             should_show_cast,
1089         }) => {
1090             if f.alternate() {
1091                 if should_show_cast {
1092                     write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
1093                 } else {
1094                     write!(f, "{:#}::", self_type.print(cx))?
1095                 }
1096             } else {
1097                 if should_show_cast {
1098                     write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
1099                 } else {
1100                     write!(f, "{}::", self_type.print(cx))?
1101                 }
1102             };
1103             // It's pretty unsightly to look at `<A as B>::C` in output, and
1104             // we've got hyperlinking on our side, so try to avoid longer
1105             // notation as much as possible by making `C` a hyperlink to trait
1106             // `B` to disambiguate.
1107             //
1108             // FIXME: this is still a lossy conversion and there should probably
1109             //        be a better way of representing this in general? Most of
1110             //        the ugliness comes from inlining across crates where
1111             //        everything comes in as a fully resolved QPath (hard to
1112             //        look at).
1113             match href(trait_.def_id(), cx) {
1114                 Ok((ref url, _, ref path)) if !f.alternate() => {
1115                     write!(
1116                         f,
1117                         "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1118                                     title=\"type {path}::{name}\">{name}</a>{args}",
1119                         url = url,
1120                         shortty = ItemType::AssocType,
1121                         name = assoc.name,
1122                         path = join_with_double_colon(path),
1123                         args = assoc.args.print(cx),
1124                     )?;
1125                 }
1126                 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1127             }
1128             Ok(())
1129         }
1130     }
1131 }
1132
1133 impl clean::Type {
1134     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1135         &'a self,
1136         cx: &'a Context<'tcx>,
1137     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1138         display_fn(move |f| fmt_type(self, f, false, cx))
1139     }
1140 }
1141
1142 impl clean::Path {
1143     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1144         &'a self,
1145         cx: &'a Context<'tcx>,
1146     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1147         display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1148     }
1149 }
1150
1151 impl clean::Impl {
1152     pub(crate) fn print<'a, 'tcx: 'a>(
1153         &'a self,
1154         use_absolute: bool,
1155         cx: &'a Context<'tcx>,
1156     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1157         display_fn(move |f| {
1158             if f.alternate() {
1159                 write!(f, "impl{:#} ", self.generics.print(cx))?;
1160             } else {
1161                 write!(f, "impl{} ", self.generics.print(cx))?;
1162             }
1163
1164             if let Some(ref ty) = self.trait_ {
1165                 match self.polarity {
1166                     ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1167                     ty::ImplPolarity::Negative => write!(f, "!")?,
1168                 }
1169                 fmt::Display::fmt(&ty.print(cx), f)?;
1170                 write!(f, " for ")?;
1171             }
1172
1173             if let clean::Type::Tuple(types) = &self.for_ &&
1174                 let [clean::Type::Generic(name)] = &types[..] &&
1175                 (self.kind.is_fake_variadic() || self.kind.is_auto())
1176             {
1177                 // Hardcoded anchor library/core/src/primitive_docs.rs
1178                 // Link should match `# Trait implementations`
1179                 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1180             } else if let clean::BareFunction(bare_fn) = &self.for_ &&
1181                 let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
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
1187                 let hrtb = bare_fn.print_hrtb_with_space(cx);
1188                 let unsafety = bare_fn.unsafety.print_with_space();
1189                 let abi = print_abi_with_space(bare_fn.abi);
1190                 if f.alternate() {
1191                     write!(
1192                         f,
1193                         "{hrtb:#}{unsafety}{abi:#}",
1194                     )?;
1195                 } else {
1196                     write!(
1197                         f,
1198                         "{hrtb}{unsafety}{abi}",
1199                     )?;
1200                 }
1201                 let ellipsis = if bare_fn.decl.c_variadic {
1202                     ", ..."
1203                 } else {
1204                     ""
1205                 };
1206                 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
1207                 // Write output.
1208                 if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
1209                     write!(f, " -> ")?;
1210                     fmt_type(ty, f, use_absolute, cx)?;
1211                 }
1212             } else if let Some(ty) = self.kind.as_blanket_ty() {
1213                 fmt_type(ty, f, use_absolute, cx)?;
1214             } else {
1215                 fmt_type(&self.for_, f, use_absolute, cx)?;
1216             }
1217
1218             fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
1219             Ok(())
1220         })
1221     }
1222 }
1223
1224 impl clean::Arguments {
1225     pub(crate) fn print<'a, 'tcx: 'a>(
1226         &'a self,
1227         cx: &'a Context<'tcx>,
1228     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1229         display_fn(move |f| {
1230             for (i, input) in self.values.iter().enumerate() {
1231                 write!(f, "{}: ", input.name)?;
1232
1233                 if f.alternate() {
1234                     write!(f, "{:#}", input.type_.print(cx))?;
1235                 } else {
1236                     write!(f, "{}", input.type_.print(cx))?;
1237                 }
1238                 if i + 1 < self.values.len() {
1239                     write!(f, ", ")?;
1240                 }
1241             }
1242             Ok(())
1243         })
1244     }
1245 }
1246
1247 impl clean::FnRetTy {
1248     pub(crate) fn print<'a, 'tcx: 'a>(
1249         &'a self,
1250         cx: &'a Context<'tcx>,
1251     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1252         display_fn(move |f| match self {
1253             clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1254             clean::Return(ty) if f.alternate() => {
1255                 write!(f, " -> {:#}", ty.print(cx))
1256             }
1257             clean::Return(ty) => write!(f, " -&gt; {}", ty.print(cx)),
1258             clean::DefaultReturn => Ok(()),
1259         })
1260     }
1261 }
1262
1263 impl clean::BareFunctionDecl {
1264     fn print_hrtb_with_space<'a, 'tcx: 'a>(
1265         &'a self,
1266         cx: &'a Context<'tcx>,
1267     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1268         display_fn(move |f| {
1269             if !self.generic_params.is_empty() {
1270                 write!(
1271                     f,
1272                     "for&lt;{}&gt; ",
1273                     comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1274                 )
1275             } else {
1276                 Ok(())
1277             }
1278         })
1279     }
1280 }
1281
1282 impl clean::FnDecl {
1283     pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1284         &'a self,
1285         cx: &'a Context<'tcx>,
1286     ) -> impl fmt::Display + 'b + Captures<'tcx> {
1287         display_fn(move |f| {
1288             let ellipsis = if self.c_variadic { ", ..." } else { "" };
1289             if f.alternate() {
1290                 write!(
1291                     f,
1292                     "({args:#}{ellipsis}){arrow:#}",
1293                     args = self.inputs.print(cx),
1294                     ellipsis = ellipsis,
1295                     arrow = self.output.print(cx)
1296                 )
1297             } else {
1298                 write!(
1299                     f,
1300                     "({args}{ellipsis}){arrow}",
1301                     args = self.inputs.print(cx),
1302                     ellipsis = ellipsis,
1303                     arrow = self.output.print(cx)
1304                 )
1305             }
1306         })
1307     }
1308
1309     /// * `header_len`: The length of the function header and name. In other words, the number of
1310     ///   characters in the function declaration up to but not including the parentheses.
1311     ///   <br>Used to determine line-wrapping.
1312     /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1313     ///   necessary.
1314     pub(crate) fn full_print<'a, 'tcx: 'a>(
1315         &'a self,
1316         header_len: usize,
1317         indent: usize,
1318         cx: &'a Context<'tcx>,
1319     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1320         display_fn(move |f| self.inner_full_print(header_len, indent, f, cx))
1321     }
1322
1323     fn inner_full_print(
1324         &self,
1325         header_len: usize,
1326         indent: usize,
1327         f: &mut fmt::Formatter<'_>,
1328         cx: &Context<'_>,
1329     ) -> fmt::Result {
1330         let amp = if f.alternate() { "&" } else { "&amp;" };
1331         let mut args = Buffer::html();
1332         let mut args_plain = Buffer::new();
1333         for (i, input) in self.inputs.values.iter().enumerate() {
1334             if let Some(selfty) = input.to_self() {
1335                 match selfty {
1336                     clean::SelfValue => {
1337                         args.push_str("self");
1338                         args_plain.push_str("self");
1339                     }
1340                     clean::SelfBorrowed(Some(ref lt), mtbl) => {
1341                         write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1342                         write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1343                     }
1344                     clean::SelfBorrowed(None, mtbl) => {
1345                         write!(args, "{}{}self", amp, mtbl.print_with_space());
1346                         write!(args_plain, "&{}self", mtbl.print_with_space());
1347                     }
1348                     clean::SelfExplicit(ref typ) => {
1349                         if f.alternate() {
1350                             write!(args, "self: {:#}", typ.print(cx));
1351                         } else {
1352                             write!(args, "self: {}", typ.print(cx));
1353                         }
1354                         write!(args_plain, "self: {:#}", typ.print(cx));
1355                     }
1356                 }
1357             } else {
1358                 if i > 0 {
1359                     args.push_str("<br>");
1360                 }
1361                 if input.is_const {
1362                     args.push_str("const ");
1363                     args_plain.push_str("const ");
1364                 }
1365                 write!(args, "{}: ", input.name);
1366                 write!(args_plain, "{}: ", input.name);
1367
1368                 if f.alternate() {
1369                     write!(args, "{:#}", input.type_.print(cx));
1370                 } else {
1371                     write!(args, "{}", input.type_.print(cx));
1372                 }
1373                 write!(args_plain, "{:#}", input.type_.print(cx));
1374             }
1375             if i + 1 < self.inputs.values.len() {
1376                 args.push_str(",");
1377                 args_plain.push_str(",");
1378             }
1379         }
1380
1381         let mut args_plain = format!("({})", args_plain.into_inner());
1382         let mut args = args.into_inner();
1383
1384         if self.c_variadic {
1385             args.push_str(",<br> ...");
1386             args_plain.push_str(", ...");
1387         }
1388
1389         let arrow_plain = format!("{:#}", self.output.print(cx));
1390         let arrow =
1391             if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) };
1392
1393         let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1394         let output = if declaration_len > 80 {
1395             let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1396             let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1397             format!(
1398                 "({pad}{args}{close}){arrow}",
1399                 pad = if self.inputs.values.is_empty() { "" } else { &full_pad },
1400                 args = args.replace("<br>", &full_pad),
1401                 close = close_pad,
1402                 arrow = arrow
1403             )
1404         } else {
1405             format!("({args}){arrow}", args = args.replace("<br>", " "), arrow = arrow)
1406         };
1407
1408         if f.alternate() {
1409             write!(f, "{}", output.replace("<br>", "\n"))
1410         } else {
1411             write!(f, "{}", output)
1412         }
1413     }
1414 }
1415
1416 pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
1417     visibility: Option<ty::Visibility<DefId>>,
1418     item_did: ItemId,
1419     cx: &'a Context<'tcx>,
1420 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1421     use std::fmt::Write as _;
1422
1423     let to_print: Cow<'static, str> = match visibility {
1424         None => "".into(),
1425         Some(ty::Visibility::Public) => "pub ".into(),
1426         Some(ty::Visibility::Restricted(vis_did)) => {
1427             // FIXME(camelid): This may not work correctly if `item_did` is a module.
1428             //                 However, rustdoc currently never displays a module's
1429             //                 visibility, so it shouldn't matter.
1430             let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1431
1432             if vis_did.is_crate_root() {
1433                 "pub(crate) ".into()
1434             } else if parent_module == Some(vis_did) {
1435                 // `pub(in foo)` where `foo` is the parent module
1436                 // is the same as no visibility modifier
1437                 "".into()
1438             } else if parent_module.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1439                 == Some(vis_did)
1440             {
1441                 "pub(super) ".into()
1442             } else {
1443                 let path = cx.tcx().def_path(vis_did);
1444                 debug!("path={:?}", path);
1445                 // modified from `resolved_path()` to work with `DefPathData`
1446                 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1447                 let anchor = anchor(vis_did, last_name, cx).to_string();
1448
1449                 let mut s = "pub(in ".to_owned();
1450                 for seg in &path.data[..path.data.len() - 1] {
1451                     let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1452                 }
1453                 let _ = write!(s, "{}) ", anchor);
1454                 s.into()
1455             }
1456         }
1457     };
1458     display_fn(move |f| write!(f, "{}", to_print))
1459 }
1460
1461 /// This function is the same as print_with_space, except that it renders no links.
1462 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1463 /// any HTML in it.
1464 pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
1465     visibility: Option<ty::Visibility<DefId>>,
1466     tcx: TyCtxt<'tcx>,
1467     item_did: DefId,
1468 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1469     let to_print = match visibility {
1470         None => String::new(),
1471         Some(ty::Visibility::Public) => "pub ".to_owned(),
1472         Some(ty::Visibility::Restricted(vis_did)) => {
1473             // FIXME(camelid): This may not work correctly if `item_did` is a module.
1474             //                 However, rustdoc currently never displays a module's
1475             //                 visibility, so it shouldn't matter.
1476             let parent_module = find_nearest_parent_module(tcx, item_did);
1477
1478             if vis_did.is_crate_root() {
1479                 "pub(crate) ".to_owned()
1480             } else if parent_module == Some(vis_did) {
1481                 // `pub(in foo)` where `foo` is the parent module
1482                 // is the same as no visibility modifier
1483                 String::new()
1484             } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1485                 == Some(vis_did)
1486             {
1487                 "pub(super) ".to_owned()
1488             } else {
1489                 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1490             }
1491         }
1492     };
1493     display_fn(move |f| f.write_str(&to_print))
1494 }
1495
1496 pub(crate) trait PrintWithSpace {
1497     fn print_with_space(&self) -> &str;
1498 }
1499
1500 impl PrintWithSpace for hir::Unsafety {
1501     fn print_with_space(&self) -> &str {
1502         match self {
1503             hir::Unsafety::Unsafe => "unsafe ",
1504             hir::Unsafety::Normal => "",
1505         }
1506     }
1507 }
1508
1509 impl PrintWithSpace for hir::IsAsync {
1510     fn print_with_space(&self) -> &str {
1511         match self {
1512             hir::IsAsync::Async => "async ",
1513             hir::IsAsync::NotAsync => "",
1514         }
1515     }
1516 }
1517
1518 impl PrintWithSpace for hir::Mutability {
1519     fn print_with_space(&self) -> &str {
1520         match self {
1521             hir::Mutability::Not => "",
1522             hir::Mutability::Mut => "mut ",
1523         }
1524     }
1525 }
1526
1527 pub(crate) fn print_constness_with_space(
1528     c: &hir::Constness,
1529     s: Option<ConstStability>,
1530 ) -> &'static str {
1531     match (c, s) {
1532         // const stable or when feature(staged_api) is not set
1533         (
1534             hir::Constness::Const,
1535             Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1536         )
1537         | (hir::Constness::Const, None) => "const ",
1538         // const unstable or not const
1539         _ => "",
1540     }
1541 }
1542
1543 impl clean::Import {
1544     pub(crate) fn print<'a, 'tcx: 'a>(
1545         &'a self,
1546         cx: &'a Context<'tcx>,
1547     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1548         display_fn(move |f| match self.kind {
1549             clean::ImportKind::Simple(name) => {
1550                 if name == self.source.path.last() {
1551                     write!(f, "use {};", self.source.print(cx))
1552                 } else {
1553                     write!(f, "use {} as {};", self.source.print(cx), name)
1554                 }
1555             }
1556             clean::ImportKind::Glob => {
1557                 if self.source.path.segments.is_empty() {
1558                     write!(f, "use *;")
1559                 } else {
1560                     write!(f, "use {}::*;", self.source.print(cx))
1561                 }
1562             }
1563         })
1564     }
1565 }
1566
1567 impl clean::ImportSource {
1568     pub(crate) fn print<'a, 'tcx: 'a>(
1569         &'a self,
1570         cx: &'a Context<'tcx>,
1571     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1572         display_fn(move |f| match self.did {
1573             Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1574             _ => {
1575                 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1576                     write!(f, "{}::", seg.name)?;
1577                 }
1578                 let name = self.path.last();
1579                 if let hir::def::Res::PrimTy(p) = self.path.res {
1580                     primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1581                 } else {
1582                     write!(f, "{}", name)?;
1583                 }
1584                 Ok(())
1585             }
1586         })
1587     }
1588 }
1589
1590 impl clean::TypeBinding {
1591     pub(crate) fn print<'a, 'tcx: 'a>(
1592         &'a self,
1593         cx: &'a Context<'tcx>,
1594     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1595         display_fn(move |f| {
1596             f.write_str(self.assoc.name.as_str())?;
1597             if f.alternate() {
1598                 write!(f, "{:#}", self.assoc.args.print(cx))?;
1599             } else {
1600                 write!(f, "{}", self.assoc.args.print(cx))?;
1601             }
1602             match self.kind {
1603                 clean::TypeBindingKind::Equality { ref term } => {
1604                     if f.alternate() {
1605                         write!(f, " = {:#}", term.print(cx))?;
1606                     } else {
1607                         write!(f, " = {}", term.print(cx))?;
1608                     }
1609                 }
1610                 clean::TypeBindingKind::Constraint { ref bounds } => {
1611                     if !bounds.is_empty() {
1612                         if f.alternate() {
1613                             write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1614                         } else {
1615                             write!(f, ":&nbsp;{}", print_generic_bounds(bounds, cx))?;
1616                         }
1617                     }
1618                 }
1619             }
1620             Ok(())
1621         })
1622     }
1623 }
1624
1625 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1626     display_fn(move |f| {
1627         let quot = if f.alternate() { "\"" } else { "&quot;" };
1628         match abi {
1629             Abi::Rust => Ok(()),
1630             abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1631         }
1632     })
1633 }
1634
1635 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1636     if v { "default " } else { "" }
1637 }
1638
1639 impl clean::GenericArg {
1640     pub(crate) fn print<'a, 'tcx: 'a>(
1641         &'a self,
1642         cx: &'a Context<'tcx>,
1643     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1644         display_fn(move |f| match self {
1645             clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1646             clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1647             clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1648             clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1649         })
1650     }
1651 }
1652
1653 impl clean::types::Term {
1654     pub(crate) fn print<'a, 'tcx: 'a>(
1655         &'a self,
1656         cx: &'a Context<'tcx>,
1657     ) -> impl fmt::Display + 'a + Captures<'tcx> {
1658         display_fn(move |f| match self {
1659             clean::types::Term::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1660             clean::types::Term::Constant(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1661         })
1662     }
1663 }
1664
1665 pub(crate) fn display_fn(
1666     f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1667 ) -> impl fmt::Display {
1668     struct WithFormatter<F>(Cell<Option<F>>);
1669
1670     impl<F> fmt::Display for WithFormatter<F>
1671     where
1672         F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1673     {
1674         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1675             (self.0.take()).unwrap()(f)
1676         }
1677     }
1678
1679     WithFormatter(Cell::new(Some(f)))
1680 }