rustdoc/html/
format.rs

1//! HTML formatting module
2//!
3//! This module contains a large number of `Display` implementations for
4//! various types in `rustdoc::clean`.
5//!
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.
9
10use std::cmp::Ordering;
11use std::fmt::{self, Display, Write};
12use std::iter::{self, once};
13use std::slice;
14
15use itertools::{Either, Itertools};
16use rustc_abi::ExternAbi;
17use rustc_ast::join_path_syms;
18use rustc_data_structures::fx::FxHashSet;
19use rustc_hir as hir;
20use rustc_hir::def::{DefKind, MacroKinds};
21use rustc_hir::def_id::{DefId, LOCAL_CRATE};
22use rustc_hir::{ConstStability, StabilityLevel, StableSince};
23use rustc_metadata::creader::CStore;
24use rustc_middle::ty::{self, TyCtxt, TypingMode};
25use rustc_span::symbol::kw;
26use rustc_span::{Symbol, sym};
27use tracing::{debug, trace};
28
29use super::url_parts_builder::UrlPartsBuilder;
30use crate::clean::types::ExternalLocation;
31use crate::clean::utils::find_nearest_parent_module;
32use crate::clean::{self, ExternalCrate, PrimitiveType};
33use crate::display::{Joined as _, MaybeDisplay as _, WithOpts, Wrapped};
34use crate::formats::cache::Cache;
35use crate::formats::item_type::ItemType;
36use crate::html::escape::{Escape, EscapeBodyText};
37use crate::html::render::Context;
38use crate::passes::collect_intra_doc_links::UrlFragment;
39
40pub(crate) fn print_generic_bounds(
41    bounds: &[clean::GenericBound],
42    cx: &Context<'_>,
43) -> impl Display {
44    fmt::from_fn(move |f| {
45        let mut bounds_dup = FxHashSet::default();
46
47        bounds
48            .iter()
49            .filter(move |b| bounds_dup.insert(*b))
50            .map(|bound| print_generic_bound(bound, cx))
51            .joined(" + ", f)
52    })
53}
54
55pub(crate) fn print_generic_param_def(
56    generic_param: &clean::GenericParamDef,
57    cx: &Context<'_>,
58) -> impl Display {
59    fmt::from_fn(move |f| match &generic_param.kind {
60        clean::GenericParamDefKind::Lifetime { outlives } => {
61            write!(f, "{}", generic_param.name)?;
62
63            if !outlives.is_empty() {
64                f.write_str(": ")?;
65                outlives.iter().map(|lt| print_lifetime(lt)).joined(" + ", f)?;
66            }
67
68            Ok(())
69        }
70        clean::GenericParamDefKind::Type { bounds, default, .. } => {
71            f.write_str(generic_param.name.as_str())?;
72
73            if !bounds.is_empty() {
74                f.write_str(": ")?;
75                print_generic_bounds(bounds, cx).fmt(f)?;
76            }
77
78            if let Some(ty) = default {
79                f.write_str(" = ")?;
80                print_type(ty, cx).fmt(f)?;
81            }
82
83            Ok(())
84        }
85        clean::GenericParamDefKind::Const { ty, default, .. } => {
86            write!(f, "const {}: ", generic_param.name)?;
87            print_type(ty, cx).fmt(f)?;
88
89            if let Some(default) = default {
90                f.write_str(" = ")?;
91                if f.alternate() {
92                    write!(f, "{default}")?;
93                } else {
94                    write!(f, "{}", Escape(default))?;
95                }
96            }
97
98            Ok(())
99        }
100    })
101}
102
103pub(crate) fn print_generics(generics: &clean::Generics, cx: &Context<'_>) -> impl Display {
104    let mut real_params = generics.params.iter().filter(|p| !p.is_synthetic_param()).peekable();
105    if real_params.peek().is_none() {
106        None
107    } else {
108        Some(Wrapped::with_angle_brackets().wrap_fn(move |f| {
109            real_params.clone().map(|g| print_generic_param_def(g, cx)).joined(", ", f)
110        }))
111    }
112    .maybe_display()
113}
114
115#[derive(Clone, Copy, PartialEq, Eq)]
116pub(crate) enum Ending {
117    Newline,
118    NoNewline,
119}
120
121fn print_where_predicate(predicate: &clean::WherePredicate, cx: &Context<'_>) -> impl Display {
122    fmt::from_fn(move |f| {
123        match predicate {
124            clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
125                print_higher_ranked_params_with_space(bound_params, cx, "for").fmt(f)?;
126                print_type(ty, cx).fmt(f)?;
127                f.write_str(":")?;
128                if !bounds.is_empty() {
129                    f.write_str(" ")?;
130                    print_generic_bounds(bounds, cx).fmt(f)?;
131                }
132                Ok(())
133            }
134            clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
135                // We don't need to check `alternate` since we can be certain that neither
136                // the lifetime nor the bounds contain any characters which need escaping.
137                write!(f, "{}:", print_lifetime(lifetime))?;
138                if !bounds.is_empty() {
139                    write!(f, " {}", print_generic_bounds(bounds, cx))?;
140                }
141                Ok(())
142            }
143            clean::WherePredicate::EqPredicate { lhs, rhs } => {
144                let opts = WithOpts::from(f);
145                write!(
146                    f,
147                    "{} == {}",
148                    opts.display(print_qpath_data(lhs, cx)),
149                    opts.display(print_term(rhs, cx)),
150                )
151            }
152        }
153    })
154}
155
156/// * The Generics from which to emit a where-clause.
157/// * The number of spaces to indent each line with.
158/// * Whether the where-clause needs to add a comma and newline after the last bound.
159pub(crate) fn print_where_clause(
160    gens: &clean::Generics,
161    cx: &Context<'_>,
162    indent: usize,
163    ending: Ending,
164) -> Option<impl Display> {
165    if gens.where_predicates.is_empty() {
166        return None;
167    }
168
169    Some(fmt::from_fn(move |f| {
170        let where_preds = fmt::from_fn(|f| {
171            gens.where_predicates
172                .iter()
173                .map(|predicate| {
174                    fmt::from_fn(|f| {
175                        if f.alternate() {
176                            f.write_str(" ")?;
177                        } else {
178                            f.write_str("\n")?;
179                        }
180                        print_where_predicate(predicate, cx).fmt(f)
181                    })
182                })
183                .joined(",", f)
184        });
185
186        let clause = if f.alternate() {
187            if ending == Ending::Newline {
188                format!(" where{where_preds},")
189            } else {
190                format!(" where{where_preds}")
191            }
192        } else {
193            let mut br_with_padding = String::with_capacity(6 * indent + 28);
194            br_with_padding.push('\n');
195
196            let where_indent = 3;
197            let padding_amount = if ending == Ending::Newline {
198                indent + 4
199            } else if indent == 0 {
200                4
201            } else {
202                indent + where_indent + "where ".len()
203            };
204
205            for _ in 0..padding_amount {
206                br_with_padding.push(' ');
207            }
208            let where_preds = where_preds.to_string().replace('\n', &br_with_padding);
209
210            if ending == Ending::Newline {
211                let mut clause = " ".repeat(indent.saturating_sub(1));
212                write!(clause, "<div class=\"where\">where{where_preds},</div>")?;
213                clause
214            } else {
215                // insert a newline after a single space but before multiple spaces at the start
216                if indent == 0 {
217                    format!("\n<span class=\"where\">where{where_preds}</span>")
218                } else {
219                    // put the first one on the same line as the 'where' keyword
220                    let where_preds = where_preds.replacen(&br_with_padding, " ", 1);
221
222                    let mut clause = br_with_padding;
223                    // +1 is for `\n`.
224                    clause.truncate(indent + 1 + where_indent);
225
226                    write!(clause, "<span class=\"where\">where{where_preds}</span>")?;
227                    clause
228                }
229            }
230        };
231        write!(f, "{clause}")
232    }))
233}
234
235#[inline]
236pub(crate) fn print_lifetime(lt: &clean::Lifetime) -> &str {
237    lt.0.as_str()
238}
239
240pub(crate) fn print_constant_kind(
241    constant_kind: &clean::ConstantKind,
242    tcx: TyCtxt<'_>,
243) -> impl Display {
244    let expr = constant_kind.expr(tcx);
245    fmt::from_fn(
246        move |f| {
247            if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
248        },
249    )
250}
251
252fn print_poly_trait(poly_trait: &clean::PolyTrait, cx: &Context<'_>) -> impl Display {
253    fmt::from_fn(move |f| {
254        print_higher_ranked_params_with_space(&poly_trait.generic_params, cx, "for").fmt(f)?;
255        print_path(&poly_trait.trait_, cx).fmt(f)
256    })
257}
258
259pub(crate) fn print_generic_bound(
260    generic_bound: &clean::GenericBound,
261    cx: &Context<'_>,
262) -> impl Display {
263    fmt::from_fn(move |f| match generic_bound {
264        clean::GenericBound::Outlives(lt) => f.write_str(print_lifetime(lt)),
265        clean::GenericBound::TraitBound(ty, modifiers) => {
266            // `const` and `[const]` trait bounds are experimental; don't render them.
267            let hir::TraitBoundModifiers { polarity, constness: _ } = modifiers;
268            f.write_str(match polarity {
269                hir::BoundPolarity::Positive => "",
270                hir::BoundPolarity::Maybe(_) => "?",
271                hir::BoundPolarity::Negative(_) => "!",
272            })?;
273            print_poly_trait(ty, cx).fmt(f)
274        }
275        clean::GenericBound::Use(args) => {
276            f.write_str("use")?;
277            Wrapped::with_angle_brackets()
278                .wrap_fn(|f| args.iter().map(|arg| arg.name()).joined(", ", f))
279                .fmt(f)
280        }
281    })
282}
283
284fn print_generic_args(generic_args: &clean::GenericArgs, cx: &Context<'_>) -> impl Display {
285    fmt::from_fn(move |f| {
286        match generic_args {
287            clean::GenericArgs::AngleBracketed { args, constraints } => {
288                if !args.is_empty() || !constraints.is_empty() {
289                    Wrapped::with_angle_brackets()
290                        .wrap_fn(|f| {
291                            [Either::Left(args), Either::Right(constraints)]
292                                .into_iter()
293                                .flat_map(Either::factor_into_iter)
294                                .map(|either| {
295                                    either.map_either(
296                                        |arg| print_generic_arg(arg, cx),
297                                        |constraint| print_assoc_item_constraint(constraint, cx),
298                                    )
299                                })
300                                .joined(", ", f)
301                        })
302                        .fmt(f)?;
303                }
304            }
305            clean::GenericArgs::Parenthesized { inputs, output } => {
306                Wrapped::with_parens()
307                    .wrap_fn(|f| inputs.iter().map(|ty| print_type(ty, cx)).joined(", ", f))
308                    .fmt(f)?;
309                if let Some(ref ty) = *output {
310                    f.write_str(if f.alternate() { " -> " } else { " -&gt; " })?;
311                    print_type(ty, cx).fmt(f)?;
312                }
313            }
314            clean::GenericArgs::ReturnTypeNotation => {
315                f.write_str("(..)")?;
316            }
317        }
318        Ok(())
319    })
320}
321
322// Possible errors when computing href link source for a `DefId`
323#[derive(PartialEq, Eq)]
324pub(crate) enum HrefError {
325    /// This item is known to rustdoc, but from a crate that does not have documentation generated.
326    ///
327    /// This can only happen for non-local items.
328    ///
329    /// # Example
330    ///
331    /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
332    /// implements it for a local type.
333    /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
334    ///
335    /// ```sh
336    /// rustc a.rs --crate-type=lib
337    /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
338    /// ```
339    ///
340    /// Now, the associated items in the trait impl want to link to the corresponding item in the
341    /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
342    /// *documentation (was) not built*.
343    DocumentationNotBuilt,
344    /// This can only happen for non-local items when `--document-private-items` is not passed.
345    Private,
346    // Not in external cache, href link should be in same page
347    NotInExternalCache,
348    /// Refers to an unnamable item, such as one defined within a function or const block.
349    UnnamableItem,
350}
351
352/// Type representing information of an `href` attribute.
353pub(crate) struct HrefInfo {
354    /// URL to the item page.
355    pub(crate) url: String,
356    /// Kind of the item (used to generate the `title` attribute).
357    pub(crate) kind: ItemType,
358    /// Rust path to the item (used to generate the `title` attribute).
359    pub(crate) rust_path: Vec<Symbol>,
360}
361
362/// This function is to get the external macro path because they are not in the cache used in
363/// `href_with_root_path`.
364fn generate_macro_def_id_path(
365    def_id: DefId,
366    cx: &Context<'_>,
367    root_path: Option<&str>,
368) -> Result<HrefInfo, HrefError> {
369    let tcx = cx.tcx();
370    let crate_name = tcx.crate_name(def_id.krate);
371    let cache = cx.cache();
372
373    let cstore = CStore::from_tcx(tcx);
374    // We need this to prevent a `panic` when this function is used from intra doc links...
375    if !cstore.has_crate_data(def_id.krate) {
376        debug!("No data for crate {crate_name}");
377        return Err(HrefError::NotInExternalCache);
378    }
379    let DefKind::Macro(kinds) = tcx.def_kind(def_id) else {
380        unreachable!();
381    };
382    let item_type = if kinds == MacroKinds::DERIVE {
383        ItemType::ProcDerive
384    } else if kinds == MacroKinds::ATTR {
385        ItemType::ProcAttribute
386    } else {
387        ItemType::Macro
388    };
389    let mut path = clean::inline::get_item_path(tcx, def_id, item_type);
390    if path.len() < 2 {
391        // The minimum we can have is the crate name followed by the macro name. If shorter, then
392        // it means that `relative` was empty, which is an error.
393        debug!("macro path cannot be empty!");
394        return Err(HrefError::NotInExternalCache);
395    }
396
397    // FIXME: Try to use `iter().chain().once()` instead.
398    let mut prev = None;
399    if let Some(last) = path.pop() {
400        path.push(Symbol::intern(&format!("{}.{last}.html", item_type.as_str())));
401        prev = Some(last);
402    }
403
404    let url = match cache.extern_locations[&def_id.krate] {
405        ExternalLocation::Remote(ref s) => {
406            // `ExternalLocation::Remote` always end with a `/`.
407            format!("{s}{path}", path = fmt::from_fn(|f| path.iter().joined("/", f)))
408        }
409        ExternalLocation::Local => {
410            // `root_path` always end with a `/`.
411            format!(
412                "{root_path}{path}",
413                root_path = root_path.unwrap_or(""),
414                path = fmt::from_fn(|f| path.iter().joined("/", f))
415            )
416        }
417        ExternalLocation::Unknown => {
418            debug!("crate {crate_name} not in cache when linkifying macros");
419            return Err(HrefError::NotInExternalCache);
420        }
421    };
422    if let Some(prev) = prev {
423        path.pop();
424        path.push(prev);
425    }
426    Ok(HrefInfo { url, kind: item_type, rust_path: path })
427}
428
429fn generate_item_def_id_path(
430    mut def_id: DefId,
431    original_def_id: DefId,
432    cx: &Context<'_>,
433    root_path: Option<&str>,
434) -> Result<HrefInfo, HrefError> {
435    use rustc_middle::traits::ObligationCause;
436    use rustc_trait_selection::infer::TyCtxtInferExt;
437    use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
438
439    let tcx = cx.tcx();
440    let crate_name = tcx.crate_name(def_id.krate);
441
442    // No need to try to infer the actual parent item if it's not an associated item from the `impl`
443    // block.
444    if def_id != original_def_id && matches!(tcx.def_kind(def_id), DefKind::Impl { .. }) {
445        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
446        def_id = infcx
447            .at(&ObligationCause::dummy(), tcx.param_env(def_id))
448            .query_normalize(ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()))
449            .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
450            .ok()
451            .and_then(|normalized| normalized.skip_binder().ty_adt_def())
452            .map(|adt| adt.did())
453            .unwrap_or(def_id);
454    }
455
456    let relative = clean::inline::item_relative_path(tcx, def_id);
457    let fqp: Vec<Symbol> = once(crate_name).chain(relative).collect();
458
459    let shortty = ItemType::from_def_id(def_id, tcx);
460    let module_fqp = to_module_fqp(shortty, &fqp);
461    let mut is_remote = false;
462
463    let url_parts = url_parts(cx.cache(), def_id, module_fqp, &cx.current, &mut is_remote)?;
464    let mut url_parts = make_href(root_path, shortty, url_parts, &fqp, is_remote);
465    if def_id != original_def_id {
466        let kind = ItemType::from_def_id(original_def_id, tcx);
467        url_parts = format!("{url_parts}#{kind}.{}", tcx.item_name(original_def_id))
468    };
469    Ok(HrefInfo { url: url_parts, kind: shortty, rust_path: fqp })
470}
471
472/// Checks if the given defid refers to an item that is unnamable, such as one defined in a const block.
473fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool {
474    let mut cur_did = did;
475    while let Some(parent) = tcx.opt_parent(cur_did) {
476        match tcx.def_kind(parent) {
477            // items defined in these can be linked to, as long as they are visible
478            DefKind::Mod | DefKind::ForeignMod => cur_did = parent,
479            // items in impls can be linked to,
480            // as long as we can link to the item the impl is on.
481            // since associated traits are not a thing,
482            // it should not be possible to refer to an impl item if
483            // the base type is not namable.
484            DefKind::Impl { .. } => return false,
485            // everything else does not have docs generated for it
486            _ => return true,
487        }
488    }
489    return false;
490}
491
492fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
493    if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
494}
495
496fn url_parts(
497    cache: &Cache,
498    def_id: DefId,
499    module_fqp: &[Symbol],
500    relative_to: &[Symbol],
501    is_remote: &mut bool,
502) -> Result<UrlPartsBuilder, HrefError> {
503    match cache.extern_locations[&def_id.krate] {
504        ExternalLocation::Remote(ref s) => {
505            *is_remote = true;
506            let s = s.trim_end_matches('/');
507            let mut builder = UrlPartsBuilder::singleton(s);
508            builder.extend(module_fqp.iter().copied());
509            Ok(builder)
510        }
511        ExternalLocation::Local => Ok(href_relative_parts(module_fqp, relative_to)),
512        ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt),
513    }
514}
515
516fn make_href(
517    root_path: Option<&str>,
518    shortty: ItemType,
519    mut url_parts: UrlPartsBuilder,
520    fqp: &[Symbol],
521    is_remote: bool,
522) -> String {
523    if !is_remote && let Some(root_path) = root_path {
524        let root = root_path.trim_end_matches('/');
525        url_parts.push_front(root);
526    }
527    debug!(?url_parts);
528    match shortty {
529        ItemType::Module => {
530            url_parts.push("index.html");
531        }
532        _ => {
533            let last = fqp.last().unwrap();
534            url_parts.push_fmt(format_args!("{shortty}.{last}.html"));
535        }
536    }
537    url_parts.finish()
538}
539
540pub(crate) fn href_with_root_path(
541    original_did: DefId,
542    cx: &Context<'_>,
543    root_path: Option<&str>,
544) -> Result<HrefInfo, HrefError> {
545    let tcx = cx.tcx();
546    let def_kind = tcx.def_kind(original_did);
547    let did = match def_kind {
548        DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
549            // documented on their parent's page
550            tcx.parent(original_did)
551        }
552        // If this a constructor, we get the parent (either a struct or a variant) and then
553        // generate the link for this item.
554        DefKind::Ctor(..) => return href_with_root_path(tcx.parent(original_did), cx, root_path),
555        DefKind::ExternCrate => {
556            // Link to the crate itself, not the `extern crate` item.
557            if let Some(local_did) = original_did.as_local() {
558                tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
559            } else {
560                original_did
561            }
562        }
563        _ => original_did,
564    };
565    if is_unnamable(cx.tcx(), did) {
566        return Err(HrefError::UnnamableItem);
567    }
568    let cache = cx.cache();
569    let relative_to = &cx.current;
570
571    if !original_did.is_local() {
572        // If we are generating an href for the "jump to def" feature, then the only case we want
573        // to ignore is if the item is `doc(hidden)` because we can't link to it.
574        if root_path.is_some() {
575            if tcx.is_doc_hidden(original_did) {
576                return Err(HrefError::Private);
577            }
578        } else if !cache.effective_visibilities.is_directly_public(tcx, did)
579            && !cache.document_private
580            && !cache.primitive_locations.values().any(|&id| id == did)
581        {
582            return Err(HrefError::Private);
583        }
584    }
585
586    let mut is_remote = false;
587    let (fqp, shortty, url_parts) = match cache.paths.get(&did) {
588        Some(&(ref fqp, shortty)) => (fqp, shortty, {
589            let module_fqp = to_module_fqp(shortty, fqp.as_slice());
590            debug!(?fqp, ?shortty, ?module_fqp);
591            href_relative_parts(module_fqp, relative_to)
592        }),
593        None => {
594            // Associated items are handled differently with "jump to def". The anchor is generated
595            // directly here whereas for intra-doc links, we have some extra computation being
596            // performed there.
597            let def_id_to_get = if root_path.is_some() { original_did } else { did };
598            if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&def_id_to_get) {
599                let module_fqp = to_module_fqp(shortty, fqp);
600                (fqp, shortty, url_parts(cache, did, module_fqp, relative_to, &mut is_remote)?)
601            } else if matches!(def_kind, DefKind::Macro(_)) {
602                return generate_macro_def_id_path(did, cx, root_path);
603            } else if did.is_local() {
604                return Err(HrefError::Private);
605            } else {
606                return generate_item_def_id_path(did, original_did, cx, root_path);
607            }
608        }
609    };
610    Ok(HrefInfo {
611        url: make_href(root_path, shortty, url_parts, fqp, is_remote),
612        kind: shortty,
613        rust_path: fqp.clone(),
614    })
615}
616
617pub(crate) fn href(did: DefId, cx: &Context<'_>) -> Result<HrefInfo, HrefError> {
618    href_with_root_path(did, cx, None)
619}
620
621/// Both paths should only be modules.
622/// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
623/// both need `../iter/trait.Iterator.html` to get at the iterator trait.
624pub(crate) fn href_relative_parts(fqp: &[Symbol], relative_to_fqp: &[Symbol]) -> UrlPartsBuilder {
625    for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
626        // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
627        if f != r {
628            let dissimilar_part_count = relative_to_fqp.len() - i;
629            let fqp_module = &fqp[i..];
630            return iter::repeat_n(sym::dotdot, dissimilar_part_count)
631                .chain(fqp_module.iter().copied())
632                .collect();
633        }
634    }
635    match relative_to_fqp.len().cmp(&fqp.len()) {
636        Ordering::Less => {
637            // e.g. linking to std::sync::atomic from std::sync
638            fqp[relative_to_fqp.len()..fqp.len()].iter().copied().collect()
639        }
640        Ordering::Greater => {
641            // e.g. linking to std::sync from std::sync::atomic
642            let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
643            iter::repeat_n(sym::dotdot, dissimilar_part_count).collect()
644        }
645        Ordering::Equal => {
646            // linking to the same module
647            UrlPartsBuilder::new()
648        }
649    }
650}
651
652pub(crate) fn link_tooltip(
653    did: DefId,
654    fragment: &Option<UrlFragment>,
655    cx: &Context<'_>,
656) -> impl fmt::Display {
657    fmt::from_fn(move |f| {
658        let cache = cx.cache();
659        let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did))
660        else {
661            return Ok(());
662        };
663        let fqp = if *shortty == ItemType::Primitive {
664            // primitives are documented in a crate, but not actually part of it
665            slice::from_ref(fqp.last().unwrap())
666        } else {
667            fqp
668        };
669        if let &Some(UrlFragment::Item(id)) = fragment {
670            write!(f, "{} ", cx.tcx().def_descr(id))?;
671            for component in fqp {
672                write!(f, "{component}::")?;
673            }
674            write!(f, "{}", cx.tcx().item_name(id))?;
675        } else if !fqp.is_empty() {
676            write!(f, "{shortty} ")?;
677            write!(f, "{}", join_path_syms(fqp))?;
678        }
679        Ok(())
680    })
681}
682
683/// Used to render a [`clean::Path`].
684fn resolved_path(
685    w: &mut fmt::Formatter<'_>,
686    did: DefId,
687    path: &clean::Path,
688    print_all: bool,
689    use_absolute: bool,
690    cx: &Context<'_>,
691) -> fmt::Result {
692    let last = path.segments.last().unwrap();
693
694    if print_all {
695        for seg in &path.segments[..path.segments.len() - 1] {
696            write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
697        }
698    }
699    if w.alternate() {
700        write!(w, "{}{:#}", last.name, print_generic_args(&last.args, cx))?;
701    } else {
702        let path = fmt::from_fn(|f| {
703            if use_absolute {
704                if let Ok(HrefInfo { rust_path, .. }) = href(did, cx) {
705                    write!(
706                        f,
707                        "{path}::{anchor}",
708                        path = join_path_syms(&rust_path[..rust_path.len() - 1]),
709                        anchor = print_anchor(did, *rust_path.last().unwrap(), cx)
710                    )
711                } else {
712                    write!(f, "{}", last.name)
713                }
714            } else {
715                write!(f, "{}", print_anchor(did, last.name, cx))
716            }
717        });
718        write!(w, "{path}{args}", args = print_generic_args(&last.args, cx))?;
719    }
720    Ok(())
721}
722
723fn primitive_link(
724    f: &mut fmt::Formatter<'_>,
725    prim: clean::PrimitiveType,
726    name: fmt::Arguments<'_>,
727    cx: &Context<'_>,
728) -> fmt::Result {
729    primitive_link_fragment(f, prim, name, "", cx)
730}
731
732fn primitive_link_fragment(
733    f: &mut fmt::Formatter<'_>,
734    prim: clean::PrimitiveType,
735    name: fmt::Arguments<'_>,
736    fragment: &str,
737    cx: &Context<'_>,
738) -> fmt::Result {
739    let m = &cx.cache();
740    let mut needs_termination = false;
741    if !f.alternate() {
742        match m.primitive_locations.get(&prim) {
743            Some(&def_id) if def_id.is_local() => {
744                let len = cx.current.len();
745                let path = fmt::from_fn(|f| {
746                    if len == 0 {
747                        let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
748                        write!(f, "{cname_sym}/")?;
749                    } else {
750                        for _ in 0..(len - 1) {
751                            f.write_str("../")?;
752                        }
753                    }
754                    Ok(())
755                });
756                write!(
757                    f,
758                    "<a class=\"primitive\" href=\"{path}primitive.{}.html{fragment}\">",
759                    prim.as_sym()
760                )?;
761                needs_termination = true;
762            }
763            Some(&def_id) => {
764                let loc = match m.extern_locations[&def_id.krate] {
765                    ExternalLocation::Remote(ref s) => {
766                        let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
767                        let builder: UrlPartsBuilder =
768                            [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
769                                .into_iter()
770                                .collect();
771                        Some(builder)
772                    }
773                    ExternalLocation::Local => {
774                        let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
775                        Some(if cx.current.first() == Some(&cname_sym) {
776                            iter::repeat_n(sym::dotdot, cx.current.len() - 1).collect()
777                        } else {
778                            iter::repeat_n(sym::dotdot, cx.current.len())
779                                .chain(iter::once(cname_sym))
780                                .collect()
781                        })
782                    }
783                    ExternalLocation::Unknown => None,
784                };
785                if let Some(mut loc) = loc {
786                    loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
787                    write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
788                    needs_termination = true;
789                }
790            }
791            None => {}
792        }
793    }
794    Display::fmt(&name, f)?;
795    if needs_termination {
796        write!(f, "</a>")?;
797    }
798    Ok(())
799}
800
801fn print_tybounds(
802    bounds: &[clean::PolyTrait],
803    lt: &Option<clean::Lifetime>,
804    cx: &Context<'_>,
805) -> impl Display {
806    fmt::from_fn(move |f| {
807        bounds.iter().map(|bound| print_poly_trait(bound, cx)).joined(" + ", f)?;
808        if let Some(lt) = lt {
809            // We don't need to check `alternate` since we can be certain that
810            // the lifetime doesn't contain any characters which need escaping.
811            write!(f, " + {}", print_lifetime(lt))?;
812        }
813        Ok(())
814    })
815}
816
817fn print_higher_ranked_params_with_space(
818    params: &[clean::GenericParamDef],
819    cx: &Context<'_>,
820    keyword: &'static str,
821) -> impl Display {
822    fmt::from_fn(move |f| {
823        if !params.is_empty() {
824            f.write_str(keyword)?;
825            Wrapped::with_angle_brackets()
826                .wrap_fn(|f| {
827                    params.iter().map(|lt| print_generic_param_def(lt, cx)).joined(", ", f)
828                })
829                .fmt(f)?;
830            f.write_char(' ')?;
831        }
832        Ok(())
833    })
834}
835
836pub(crate) fn fragment(did: DefId, tcx: TyCtxt<'_>) -> impl Display {
837    fmt::from_fn(move |f| {
838        let def_kind = tcx.def_kind(did);
839        match def_kind {
840            DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
841                let item_type = ItemType::from_def_id(did, tcx);
842                write!(f, "#{}.{}", item_type.as_str(), tcx.item_name(did))
843            }
844            DefKind::Field => {
845                let parent_def_id = tcx.parent(did);
846                f.write_char('#')?;
847                if tcx.def_kind(parent_def_id) == DefKind::Variant {
848                    write!(f, "variant.{}.field", tcx.item_name(parent_def_id).as_str())?;
849                } else {
850                    f.write_str("structfield")?;
851                };
852                write!(f, ".{}", tcx.item_name(did))
853            }
854            _ => Ok(()),
855        }
856    })
857}
858
859pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
860    fmt::from_fn(move |f| {
861        if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) {
862            write!(
863                f,
864                r#"<a class="{kind}" href="{url}{anchor}" title="{kind} {path}">{text}</a>"#,
865                anchor = fragment(did, cx.tcx()),
866                path = join_path_syms(rust_path),
867                text = EscapeBodyText(text.as_str()),
868            )
869        } else {
870            f.write_str(text.as_str())
871        }
872    })
873}
874
875fn fmt_type(
876    t: &clean::Type,
877    f: &mut fmt::Formatter<'_>,
878    use_absolute: bool,
879    cx: &Context<'_>,
880) -> fmt::Result {
881    trace!("fmt_type(t = {t:?})");
882
883    match t {
884        clean::Generic(name) => f.write_str(name.as_str()),
885        clean::SelfTy => f.write_str("Self"),
886        clean::Type::Path { path } => {
887            // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
888            let did = path.def_id();
889            resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
890        }
891        clean::DynTrait(bounds, lt) => {
892            f.write_str("dyn ")?;
893            print_tybounds(bounds, lt, cx).fmt(f)
894        }
895        clean::Infer => write!(f, "_"),
896        clean::Primitive(clean::PrimitiveType::Never) => {
897            primitive_link(f, PrimitiveType::Never, format_args!("!"), cx)
898        }
899        &clean::Primitive(prim) => primitive_link(f, prim, format_args!("{}", prim.as_sym()), cx),
900        clean::BareFunction(decl) => {
901            print_higher_ranked_params_with_space(&decl.generic_params, cx, "for").fmt(f)?;
902            decl.safety.print_with_space().fmt(f)?;
903            print_abi_with_space(decl.abi).fmt(f)?;
904            if f.alternate() {
905                f.write_str("fn")?;
906            } else {
907                primitive_link(f, PrimitiveType::Fn, format_args!("fn"), cx)?;
908            }
909            print_fn_decl(&decl.decl, cx).fmt(f)
910        }
911        clean::UnsafeBinder(binder) => {
912            print_higher_ranked_params_with_space(&binder.generic_params, cx, "unsafe").fmt(f)?;
913            print_type(&binder.ty, cx).fmt(f)
914        }
915        clean::Tuple(typs) => match &typs[..] {
916            &[] => primitive_link(f, PrimitiveType::Unit, format_args!("()"), cx),
917            [one] => {
918                if let clean::Generic(name) = one {
919                    primitive_link(f, PrimitiveType::Tuple, format_args!("({name},)"), cx)
920                } else {
921                    write!(f, "(")?;
922                    print_type(one, cx).fmt(f)?;
923                    write!(f, ",)")
924                }
925            }
926            many => {
927                let generic_names: Vec<Symbol> = many
928                    .iter()
929                    .filter_map(|t| match t {
930                        clean::Generic(name) => Some(*name),
931                        _ => None,
932                    })
933                    .collect();
934                let is_generic = generic_names.len() == many.len();
935                if is_generic {
936                    primitive_link(
937                        f,
938                        PrimitiveType::Tuple,
939                        format_args!(
940                            "{}",
941                            Wrapped::with_parens()
942                                .wrap_fn(|f| generic_names.iter().joined(", ", f))
943                        ),
944                        cx,
945                    )
946                } else {
947                    Wrapped::with_parens()
948                        .wrap_fn(|f| many.iter().map(|item| print_type(item, cx)).joined(", ", f))
949                        .fmt(f)
950                }
951            }
952        },
953        clean::Slice(box clean::Generic(name)) => {
954            primitive_link(f, PrimitiveType::Slice, format_args!("[{name}]"), cx)
955        }
956        clean::Slice(t) => Wrapped::with_square_brackets().wrap(print_type(t, cx)).fmt(f),
957        clean::Type::Pat(t, pat) => {
958            fmt::Display::fmt(&print_type(t, cx), f)?;
959            write!(f, " is {pat}")
960        }
961        clean::Array(box clean::Generic(name), n) if !f.alternate() => primitive_link(
962            f,
963            PrimitiveType::Array,
964            format_args!("[{name}; {n}]", n = Escape(n)),
965            cx,
966        ),
967        clean::Array(t, n) => Wrapped::with_square_brackets()
968            .wrap(fmt::from_fn(|f| {
969                print_type(t, cx).fmt(f)?;
970                f.write_str("; ")?;
971                if f.alternate() {
972                    f.write_str(n)
973                } else {
974                    primitive_link(f, PrimitiveType::Array, format_args!("{n}", n = Escape(n)), cx)
975                }
976            }))
977            .fmt(f),
978        clean::RawPointer(m, t) => {
979            let m = m.ptr_str();
980
981            if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
982                primitive_link(
983                    f,
984                    clean::PrimitiveType::RawPointer,
985                    format_args!("*{m} {ty}", ty = WithOpts::from(f).display(print_type(t, cx))),
986                    cx,
987                )
988            } else {
989                primitive_link(f, clean::PrimitiveType::RawPointer, format_args!("*{m} "), cx)?;
990                print_type(t, cx).fmt(f)
991            }
992        }
993        clean::BorrowedRef { lifetime: l, mutability, type_: ty } => {
994            let lt = fmt::from_fn(|f| match l {
995                Some(l) => write!(f, "{} ", print_lifetime(l)),
996                _ => Ok(()),
997            });
998            let m = mutability.print_with_space();
999            let amp = if f.alternate() { "&" } else { "&amp;" };
1000
1001            if let clean::Generic(name) = **ty {
1002                return primitive_link(
1003                    f,
1004                    PrimitiveType::Reference,
1005                    format_args!("{amp}{lt}{m}{name}"),
1006                    cx,
1007                );
1008            }
1009
1010            write!(f, "{amp}{lt}{m}")?;
1011
1012            let needs_parens = match **ty {
1013                clean::DynTrait(ref bounds, ref trait_lt)
1014                    if bounds.len() > 1 || trait_lt.is_some() =>
1015                {
1016                    true
1017                }
1018                clean::ImplTrait(ref bounds) if bounds.len() > 1 => true,
1019                _ => false,
1020            };
1021            Wrapped::with_parens()
1022                .when(needs_parens)
1023                .wrap_fn(|f| fmt_type(ty, f, use_absolute, cx))
1024                .fmt(f)
1025        }
1026        clean::ImplTrait(bounds) => {
1027            f.write_str("impl ")?;
1028            print_generic_bounds(bounds, cx).fmt(f)
1029        }
1030        clean::QPath(qpath) => print_qpath_data(qpath, cx).fmt(f),
1031    }
1032}
1033
1034pub(crate) fn print_type(type_: &clean::Type, cx: &Context<'_>) -> impl Display {
1035    fmt::from_fn(move |f| fmt_type(type_, f, false, cx))
1036}
1037
1038pub(crate) fn print_path(path: &clean::Path, cx: &Context<'_>) -> impl Display {
1039    fmt::from_fn(move |f| resolved_path(f, path.def_id(), path, false, false, cx))
1040}
1041
1042fn print_qpath_data(qpath_data: &clean::QPathData, cx: &Context<'_>) -> impl Display {
1043    let clean::QPathData { ref assoc, ref self_type, should_fully_qualify, ref trait_ } =
1044        *qpath_data;
1045
1046    fmt::from_fn(move |f| {
1047        // FIXME(inherent_associated_types): Once we support non-ADT self-types (#106719),
1048        // we need to surround them with angle brackets in some cases (e.g. `<dyn …>::P`).
1049
1050        if let Some(trait_) = trait_
1051            && should_fully_qualify
1052        {
1053            let opts = WithOpts::from(f);
1054            Wrapped::with_angle_brackets()
1055                .wrap(format_args!(
1056                    "{} as {}",
1057                    opts.display(print_type(self_type, cx)),
1058                    opts.display(print_path(trait_, cx))
1059                ))
1060                .fmt(f)?
1061        } else {
1062            print_type(self_type, cx).fmt(f)?;
1063        }
1064        f.write_str("::")?;
1065        // It's pretty unsightly to look at `<A as B>::C` in output, and
1066        // we've got hyperlinking on our side, so try to avoid longer
1067        // notation as much as possible by making `C` a hyperlink to trait
1068        // `B` to disambiguate.
1069        //
1070        // FIXME: this is still a lossy conversion and there should probably
1071        //        be a better way of representing this in general? Most of
1072        //        the ugliness comes from inlining across crates where
1073        //        everything comes in as a fully resolved QPath (hard to
1074        //        look at).
1075        if !f.alternate() {
1076            // FIXME(inherent_associated_types): We always link to the very first associated
1077            // type (in respect to source order) that bears the given name (`assoc.name`) and that is
1078            // affiliated with the computed `DefId`. This is obviously incorrect when we have
1079            // multiple impl blocks. Ideally, we would thread the `DefId` of the assoc ty itself
1080            // through here and map it to the corresponding HTML ID that was generated by
1081            // `render::Context::derive_id` when the impl blocks were rendered.
1082            // There is no such mapping unfortunately.
1083            // As a hack, we could badly imitate `derive_id` here by keeping *count* when looking
1084            // for the assoc ty `DefId` in `tcx.associated_items(self_ty_did).in_definition_order()`
1085            // considering privacy, `doc(hidden)`, etc.
1086            // I don't feel like that right now :cold_sweat:.
1087
1088            let parent_href = match trait_ {
1089                Some(trait_) => href(trait_.def_id(), cx).ok(),
1090                None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()),
1091            };
1092
1093            if let Some(HrefInfo { url, rust_path, .. }) = parent_href {
1094                write!(
1095                    f,
1096                    "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1097                                title=\"type {path}::{name}\">{name}</a>",
1098                    shortty = ItemType::AssocType,
1099                    name = assoc.name,
1100                    path = join_path_syms(rust_path),
1101                )
1102            } else {
1103                write!(f, "{}", assoc.name)
1104            }
1105        } else {
1106            write!(f, "{}", assoc.name)
1107        }?;
1108
1109        print_generic_args(&assoc.args, cx).fmt(f)
1110    })
1111}
1112
1113pub(crate) fn print_impl(
1114    impl_: &clean::Impl,
1115    use_absolute: bool,
1116    cx: &Context<'_>,
1117) -> impl Display {
1118    fmt::from_fn(move |f| {
1119        f.write_str("impl")?;
1120        print_generics(&impl_.generics, cx).fmt(f)?;
1121        f.write_str(" ")?;
1122
1123        if let Some(ref ty) = impl_.trait_ {
1124            if impl_.is_negative_trait_impl() {
1125                f.write_char('!')?;
1126            }
1127            if impl_.kind.is_fake_variadic()
1128                && let Some(generics) = ty.generics()
1129                && let Ok(inner_type) = generics.exactly_one()
1130            {
1131                let last = ty.last();
1132                if f.alternate() {
1133                    write!(f, "{last}")?;
1134                } else {
1135                    write!(f, "{}", print_anchor(ty.def_id(), last, cx))?;
1136                };
1137                Wrapped::with_angle_brackets()
1138                    .wrap_fn(|f| impl_.print_type(inner_type, f, use_absolute, cx))
1139                    .fmt(f)?;
1140            } else {
1141                print_path(ty, cx).fmt(f)?;
1142            }
1143            f.write_str(" for ")?;
1144        }
1145
1146        if let Some(ty) = impl_.kind.as_blanket_ty() {
1147            fmt_type(ty, f, use_absolute, cx)?;
1148        } else {
1149            impl_.print_type(&impl_.for_, f, use_absolute, cx)?;
1150        }
1151
1152        print_where_clause(&impl_.generics, cx, 0, Ending::Newline).maybe_display().fmt(f)
1153    })
1154}
1155
1156impl clean::Impl {
1157    fn print_type(
1158        &self,
1159        type_: &clean::Type,
1160        f: &mut fmt::Formatter<'_>,
1161        use_absolute: bool,
1162        cx: &Context<'_>,
1163    ) -> Result<(), fmt::Error> {
1164        if let clean::Type::Tuple(types) = type_
1165            && let [clean::Type::Generic(name)] = &types[..]
1166            && (self.kind.is_fake_variadic() || self.kind.is_auto())
1167        {
1168            // Hardcoded anchor library/core/src/primitive_docs.rs
1169            // Link should match `# Trait implementations`
1170            primitive_link_fragment(
1171                f,
1172                PrimitiveType::Tuple,
1173                format_args!("({name}₁, {name}₂, …, {name}ₙ)"),
1174                "#trait-implementations-1",
1175                cx,
1176            )?;
1177        } else if let clean::Type::Array(ty, len) = type_
1178            && let clean::Type::Generic(name) = &**ty
1179            && &len[..] == "1"
1180            && (self.kind.is_fake_variadic() || self.kind.is_auto())
1181        {
1182            primitive_link(f, PrimitiveType::Array, format_args!("[{name}; N]"), cx)?;
1183        } else if let clean::BareFunction(bare_fn) = &type_
1184            && let [clean::Parameter { type_: clean::Type::Generic(name), .. }] =
1185                &bare_fn.decl.inputs[..]
1186            && (self.kind.is_fake_variadic() || self.kind.is_auto())
1187        {
1188            // Hardcoded anchor library/core/src/primitive_docs.rs
1189            // Link should match `# Trait implementations`
1190
1191            print_higher_ranked_params_with_space(&bare_fn.generic_params, cx, "for").fmt(f)?;
1192            bare_fn.safety.print_with_space().fmt(f)?;
1193            print_abi_with_space(bare_fn.abi).fmt(f)?;
1194            let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" };
1195            primitive_link_fragment(
1196                f,
1197                PrimitiveType::Tuple,
1198                format_args!("fn({name}₁, {name}₂, …, {name}ₙ{ellipsis})"),
1199                "#trait-implementations-1",
1200                cx,
1201            )?;
1202            // Write output.
1203            if !bare_fn.decl.output.is_unit() {
1204                write!(f, " -> ")?;
1205                fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?;
1206            }
1207        } else if let clean::Type::Path { path } = type_
1208            && let Some(generics) = path.generics()
1209            && let Ok(ty) = generics.exactly_one()
1210            && self.kind.is_fake_variadic()
1211        {
1212            print_anchor(path.def_id(), path.last(), cx).fmt(f)?;
1213            Wrapped::with_angle_brackets()
1214                .wrap_fn(|f| self.print_type(ty, f, use_absolute, cx))
1215                .fmt(f)?;
1216        } else {
1217            fmt_type(type_, f, use_absolute, cx)?;
1218        }
1219        Ok(())
1220    }
1221}
1222
1223pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> impl Display {
1224    fmt::from_fn(move |f| {
1225        params
1226            .iter()
1227            .map(|param| {
1228                fmt::from_fn(|f| {
1229                    if let Some(name) = param.name {
1230                        write!(f, "{name}: ")?;
1231                    }
1232                    print_type(&param.type_, cx).fmt(f)
1233                })
1234            })
1235            .joined(", ", f)
1236    })
1237}
1238
1239// Implements Write but only counts the bytes "written".
1240struct WriteCounter(usize);
1241
1242impl std::fmt::Write for WriteCounter {
1243    fn write_str(&mut self, s: &str) -> fmt::Result {
1244        self.0 += s.len();
1245        Ok(())
1246    }
1247}
1248
1249// Implements Display by emitting the given number of spaces.
1250#[derive(Clone, Copy)]
1251struct Indent(usize);
1252
1253impl Display for Indent {
1254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1255        for _ in 0..self.0 {
1256            f.write_char(' ')?;
1257        }
1258        Ok(())
1259    }
1260}
1261
1262fn print_parameter(parameter: &clean::Parameter, cx: &Context<'_>) -> impl fmt::Display {
1263    fmt::from_fn(move |f| {
1264        if let Some(self_ty) = parameter.to_receiver() {
1265            match self_ty {
1266                clean::SelfTy => f.write_str("self"),
1267                clean::BorrowedRef { lifetime, mutability, type_: box clean::SelfTy } => {
1268                    f.write_str(if f.alternate() { "&" } else { "&amp;" })?;
1269                    if let Some(lt) = lifetime {
1270                        write!(f, "{lt} ", lt = print_lifetime(lt))?;
1271                    }
1272                    write!(f, "{mutability}self", mutability = mutability.print_with_space())
1273                }
1274                _ => {
1275                    f.write_str("self: ")?;
1276                    print_type(self_ty, cx).fmt(f)
1277                }
1278            }
1279        } else {
1280            if parameter.is_const {
1281                write!(f, "const ")?;
1282            }
1283            if let Some(name) = parameter.name {
1284                write!(f, "{name}: ")?;
1285            }
1286            print_type(&parameter.type_, cx).fmt(f)
1287        }
1288    })
1289}
1290
1291fn print_fn_decl(fn_decl: &clean::FnDecl, cx: &Context<'_>) -> impl Display {
1292    fmt::from_fn(move |f| {
1293        let ellipsis = if fn_decl.c_variadic { ", ..." } else { "" };
1294        Wrapped::with_parens()
1295            .wrap_fn(|f| {
1296                print_params(&fn_decl.inputs, cx).fmt(f)?;
1297                f.write_str(ellipsis)
1298            })
1299            .fmt(f)?;
1300        fn_decl.print_output(cx).fmt(f)
1301    })
1302}
1303
1304/// * `header_len`: The length of the function header and name. In other words, the number of
1305///   characters in the function declaration up to but not including the parentheses.
1306///   This is expected to go into a `<pre>`/`code-header` block, so indentation and newlines
1307///   are preserved.
1308/// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1309///   necessary.
1310pub(crate) fn full_print_fn_decl(
1311    fn_decl: &clean::FnDecl,
1312    header_len: usize,
1313    indent: usize,
1314    cx: &Context<'_>,
1315) -> impl Display {
1316    fmt::from_fn(move |f| {
1317        // First, generate the text form of the declaration, with no line wrapping, and count the bytes.
1318        let mut counter = WriteCounter(0);
1319        write!(&mut counter, "{:#}", fmt::from_fn(|f| { fn_decl.inner_full_print(None, f, cx) }))?;
1320        // If the text form was over 80 characters wide, we will line-wrap our output.
1321        let line_wrapping_indent = if header_len + counter.0 > 80 { Some(indent) } else { None };
1322        // Generate the final output. This happens to accept `{:#}` formatting to get textual
1323        // output but in practice it is only formatted with `{}` to get HTML output.
1324        fn_decl.inner_full_print(line_wrapping_indent, f, cx)
1325    })
1326}
1327
1328impl clean::FnDecl {
1329    fn inner_full_print(
1330        &self,
1331        // For None, the declaration will not be line-wrapped. For Some(n),
1332        // the declaration will be line-wrapped, with an indent of n spaces.
1333        line_wrapping_indent: Option<usize>,
1334        f: &mut fmt::Formatter<'_>,
1335        cx: &Context<'_>,
1336    ) -> fmt::Result {
1337        Wrapped::with_parens()
1338            .wrap_fn(|f| {
1339                if !self.inputs.is_empty() {
1340                    let line_wrapping_indent = line_wrapping_indent.map(|n| Indent(n + 4));
1341
1342                    if let Some(indent) = line_wrapping_indent {
1343                        write!(f, "\n{indent}")?;
1344                    }
1345
1346                    let sep = fmt::from_fn(|f| {
1347                        if let Some(indent) = line_wrapping_indent {
1348                            write!(f, ",\n{indent}")
1349                        } else {
1350                            f.write_str(", ")
1351                        }
1352                    });
1353
1354                    self.inputs.iter().map(|param| print_parameter(param, cx)).joined(sep, f)?;
1355
1356                    if line_wrapping_indent.is_some() {
1357                        writeln!(f, ",")?
1358                    }
1359
1360                    if self.c_variadic {
1361                        match line_wrapping_indent {
1362                            None => write!(f, ", ...")?,
1363                            Some(indent) => writeln!(f, "{indent}...")?,
1364                        };
1365                    }
1366                }
1367
1368                if let Some(n) = line_wrapping_indent {
1369                    write!(f, "{}", Indent(n))?
1370                }
1371
1372                Ok(())
1373            })
1374            .fmt(f)?;
1375
1376        self.print_output(cx).fmt(f)
1377    }
1378
1379    fn print_output(&self, cx: &Context<'_>) -> impl Display {
1380        fmt::from_fn(move |f| {
1381            if self.output.is_unit() {
1382                return Ok(());
1383            }
1384
1385            f.write_str(if f.alternate() { " -> " } else { " -&gt; " })?;
1386            print_type(&self.output, cx).fmt(f)
1387        })
1388    }
1389}
1390
1391pub(crate) fn visibility_print_with_space(item: &clean::Item, cx: &Context<'_>) -> impl Display {
1392    fmt::from_fn(move |f| {
1393        if item.is_doc_hidden() {
1394            f.write_str("#[doc(hidden)] ")?;
1395        }
1396
1397        let Some(vis) = item.visibility(cx.tcx()) else {
1398            return Ok(());
1399        };
1400
1401        match vis {
1402            ty::Visibility::Public => f.write_str("pub ")?,
1403            ty::Visibility::Restricted(vis_did) => {
1404                // FIXME(camelid): This may not work correctly if `item_did` is a module.
1405                //                 However, rustdoc currently never displays a module's
1406                //                 visibility, so it shouldn't matter.
1407                let parent_module =
1408                    find_nearest_parent_module(cx.tcx(), item.item_id.expect_def_id());
1409
1410                if vis_did.is_crate_root() {
1411                    f.write_str("pub(crate) ")?;
1412                } else if parent_module == Some(vis_did) {
1413                    // `pub(in foo)` where `foo` is the parent module
1414                    // is the same as no visibility modifier; do nothing
1415                } else if parent_module
1416                    .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1417                    == Some(vis_did)
1418                {
1419                    f.write_str("pub(super) ")?;
1420                } else {
1421                    let path = cx.tcx().def_path(vis_did);
1422                    debug!("path={path:?}");
1423                    // modified from `resolved_path()` to work with `DefPathData`
1424                    let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1425                    let anchor = print_anchor(vis_did, last_name, cx);
1426
1427                    f.write_str("pub(in ")?;
1428                    for seg in &path.data[..path.data.len() - 1] {
1429                        write!(f, "{}::", seg.data.get_opt_name().unwrap())?;
1430                    }
1431                    write!(f, "{anchor}) ")?;
1432                }
1433            }
1434        }
1435        Ok(())
1436    })
1437}
1438
1439pub(crate) trait PrintWithSpace {
1440    fn print_with_space(&self) -> &str;
1441}
1442
1443impl PrintWithSpace for hir::Safety {
1444    fn print_with_space(&self) -> &str {
1445        self.prefix_str()
1446    }
1447}
1448
1449impl PrintWithSpace for hir::HeaderSafety {
1450    fn print_with_space(&self) -> &str {
1451        match self {
1452            hir::HeaderSafety::SafeTargetFeatures => "",
1453            hir::HeaderSafety::Normal(safety) => safety.print_with_space(),
1454        }
1455    }
1456}
1457
1458impl PrintWithSpace for hir::IsAsync {
1459    fn print_with_space(&self) -> &str {
1460        match self {
1461            hir::IsAsync::Async(_) => "async ",
1462            hir::IsAsync::NotAsync => "",
1463        }
1464    }
1465}
1466
1467impl PrintWithSpace for hir::Mutability {
1468    fn print_with_space(&self) -> &str {
1469        match self {
1470            hir::Mutability::Not => "",
1471            hir::Mutability::Mut => "mut ",
1472        }
1473    }
1474}
1475
1476pub(crate) fn print_constness_with_space(
1477    c: &hir::Constness,
1478    overall_stab: Option<StableSince>,
1479    const_stab: Option<ConstStability>,
1480) -> &'static str {
1481    match c {
1482        hir::Constness::Const => match (overall_stab, const_stab) {
1483            // const stable...
1484            (_, Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }))
1485            // ...or when feature(staged_api) is not set...
1486            | (_, None)
1487            // ...or when const unstable, but overall unstable too
1488            | (None, Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => {
1489                "const "
1490            }
1491            // const unstable (and overall stable)
1492            (Some(_), Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => "",
1493        },
1494        // not const
1495        hir::Constness::NotConst => "",
1496    }
1497}
1498
1499pub(crate) fn print_import(import: &clean::Import, cx: &Context<'_>) -> impl Display {
1500    fmt::from_fn(move |f| match import.kind {
1501        clean::ImportKind::Simple(name) => {
1502            if name == import.source.path.last() {
1503                write!(f, "use {};", print_import_source(&import.source, cx))
1504            } else {
1505                write!(
1506                    f,
1507                    "use {source} as {name};",
1508                    source = print_import_source(&import.source, cx)
1509                )
1510            }
1511        }
1512        clean::ImportKind::Glob => {
1513            if import.source.path.segments.is_empty() {
1514                write!(f, "use *;")
1515            } else {
1516                write!(f, "use {}::*;", print_import_source(&import.source, cx))
1517            }
1518        }
1519    })
1520}
1521
1522fn print_import_source(import_source: &clean::ImportSource, cx: &Context<'_>) -> impl Display {
1523    fmt::from_fn(move |f| match import_source.did {
1524        Some(did) => resolved_path(f, did, &import_source.path, true, false, cx),
1525        _ => {
1526            for seg in &import_source.path.segments[..import_source.path.segments.len() - 1] {
1527                write!(f, "{}::", seg.name)?;
1528            }
1529            let name = import_source.path.last();
1530            if let hir::def::Res::PrimTy(p) = import_source.path.res {
1531                primitive_link(f, PrimitiveType::from(p), format_args!("{name}"), cx)?;
1532            } else {
1533                f.write_str(name.as_str())?;
1534            }
1535            Ok(())
1536        }
1537    })
1538}
1539
1540fn print_assoc_item_constraint(
1541    assoc_item_constraint: &clean::AssocItemConstraint,
1542    cx: &Context<'_>,
1543) -> impl Display {
1544    fmt::from_fn(move |f| {
1545        f.write_str(assoc_item_constraint.assoc.name.as_str())?;
1546        print_generic_args(&assoc_item_constraint.assoc.args, cx).fmt(f)?;
1547        match assoc_item_constraint.kind {
1548            clean::AssocItemConstraintKind::Equality { ref term } => {
1549                f.write_str(" = ")?;
1550                print_term(term, cx).fmt(f)?;
1551            }
1552            clean::AssocItemConstraintKind::Bound { ref bounds } => {
1553                if !bounds.is_empty() {
1554                    f.write_str(": ")?;
1555                    print_generic_bounds(bounds, cx).fmt(f)?;
1556                }
1557            }
1558        }
1559        Ok(())
1560    })
1561}
1562
1563pub(crate) fn print_abi_with_space(abi: ExternAbi) -> impl Display {
1564    fmt::from_fn(move |f| {
1565        let quot = if f.alternate() { "\"" } else { "&quot;" };
1566        match abi {
1567            ExternAbi::Rust => Ok(()),
1568            abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1569        }
1570    })
1571}
1572
1573pub(crate) fn print_default_space(v: bool) -> &'static str {
1574    if v { "default " } else { "" }
1575}
1576
1577fn print_generic_arg(generic_arg: &clean::GenericArg, cx: &Context<'_>) -> impl Display {
1578    fmt::from_fn(move |f| match generic_arg {
1579        clean::GenericArg::Lifetime(lt) => f.write_str(print_lifetime(lt)),
1580        clean::GenericArg::Type(ty) => print_type(ty, cx).fmt(f),
1581        clean::GenericArg::Const(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1582        clean::GenericArg::Infer => f.write_char('_'),
1583    })
1584}
1585
1586fn print_term(term: &clean::Term, cx: &Context<'_>) -> impl Display {
1587    fmt::from_fn(move |f| match term {
1588        clean::Term::Type(ty) => print_type(ty, cx).fmt(f),
1589        clean::Term::Constant(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1590    })
1591}