1 //! HTML formatting module
3 //! This module contains a large number of `fmt::Display` implementations for
4 //! various types in `rustdoc::clean`.
6 //! These implementations all emit HTML. As an internal implementation detail,
7 //! some of them support an alternate format that emits text, but that should
8 //! not be used external to this module.
12 use std
::fmt
::{self, Write}
;
13 use std
::iter
::{self, once}
;
16 use rustc_attr
::{ConstStability, StabilityLevel}
;
17 use rustc_data_structures
::captures
::Captures
;
18 use rustc_data_structures
::fx
::FxHashSet
;
20 use rustc_hir
::def
::DefKind
;
21 use rustc_hir
::def_id
::DefId
;
22 use rustc_metadata
::creader
::{CStore, LoadedMacro}
;
24 use rustc_middle
::ty
::TyCtxt
;
25 use rustc_span
::symbol
::kw
;
26 use rustc_span
::{sym, Symbol}
;
27 use rustc_target
::spec
::abi
::Abi
;
29 use itertools
::Itertools
;
32 self, types
::ExternalLocation
, utils
::find_nearest_parent_module
, ExternalCrate
, ItemId
,
35 use crate::formats
::item_type
::ItemType
;
36 use crate::html
::escape
::Escape
;
37 use crate::html
::render
::Context
;
38 use crate::passes
::collect_intra_doc_links
::UrlFragment
;
40 use super::url_parts_builder
::estimate_item_path_byte_length
;
41 use super::url_parts_builder
::UrlPartsBuilder
;
43 pub(crate) trait Print
{
44 fn print(self, buffer
: &mut Buffer
);
49 F
: FnOnce(&mut Buffer
),
51 fn print(self, buffer
: &mut Buffer
) {
56 impl Print
for String
{
57 fn print(self, buffer
: &mut Buffer
) {
58 buffer
.write_str(&self);
62 impl Print
for &'_
str {
63 fn print(self, buffer
: &mut Buffer
) {
64 buffer
.write_str(self);
68 #[derive(Debug, Clone)]
69 pub(crate) struct Buffer
{
74 impl core
::fmt
::Write
for Buffer
{
76 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
77 self.buffer
.write_str(s
)
81 fn write_char(&mut self, c
: char) -> fmt
::Result
{
82 self.buffer
.write_char(c
)
86 fn write_fmt(&mut self, args
: fmt
::Arguments
<'_
>) -> fmt
::Result
{
87 self.buffer
.write_fmt(args
)
92 pub(crate) fn empty_from(v
: &Buffer
) -> Buffer
{
93 Buffer { for_html: v.for_html, buffer: String::new() }
96 pub(crate) fn html() -> Buffer
{
97 Buffer { for_html: true, buffer: String::new() }
100 pub(crate) fn new() -> Buffer
{
101 Buffer { for_html: false, buffer: String::new() }
104 pub(crate) fn is_empty(&self) -> bool
{
105 self.buffer
.is_empty()
108 pub(crate) fn into_inner(self) -> String
{
112 pub(crate) fn push_str(&mut self, s
: &str) {
113 self.buffer
.push_str(s
);
116 pub(crate) fn push_buffer(&mut self, other
: Buffer
) {
117 self.buffer
.push_str(&other
.buffer
);
120 // Intended for consumption by write! and writeln! (std::fmt) but without
121 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
123 pub(crate) fn write_str(&mut self, s
: &str) {
124 self.buffer
.push_str(s
);
127 // Intended for consumption by write! and writeln! (std::fmt) but without
128 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
130 pub(crate) fn write_fmt(&mut self, v
: fmt
::Arguments
<'_
>) {
131 self.buffer
.write_fmt(v
).unwrap();
134 pub(crate) fn to_display
<T
: Print
>(mut self, t
: T
) -> String
{
139 pub(crate) fn reserve(&mut self, additional
: usize) {
140 self.buffer
.reserve(additional
)
143 pub(crate) fn len(&self) -> usize {
148 pub(crate) fn comma_sep
<T
: fmt
::Display
>(
149 items
: impl Iterator
<Item
= T
>,
150 space_after_comma
: bool
,
151 ) -> impl fmt
::Display
{
152 display_fn(move |f
| {
153 for (i
, item
) in items
.enumerate() {
155 write
!(f
, ",{}", if space_after_comma { " " }
else { "" }
)?
;
157 fmt
::Display
::fmt(&item
, f
)?
;
163 pub(crate) fn print_generic_bounds
<'a
, 'tcx
: 'a
>(
164 bounds
: &'a
[clean
::GenericBound
],
165 cx
: &'a Context
<'tcx
>,
166 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
167 display_fn(move |f
| {
168 let mut bounds_dup
= FxHashSet
::default();
170 for (i
, bound
) in bounds
.iter().filter(|b
| bounds_dup
.insert(b
.clone())).enumerate() {
174 fmt
::Display
::fmt(&bound
.print(cx
), f
)?
;
180 impl clean
::GenericParamDef
{
181 pub(crate) fn print
<'a
, 'tcx
: 'a
>(
183 cx
: &'a Context
<'tcx
>,
184 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
185 display_fn(move |f
| match &self.kind
{
186 clean
::GenericParamDefKind
::Lifetime { outlives }
=> {
187 write
!(f
, "{}", self.name
)?
;
189 if !outlives
.is_empty() {
191 for (i
, lt
) in outlives
.iter().enumerate() {
195 write
!(f
, "{}", lt
.print())?
;
201 clean
::GenericParamDefKind
::Type { bounds, default, .. }
=> {
202 f
.write_str(self.name
.as_str())?
;
204 if !bounds
.is_empty() {
206 write
!(f
, ": {:#}", print_generic_bounds(bounds
, cx
))?
;
208 write
!(f
, ": {}", print_generic_bounds(bounds
, cx
))?
;
212 if let Some(ref ty
) = default {
214 write
!(f
, " = {:#}", ty
.print(cx
))?
;
216 write
!(f
, " = {}", ty
.print(cx
))?
;
222 clean
::GenericParamDefKind
::Const { ty, default, .. }
=> {
224 write
!(f
, "const {}: {:#}", self.name
, ty
.print(cx
))?
;
226 write
!(f
, "const {}: {}", self.name
, ty
.print(cx
))?
;
229 if let Some(default) = default {
231 write
!(f
, " = {:#}", default)?
;
233 write
!(f
, " = {}", default)?
;
243 impl clean
::Generics
{
244 pub(crate) fn print
<'a
, 'tcx
: 'a
>(
246 cx
: &'a Context
<'tcx
>,
247 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
248 display_fn(move |f
| {
249 let mut real_params
=
250 self.params
.iter().filter(|p
| !p
.is_synthetic_type_param()).peekable();
251 if real_params
.peek().is_none() {
256 write
!(f
, "<{:#}>", comma_sep(real_params
.map(|g
| g
.print(cx
)), true))
258 write
!(f
, "<{}>", comma_sep(real_params
.map(|g
| g
.print(cx
)), true))
264 #[derive(Clone, Copy, PartialEq, Eq)]
265 pub(crate) enum Ending
{
270 /// * The Generics from which to emit a where-clause.
271 /// * The number of spaces to indent each line with.
272 /// * Whether the where-clause needs to add a comma and newline after the last bound.
273 pub(crate) fn print_where_clause
<'a
, 'tcx
: 'a
>(
274 gens
: &'a clean
::Generics
,
275 cx
: &'a Context
<'tcx
>,
278 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
279 display_fn(move |f
| {
280 let mut where_predicates
= gens
.where_predicates
.iter().filter(|pred
| {
281 !matches
!(pred
, clean
::WherePredicate
::BoundPredicate { bounds, .. }
if bounds
.is_empty())
283 display_fn(move |f
| {
291 clean
::WherePredicate
::BoundPredicate { ty, bounds, bound_params }
=> {
292 let ty_cx
= ty
.print(cx
);
293 let generic_bounds
= print_generic_bounds(bounds
, cx
);
295 if bound_params
.is_empty() {
297 write
!(f
, "{ty_cx:#}: {generic_bounds:#}")
299 write
!(f
, "{ty_cx}: {generic_bounds}")
305 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
306 comma_sep(bound_params
.iter().map(|lt
| lt
.print(cx
)), true)
311 "for<{}> {ty_cx}: {generic_bounds}",
312 comma_sep(bound_params
.iter().map(|lt
| lt
.print(cx
)), true)
317 clean
::WherePredicate
::RegionPredicate { lifetime, bounds }
=> {
318 let mut bounds_display
= String
::new();
319 for bound
in bounds
.iter().map(|b
| b
.print(cx
)) {
320 write
!(bounds_display
, "{bound} + ")?
;
322 bounds_display
.truncate(bounds_display
.len() - " + ".len());
323 write
!(f
, "{}: {bounds_display}", lifetime
.print())
325 // FIXME(fmease): Render bound params.
326 clean
::WherePredicate
::EqPredicate { lhs, rhs, bound_params: _ }
=> {
328 write
!(f
, "{:#} == {:#}", lhs
.print(cx
), rhs
.print(cx
))
330 write
!(f
, "{} == {}", lhs
.print(cx
), rhs
.print(cx
))
337 if where_predicates
.peek().is_none() {
341 let where_preds
= comma_sep(where_predicates
, false);
342 let clause
= if f
.alternate() {
343 if ending
== Ending
::Newline
{
344 format
!(" where{where_preds},")
346 format
!(" where{where_preds}")
349 let mut br_with_padding
= String
::with_capacity(6 * indent
+ 28);
350 br_with_padding
.push_str("\n");
353 if ending
== Ending
::Newline { indent + 4 }
else { indent + "fn where ".len() }
;
355 for _
in 0..padding_amount
{
356 br_with_padding
.push_str(" ");
358 let where_preds
= where_preds
.to_string().replace('
\n'
, &br_with_padding
);
360 if ending
== Ending
::Newline
{
361 let mut clause
= " ".repeat(indent
.saturating_sub(1));
362 write
!(clause
, "<span class=\"where fmt-newline\">where{where_preds},</span>")?
;
365 // insert a newline after a single space but before multiple spaces at the start
367 format
!("\n<span class=\"where\">where{where_preds}</span>")
369 // put the first one on the same line as the 'where' keyword
370 let where_preds
= where_preds
.replacen(&br_with_padding
, " ", 1);
372 let mut clause
= br_with_padding
;
373 clause
.truncate(clause
.len() - "where ".len());
375 write
!(clause
, "<span class=\"where\">where{where_preds}</span>")?
;
380 write
!(f
, "{clause}")
384 impl clean
::Lifetime
{
385 pub(crate) fn print(&self) -> impl fmt
::Display
+ '_
{
390 impl clean
::Constant
{
391 pub(crate) fn print(&self, tcx
: TyCtxt
<'_
>) -> impl fmt
::Display
+ '_
{
392 let expr
= self.expr(tcx
);
395 if f
.alternate() { f.write_str(&expr) }
else { write!(f, "{}
", Escape(&expr)) }
401 impl clean::PolyTrait {
402 fn print<'a, 'tcx: 'a>(
404 cx: &'a Context<'tcx>,
405 ) -> impl fmt::Display + 'a + Captures<'tcx> {
406 display_fn(move |f| {
407 if !self.generic_params.is_empty() {
412 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
418 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
423 write!(f, "{:#}
", self.trait_.print(cx))
425 write!(f, "{}
", self.trait_.print(cx))
431 impl clean::GenericBound {
432 pub(crate) fn print<'a, 'tcx: 'a>(
434 cx: &'a Context<'tcx>,
435 ) -> impl fmt::Display + 'a + Captures<'tcx> {
436 display_fn(move |f| match self {
437 clean::GenericBound::Outlives(lt) => write!(f, "{}
", lt.print()),
438 clean::GenericBound::TraitBound(ty, modifier) => {
439 let modifier_str = match modifier {
440 hir::TraitBoundModifier::None => "",
441 hir::TraitBoundModifier::Maybe => "?
",
442 // ~const is experimental; do not display those bounds in rustdoc
443 hir::TraitBoundModifier::MaybeConst => "",
446 write!(f, "{}{:#}
", modifier_str, ty.print(cx))
448 write!(f, "{}{}
", modifier_str, ty.print(cx))
455 impl clean::GenericArgs {
456 fn print<'a, 'tcx: 'a>(
458 cx: &'a Context<'tcx>,
459 ) -> impl fmt::Display + 'a + Captures<'tcx> {
460 display_fn(move |f| {
462 clean::GenericArgs::AngleBracketed { args, bindings } => {
463 if !args.is_empty() || !bindings.is_empty() {
467 f.write_str("<
;")?;
469 let mut comma = false;
470 for arg in args.iter() {
476 write!(f, "{:#}
", arg.print(cx))?;
478 write!(f, "{}
", arg.print(cx))?;
481 for binding in bindings.iter() {
487 write!(f, "{:#}
", binding.print(cx))?;
489 write!(f, "{}
", binding.print(cx))?;
495 f.write_str(">
;")?;
499 clean::GenericArgs::Parenthesized { inputs, output } => {
501 let mut comma = false;
502 for ty in inputs.iter() {
508 write!(f, "{:#}
", ty.print(cx))?;
510 write!(f, "{}
", ty.print(cx))?;
514 if let Some(ref ty) = *output {
516 write!(f, " -> {:#}
", ty.print(cx))?;
518 write!(f, " ->
; {}
", ty.print(cx))?;
528 // Possible errors when computing href link source for a `DefId`
529 #[derive(PartialEq, Eq)]
530 pub(crate) enum HrefError {
531 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
533 /// This can only happen for non-local items.
537 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
538 /// implements it for a local type.
539 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
542 /// rustc a.rs --crate-type=lib
543 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
546 /// Now, the associated items in the trait impl want to link to the corresponding item in the
547 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
548 /// *documentation (was) not built*.
549 DocumentationNotBuilt,
550 /// This can only happen for non-local items when `--document-private-items` is not passed.
552 // Not in external cache, href link should be in same page
556 // Panics if `syms` is empty.
557 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
558 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
559 s.push_str(syms[0].as_str());
560 for sym in &syms[1..] {
562 s.push_str(sym.as_str());
567 /// This function is to get the external macro path because they are not in the cache used in
568 /// `href_with_root_path`.
569 fn generate_macro_def_id_path(
572 root_path: Option<&str>,
573 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
574 let tcx = cx.shared.tcx;
575 let crate_name = tcx.crate_name(def_id.krate);
576 let cache = cx.cache();
578 let fqp: Vec<Symbol> = tcx
583 // extern blocks (and a few others things) have an empty name.
584 match elem.data.get_opt_name() {
585 Some(s) if !s.is_empty() => Some(s),
590 let mut relative = fqp.iter().copied();
591 let cstore = CStore::from_tcx(tcx);
592 // We need this to prevent a `panic` when this function is used from intra doc links...
593 if !cstore.has_crate_data(def_id.krate) {
594 debug!("No data
for crate {}
", crate_name);
595 return Err(HrefError::NotInExternalCache);
597 // Check to see if it is a macro 2.0 or built-in macro.
598 // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
599 let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
600 LoadedMacro::MacroDef(def, _) => {
601 // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
602 matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
607 let mut path = if is_macro_2 {
608 once(crate_name).chain(relative).collect()
610 vec![crate_name, relative.next_back().unwrap()]
613 // The minimum we can have is the crate name followed by the macro name. If shorter, then
614 // it means that `relative` was empty, which is an error.
615 debug!("macro path cannot be empty
!");
616 return Err(HrefError::NotInExternalCache);
619 if let Some(last) = path.last_mut() {
620 *last = Symbol::intern(&format!("macro.{}
.html
", last.as_str()));
623 let url = match cache.extern_locations[&def_id.krate] {
624 ExternalLocation::Remote(ref s) => {
625 // `ExternalLocation::Remote` always end with a `/`.
626 format!("{}{}
", s, path.iter().map(|p| p.as_str()).join("/"))
628 ExternalLocation::Local => {
629 // `root_path` always end with a `/`.
632 root_path.unwrap_or(""),
634 path.iter().map(|p| p.as_str()).join("/")
637 ExternalLocation::Unknown => {
638 debug!("crate {} not
in cache when linkifying macros
", crate_name);
639 return Err(HrefError::NotInExternalCache);
642 Ok((url, ItemType::Macro, fqp))
645 pub(crate) fn href_with_root_path(
648 root_path: Option<&str>,
649 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
651 let def_kind = tcx.def_kind(did);
652 let did = match def_kind {
653 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
654 // documented on their parent's page
659 let cache = cx.cache();
660 let relative_to = &cx.current;
661 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
662 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
666 && !cache.effective_visibilities.is_directly_public(tcx, did)
667 && !cache.document_private
668 && !cache.primitive_locations.values().any(|&id| id == did)
670 return Err(HrefError::Private);
673 let mut is_remote = false;
674 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
675 Some(&(ref fqp, shortty)) => (fqp, shortty, {
676 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
677 debug!(?fqp, ?shortty, ?module_fqp);
678 href_relative_parts(module_fqp, relative_to).collect()
681 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
682 let module_fqp = to_module_fqp(shortty, fqp);
686 match cache.extern_locations[&did.krate] {
687 ExternalLocation::Remote(ref s) => {
689 let s = s.trim_end_matches('/');
690 let mut builder = UrlPartsBuilder::singleton(s);
691 builder.extend(module_fqp.iter().copied());
694 ExternalLocation::Local => {
695 href_relative_parts(module_fqp, relative_to).collect()
697 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
700 } else if matches!(def_kind, DefKind::Macro(_)) {
701 return generate_macro_def_id_path(did, cx, root_path);
703 return Err(HrefError::NotInExternalCache);
707 if !is_remote && let Some(root_path) = root_path {
708 let root = root_path.trim_end_matches('/');
709 url_parts.push_front(root);
713 ItemType::Module => {
714 url_parts.push("index
.html
");
717 let prefix = shortty.as_str();
718 let last = fqp.last().unwrap();
719 url_parts.push_fmt(format_args!("{}
.{}
.html
", prefix, last));
722 Ok((url_parts.finish(), shortty, fqp.to_vec()))
728 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
729 href_with_root_path(did, cx, None)
732 /// Both paths should only be modules.
733 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
734 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
735 pub(crate) fn href_relative_parts<'fqp>(
737 relative_to_fqp: &[Symbol],
738 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
739 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
740 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
742 let dissimilar_part_count = relative_to_fqp.len() - i;
743 let fqp_module = &fqp[i..fqp.len()];
745 iter::repeat(sym::dotdot)
746 .take(dissimilar_part_count)
747 .chain(fqp_module.iter().copied()),
751 // e.g. linking to std::sync::atomic from std::sync
752 if relative_to_fqp.len() < fqp.len() {
753 Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
754 // e.g. linking to std::sync from std::sync::atomic
755 } else if fqp.len() < relative_to_fqp.len() {
756 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
757 Box::new(iter::repeat(sym::dotdot).take(dissimilar_part_count))
758 // linking to the same module
760 Box::new(iter::empty())
764 pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Context<'_>) -> String {
765 let cache = cx.cache();
766 let Some((fqp, shortty)) = cache.paths.get(&did)
767 .or_else(|| cache.external_paths.get(&did))
768 else { return String::new() };
769 let mut buf = Buffer::new();
770 let fqp = if *shortty == ItemType::Primitive {
771 // primitives are documented in a crate, but not actually part of it
772 &fqp[fqp.len() - 1..]
776 if let &Some(UrlFragment::Item(id)) = fragment {
777 write!(buf, "{}
", cx.tcx().def_descr(id));
778 for component in fqp {
779 write!(buf, "{component}
::");
781 write!(buf, "{}
", cx.tcx().item_name(id));
782 } else if !fqp.is_empty() {
783 let mut fqp_it = fqp.into_iter();
784 write!(buf, "{shortty} {}
", fqp_it.next().unwrap());
785 for component in fqp_it {
786 write!(buf, "::{component}
");
792 /// Used to render a [`clean::Path`].
793 fn resolved_path<'cx>(
794 w: &mut fmt::Formatter<'_>,
799 cx: &'cx Context<'_>,
801 let last = path.segments.last().unwrap();
804 for seg in &path.segments[..path.segments.len() - 1] {
805 write!(w, "{}
::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
809 write!(w, "{}{:#}
", &last.name, last.args.print(cx))?;
811 let path = if use_absolute {
812 if let Ok((_, _, fqp)) = href(did, cx) {
815 join_with_double_colon(&fqp[..fqp.len() - 1]),
816 anchor(did, *fqp.last().unwrap(), cx)
819 last.name.to_string()
822 anchor(did, last.name, cx).to_string()
824 write!(w, "{}{}
", path, last.args.print(cx))?;
830 f: &mut fmt::Formatter<'_>,
831 prim: clean::PrimitiveType,
835 primitive_link_fragment(f, prim, name, "", cx)
838 fn primitive_link_fragment(
839 f: &mut fmt::Formatter<'_>,
840 prim: clean::PrimitiveType,
846 let mut needs_termination = false;
848 match m.primitive_locations.get(&prim) {
849 Some(&def_id) if def_id.is_local() => {
850 let len = cx.current.len();
851 let len = if len == 0 { 0 } else { len - 1 };
854 "<a class
=\"primitive
\" href
=\"{}primitive
.{}
.html{fragment}
\">",
858 needs_termination = true;
861 let loc = match m.extern_locations[&def_id.krate] {
862 ExternalLocation::Remote(ref s) => {
863 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
864 let builder: UrlPartsBuilder =
865 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
870 ExternalLocation::Local => {
871 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
872 Some(if cx.current.first() == Some(&cname_sym) {
873 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
875 iter::repeat(sym::dotdot)
876 .take(cx.current.len())
877 .chain(iter::once(cname_sym))
881 ExternalLocation::Unknown => None,
883 if let Some(mut loc) = loc {
884 loc.push_fmt(format_args!("primitive
.{}
.html
", prim.as_sym()));
885 write!(f, "<a class
=\"primitive
\" href
=\"{}{fragment}
\">", loc.finish())?;
886 needs_termination = true;
892 write!(f, "{}
", name)?;
893 if needs_termination {
899 /// Helper to render type parameters
900 fn tybounds<'a, 'tcx: 'a>(
901 bounds: &'a [clean::PolyTrait],
902 lt: &'a Option<clean::Lifetime>,
903 cx: &'a Context<'tcx>,
904 ) -> impl fmt::Display + 'a + Captures<'tcx> {
905 display_fn(move |f| {
906 for (i, bound) in bounds.iter().enumerate() {
911 fmt::Display::fmt(&bound.print(cx), f)?;
914 if let Some(lt) = lt {
916 fmt::Display::fmt(<.print(), f)?;
922 pub(crate) fn anchor<'a, 'cx: 'a>(
925 cx: &'cx Context<'_>,
926 ) -> impl fmt::Display + 'a {
927 let parts = href(did, cx);
928 display_fn(move |f| {
929 if let Ok((url, short_ty, fqp)) = parts {
932 r#"<a class
="{}" href
="{}" title
="{} {}">{}
</a
>"#,
936 join_with_double_colon(&fqp),
940 write!(f, "{}
", text)
947 f: &mut fmt::Formatter<'_>,
949 cx: &'cx Context<'_>,
951 trace!("fmt_type(t
= {:?}
)", t);
954 clean::Generic(name) => write!(f, "{}
", name),
955 clean::Type::Path { ref path } => {
956 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
957 let did = path.def_id();
958 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
960 clean::DynTrait(ref bounds, ref lt) => {
961 f.write_str("dyn ")?;
962 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
964 clean::Infer => write!(f, "_
"),
965 clean::Primitive(clean::PrimitiveType::Never) => {
966 primitive_link(f, PrimitiveType::Never, "!", cx)
968 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
969 clean::BareFunction(ref decl) => {
974 decl.print_hrtb_with_space(cx),
975 decl.unsafety.print_with_space(),
976 print_abi_with_space(decl.abi),
983 decl.print_hrtb_with_space(cx),
984 decl.unsafety.print_with_space(),
985 print_abi_with_space(decl.abi)
987 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
988 write!(f, "{}
", decl.decl.print(cx))
991 clean::Tuple(ref typs) => {
993 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
995 if let clean::Generic(name) = one {
996 primitive_link(f, PrimitiveType::Tuple, &format!("({name}
,)"), cx)
999 // Carry `f.alternate()` into this display w/o branching manually.
1000 fmt::Display::fmt(&one.print(cx), f)?;
1005 let generic_names: Vec<Symbol> = many
1007 .filter_map(|t| match t {
1008 clean::Generic(name) => Some(*name),
1012 let is_generic = generic_names.len() == many.len();
1016 PrimitiveType::Tuple,
1017 &format!("({}
)", generic_names.iter().map(|s| s.as_str()).join(", ")),
1022 for (i, item) in many.iter().enumerate() {
1026 // Carry `f.alternate()` into this display w/o branching manually.
1027 fmt::Display::fmt(&item.print(cx), f)?;
1034 clean::Slice(ref t) => match **t {
1035 clean::Generic(name) => {
1036 primitive_link(f, PrimitiveType::Slice, &format!("[{name}
]"), cx)
1040 fmt::Display::fmt(&t.print(cx), f)?;
1044 clean::Array(ref t, ref n) => match **t {
1045 clean::Generic(name) if !f.alternate() => primitive_link(
1047 PrimitiveType::Array,
1048 &format!("[{name}
; {n}
]", n = Escape(n)),
1053 fmt::Display::fmt(&t.print(cx), f)?;
1055 write!(f, "; {n}
")?;
1058 primitive_link(f, PrimitiveType::Array, &format!("{n}
", n = Escape(n)), cx)?;
1063 clean::RawPointer(m, ref t) => {
1065 hir::Mutability::Mut => "mut",
1066 hir::Mutability::Not => "const",
1069 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1070 let text = if f.alternate() {
1071 format!("*{} {:#}
", m, t.print(cx))
1073 format!("*{} {}
", m, t.print(cx))
1075 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1077 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{}
", m), cx)?;
1078 fmt::Display::fmt(&t.print(cx), f)
1081 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1083 Some(l) => format!("{}
", l.print()),
1086 let m = mutability.print_with_space();
1087 let amp = if f.alternate() { "&" } else { "&" };
1089 clean::DynTrait(ref bounds, ref trait_lt)
1090 if bounds.len() > 1 || trait_lt.is_some() =>
1092 write!(f, "{}{}{}
(", amp, lt, m)?;
1093 fmt_type(ty, f, use_absolute, cx)?;
1096 clean::Generic(name) => {
1097 primitive_link(f, PrimitiveType::Reference, &format!("{amp}{lt}{m}{name}
"), cx)
1100 write!(f, "{}{}{}
", amp, lt, m)?;
1101 fmt_type(ty, f, use_absolute, cx)
1105 clean::ImplTrait(ref bounds) => {
1107 write!(f, "impl {:#}
", print_generic_bounds(bounds, cx))
1109 write!(f, "impl {}
", print_generic_bounds(bounds, cx))
1112 clean::QPath(box clean::QPathData {
1119 if should_show_cast {
1120 write!(f, "<{:#}
as {:#}
>::", self_type.print(cx), trait_.print(cx))?
1122 write!(f, "{:#}
::", self_type.print(cx))?
1125 if should_show_cast {
1126 write!(f, "<
;{}
as {}
>
;::", self_type.print(cx), trait_.print(cx))?
1128 write!(f, "{}
::", self_type.print(cx))?
1131 // It's pretty unsightly to look at `<A as B>::C` in output, and
1132 // we've got hyperlinking on our side, so try to avoid longer
1133 // notation as much as possible by making `C` a hyperlink to trait
1134 // `B` to disambiguate.
1136 // FIXME: this is still a lossy conversion and there should probably
1137 // be a better way of representing this in general? Most of
1138 // the ugliness comes from inlining across crates where
1139 // everything comes in as a fully resolved QPath (hard to
1141 if !f.alternate() && let Ok((url, _, path)) = href(trait_.def_id(), cx) {
1144 "<a class
=\"associatedtype
\" href
=\"{url}
#{shortty}.{name}\" \
1145 title=\"type {path}::{name}\">{name}</a>",
1146 shortty = ItemType::AssocType,
1148 path = join_with_double_colon(&path),
1151 write!(f, "{}", assoc.name)
1154 // Carry `f.alternate()` into this display w/o branching manually.
1155 fmt::Display::fmt(&assoc.args.print(cx), f)
1161 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1163 cx: &'a Context<'tcx>,
1164 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1165 display_fn(move |f| fmt_type(self, f, false, cx))
1170 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1172 cx: &'a Context<'tcx>,
1173 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1174 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1179 pub(crate) fn print<'a, 'tcx: 'a>(
1182 cx: &'a Context<'tcx>,
1183 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1184 display_fn(move |f| {
1186 write!(f, "impl{:#} ", self.generics.print(cx))?;
1188 write!(f, "impl{} ", self.generics.print(cx))?;
1191 if let Some(ref ty) = self.trait_ {
1192 match self.polarity {
1193 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1194 ty::ImplPolarity::Negative => write!(f, "!")?,
1196 fmt::Display::fmt(&ty.print(cx), f)?;
1197 write!(f, " for ")?;
1200 if let clean::Type::Tuple(types) = &self.for_ &&
1201 let [clean::Type::Generic(name)] = &types[..] &&
1202 (self.kind.is_fake_variadic() || self.kind.is_auto())
1204 // Hardcoded anchor library/core/src/primitive_docs.rs
1205 // Link should match `# Trait implementations`
1206 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1207 } else if let clean::BareFunction(bare_fn) = &self.for_ &&
1208 let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
1209 (self.kind.is_fake_variadic() || self.kind.is_auto())
1211 // Hardcoded anchor library/core/src/primitive_docs.rs
1212 // Link should match `# Trait implementations`
1214 let hrtb = bare_fn.print_hrtb_with_space(cx);
1215 let unsafety = bare_fn.unsafety.print_with_space();
1216 let abi = print_abi_with_space(bare_fn.abi);
1220 "{hrtb:#}{unsafety}{abi:#}",
1225 "{hrtb}{unsafety}{abi}",
1228 let ellipsis = if bare_fn.decl.c_variadic {
1233 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
1235 if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
1237 fmt_type(ty, f, use_absolute, cx)?;
1239 } else if let Some(ty) = self.kind.as_blanket_ty() {
1240 fmt_type(ty, f, use_absolute, cx)?;
1242 fmt_type(&self.for_, f, use_absolute, cx)?;
1245 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
1251 impl clean::Arguments {
1252 pub(crate) fn print<'a, 'tcx: 'a>(
1254 cx: &'a Context<'tcx>,
1255 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1256 display_fn(move |f| {
1257 for (i, input) in self.values.iter().enumerate() {
1258 write!(f, "{}: ", input.name)?;
1261 write!(f, "{:#}", input.type_.print(cx))?;
1263 write!(f, "{}", input.type_.print(cx))?;
1265 if i + 1 < self.values.len() {
1274 impl clean::FnRetTy {
1275 pub(crate) fn print<'a, 'tcx: 'a>(
1277 cx: &'a Context<'tcx>,
1278 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1279 display_fn(move |f| match self {
1280 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1281 clean::Return(ty) if f.alternate() => {
1282 write!(f, " -> {:#}", ty.print(cx))
1284 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1285 clean::DefaultReturn => Ok(()),
1290 impl clean::BareFunctionDecl {
1291 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1293 cx: &'a Context<'tcx>,
1294 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1295 display_fn(move |f| {
1296 if !self.generic_params.is_empty() {
1300 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1309 // Implements Write but only counts the bytes "written".
1310 struct WriteCounter(usize);
1312 impl std::fmt::Write for WriteCounter {
1313 fn write_str(&mut self, s: &str) -> fmt::Result {
1319 // Implements Display by emitting the given number of spaces.
1320 struct Indent(usize);
1322 impl fmt::Display for Indent {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 (0..self.0).for_each(|_| {
1325 f.write_char(' ').unwrap();
1331 impl clean::FnDecl {
1332 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1334 cx: &'a Context<'tcx>,
1335 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1336 display_fn(move |f| {
1337 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1341 "({args:#}{ellipsis}){arrow:#}",
1342 args = self.inputs.print(cx),
1343 ellipsis = ellipsis,
1344 arrow = self.output.print(cx)
1349 "({args}{ellipsis}){arrow}",
1350 args = self.inputs.print(cx),
1351 ellipsis = ellipsis,
1352 arrow = self.output.print(cx)
1358 /// * `header_len`: The length of the function header and name. In other words, the number of
1359 /// characters in the function declaration up to but not including the parentheses.
1360 /// This is expected to go into a `<pre>`/`code-header` block, so indentation and newlines
1362 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1364 pub(crate) fn full_print<'a, 'tcx: 'a>(
1368 cx: &'a Context<'tcx>,
1369 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1370 display_fn(move |f| {
1371 // First, generate the text form of the declaration, with no line wrapping, and count the bytes.
1372 let mut counter = WriteCounter(0);
1373 write!(&mut counter, "{:#}", display_fn(|f| { self.inner_full_print(None, f, cx) }))
1375 // If the text form was over 80 characters wide, we will line-wrap our output.
1376 let line_wrapping_indent =
1377 if header_len + counter.0 > 80 { Some(indent) } else { None };
1378 // Generate the final output. This happens to accept `{:#}` formatting to get textual
1379 // output but in practice it is only formatted with `{}` to get HTML output.
1380 self.inner_full_print(line_wrapping_indent, f, cx)
1384 fn inner_full_print(
1386 // For None, the declaration will not be line-wrapped. For Some(n),
1387 // the declaration will be line-wrapped, with an indent of n spaces.
1388 line_wrapping_indent: Option<usize>,
1389 f: &mut fmt::Formatter<'_>,
1392 let amp = if f.alternate() { "&" } else { "&" };
1395 if let Some(n) = line_wrapping_indent {
1396 write!(f, "\n{}", Indent(n + 4))?;
1398 for (i, input) in self.inputs.values.iter().enumerate() {
1400 match line_wrapping_indent {
1401 None => write!(f, ", ")?,
1402 Some(n) => write!(f, ",\n{}", Indent(n + 4))?,
1405 if let Some(selfty) = input.to_self() {
1407 clean::SelfValue => {
1410 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1411 write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?;
1413 clean::SelfBorrowed(None, mtbl) => {
1414 write!(f, "{}{}self", amp, mtbl.print_with_space())?;
1416 clean::SelfExplicit(ref typ) => {
1417 write!(f, "self: ")?;
1418 fmt::Display::fmt(&typ.print(cx), f)?;
1423 write!(f, "const ")?;
1425 write!(f, "{}: ", input.name)?;
1426 fmt::Display::fmt(&input.type_.print(cx), f)?;
1430 if self.c_variadic {
1431 match line_wrapping_indent {
1432 None => write!(f, ", ...")?,
1433 Some(n) => write!(f, "\n{}...", Indent(n + 4))?,
1437 match line_wrapping_indent {
1438 None => write!(f, ")")?,
1439 Some(n) => write!(f, "\n{})", Indent(n))?,
1442 fmt::Display::fmt(&self.output.print(cx), f)?;
1447 pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
1448 visibility: Option<ty::Visibility<DefId>>,
1450 cx: &'a Context<'tcx>,
1451 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1452 use std::fmt::Write as _;
1454 let to_print: Cow<'static, str> = match visibility {
1456 Some(ty::Visibility::Public) => "pub ".into(),
1457 Some(ty::Visibility::Restricted(vis_did)) => {
1458 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1459 // However, rustdoc currently never displays a module's
1460 // visibility, so it shouldn't matter.
1461 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1463 if vis_did.is_crate_root() {
1464 "pub(crate) ".into()
1465 } else if parent_module == Some(vis_did) {
1466 // `pub(in foo)` where `foo` is the parent module
1467 // is the same as no visibility modifier
1469 } else if parent_module.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1472 "pub(super) ".into()
1474 let path = cx.tcx().def_path(vis_did);
1475 debug!("path={:?}", path);
1476 // modified from `resolved_path()` to work with `DefPathData`
1477 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1478 let anchor = anchor(vis_did, last_name, cx);
1480 let mut s = "pub(in ".to_owned();
1481 for seg in &path.data[..path.data.len() - 1] {
1482 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1484 let _ = write!(s, "{}) ", anchor);
1489 display_fn(move |f| write!(f, "{}", to_print))
1492 /// This function is the same as print_with_space, except that it renders no links.
1493 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1495 pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
1496 visibility: Option<ty::Visibility<DefId>>,
1499 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1500 let to_print: Cow<'static, str> = match visibility {
1502 Some(ty::Visibility::Public) => "pub ".into(),
1503 Some(ty::Visibility::Restricted(vis_did)) => {
1504 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1505 // However, rustdoc currently never displays a module's
1506 // visibility, so it shouldn't matter.
1507 let parent_module = find_nearest_parent_module(tcx, item_did);
1509 if vis_did.is_crate_root() {
1510 "pub(crate) ".into()
1511 } else if parent_module == Some(vis_did) {
1512 // `pub(in foo)` where `foo` is the parent module
1513 // is the same as no visibility modifier
1515 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1518 "pub(super) ".into()
1520 format!("pub(in {}) ", tcx.def_path_str(vis_did)).into()
1524 display_fn(move |f| f.write_str(&to_print))
1527 pub(crate) trait PrintWithSpace {
1528 fn print_with_space(&self) -> &str;
1531 impl PrintWithSpace for hir::Unsafety {
1532 fn print_with_space(&self) -> &str {
1534 hir::Unsafety::Unsafe => "unsafe ",
1535 hir::Unsafety::Normal => "",
1540 impl PrintWithSpace for hir::IsAsync {
1541 fn print_with_space(&self) -> &str {
1543 hir::IsAsync::Async => "async ",
1544 hir::IsAsync::NotAsync => "",
1549 impl PrintWithSpace for hir::Mutability {
1550 fn print_with_space(&self) -> &str {
1552 hir::Mutability::Not => "",
1553 hir::Mutability::Mut => "mut ",
1558 pub(crate) fn print_constness_with_space(
1560 s: Option<ConstStability>,
1563 // const stable or when feature(staged_api) is not set
1565 hir::Constness::Const,
1566 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1568 | (hir::Constness::Const, None) => "const ",
1569 // const unstable or not const
1574 impl clean::Import {
1575 pub(crate) fn print<'a, 'tcx: 'a>(
1577 cx: &'a Context<'tcx>,
1578 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1579 display_fn(move |f| match self.kind {
1580 clean::ImportKind::Simple(name) => {
1581 if name == self.source.path.last() {
1582 write!(f, "use {};", self.source.print(cx))
1584 write!(f, "use {} as {};", self.source.print(cx), name)
1587 clean::ImportKind::Glob => {
1588 if self.source.path.segments.is_empty() {
1591 write!(f, "use {}::*;", self.source.print(cx))
1598 impl clean::ImportSource {
1599 pub(crate) fn print<'a, 'tcx: 'a>(
1601 cx: &'a Context<'tcx>,
1602 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1603 display_fn(move |f| match self.did {
1604 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1606 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1607 write!(f, "{}::", seg.name)?;
1609 let name = self.path.last();
1610 if let hir::def::Res::PrimTy(p) = self.path.res {
1611 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1613 write!(f, "{}", name)?;
1621 impl clean::TypeBinding {
1622 pub(crate) fn print<'a, 'tcx: 'a>(
1624 cx: &'a Context<'tcx>,
1625 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1626 display_fn(move |f| {
1627 f.write_str(self.assoc.name.as_str())?;
1629 write!(f, "{:#}", self.assoc.args.print(cx))?;
1631 write!(f, "{}", self.assoc.args.print(cx))?;
1634 clean::TypeBindingKind::Equality { ref term } => {
1636 write!(f, " = {:#}", term.print(cx))?;
1638 write!(f, " = {}", term.print(cx))?;
1641 clean::TypeBindingKind::Constraint { ref bounds } => {
1642 if !bounds.is_empty() {
1644 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1646 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1656 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1657 display_fn(move |f| {
1658 let quot = if f.alternate() { "\"" } else { """ };
1660 Abi::Rust => Ok(()),
1661 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1666 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1667 if v { "default " } else { "" }
1670 impl clean::GenericArg {
1671 pub(crate) fn print<'a, 'tcx: 'a>(
1673 cx: &'a Context<'tcx>,
1674 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1675 display_fn(move |f| match self {
1676 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1677 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1678 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1679 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1684 impl clean::types::Term {
1685 pub(crate) fn print<'a, 'tcx: 'a>(
1687 cx: &'a Context<'tcx>,
1688 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1689 display_fn(move |f| match self {
1690 clean::types::Term::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1691 clean::types::Term::Constant(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1696 pub(crate) fn display_fn(
1697 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1698 ) -> impl fmt::Display {
1699 struct WithFormatter<F>(Cell<Option<F>>);
1701 impl<F> fmt::Display for WithFormatter<F>
1703 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1706 (self.0.take()).unwrap()(f)
1710 WithFormatter(Cell::new(Some(f)))