Skip to main content

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;
26use rustc_span::symbol::kw;
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 path = clean::inline::get_item_path(tcx, def_id, item_type);
390    // The minimum we can have is the crate name followed by the macro name. If shorter, then
391    // it means that `relative` was empty, which is an error.
392    let [module_path @ .., last] = path.as_slice() else {
393        debug!("macro path is empty!");
394        return Err(HrefError::NotInExternalCache);
395    };
396    if module_path.is_empty() {
397        debug!("macro path too short: missing crate prefix (got 1 element, need at least 2)");
398        return Err(HrefError::NotInExternalCache);
399    }
400
401    let url = match cache.extern_locations[&def_id.krate] {
402        ExternalLocation::Remote { ref url, is_absolute } => {
403            let mut prefix = remote_url_prefix(url, is_absolute, cx.current.len());
404            prefix.extend(module_path.iter().copied());
405            prefix.push_fmt(format_args!("{}.{last}.html", item_type.as_str()));
406            prefix.finish()
407        }
408        ExternalLocation::Local => {
409            // `root_path` always end with a `/`.
410            format!(
411                "{root_path}{path}/{item_type}.{last}.html",
412                root_path = root_path.unwrap_or(""),
413                path = fmt::from_fn(|f| module_path.iter().joined("/", f)),
414                item_type = item_type.as_str(),
415            )
416        }
417        ExternalLocation::Unknown => {
418            debug!("crate {crate_name} not in cache when linkifying macros");
419            return Err(HrefError::NotInExternalCache);
420        }
421    };
422    Ok(HrefInfo { url, kind: item_type, rust_path: path })
423}
424
425fn generate_item_def_id_path(
426    mut def_id: DefId,
427    original_def_id: DefId,
428    cx: &Context<'_>,
429    root_path: Option<&str>,
430) -> Result<HrefInfo, HrefError> {
431    use rustc_middle::traits::ObligationCause;
432    use rustc_trait_selection::infer::TyCtxtInferExt;
433    use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
434
435    let tcx = cx.tcx();
436    let crate_name = tcx.crate_name(def_id.krate);
437
438    // No need to try to infer the actual parent item if it's not an associated item from the `impl`
439    // block.
440    if def_id != original_def_id && matches!(tcx.def_kind(def_id), DefKind::Impl { .. }) {
441        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
442        def_id = infcx
443            .at(&ObligationCause::dummy(), tcx.param_env(def_id))
444            .query_normalize(ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()))
445            .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
446            .ok()
447            .and_then(|normalized| normalized.skip_binder().ty_adt_def())
448            .map(|adt| adt.did())
449            .unwrap_or(def_id);
450    }
451
452    let relative = clean::inline::item_relative_path(tcx, def_id);
453    let fqp: Vec<Symbol> = once(crate_name).chain(relative).collect();
454
455    let shortty = ItemType::from_def_id(def_id, tcx);
456    let module_fqp = to_module_fqp(shortty, &fqp);
457
458    let (parts, is_absolute) = url_parts(cx.cache(), def_id, module_fqp, &cx.current)?;
459    let mut url = make_href(root_path, shortty, parts, &fqp, is_absolute);
460
461    if def_id != original_def_id {
462        let kind = ItemType::from_def_id(original_def_id, tcx);
463        url = format!("{url}#{kind}.{}", tcx.item_name(original_def_id))
464    };
465    Ok(HrefInfo { url, kind: shortty, rust_path: fqp })
466}
467
468/// Checks if the given defid refers to an item that is unnamable, such as one defined in a const block.
469fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool {
470    let mut cur_did = did;
471    while let Some(parent) = tcx.opt_parent(cur_did) {
472        match tcx.def_kind(parent) {
473            // items defined in these can be linked to, as long as they are visible
474            DefKind::Mod | DefKind::ForeignMod => cur_did = parent,
475            // items in impls can be linked to,
476            // as long as we can link to the item the impl is on.
477            // since associated traits are not a thing,
478            // it should not be possible to refer to an impl item if
479            // the base type is not namable.
480            DefKind::Impl { .. } => return false,
481            // everything else does not have docs generated for it
482            _ => return true,
483        }
484    }
485    return false;
486}
487
488fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
489    if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
490}
491
492fn remote_url_prefix(url: &str, is_absolute: bool, depth: usize) -> UrlPartsBuilder {
493    let url = url.trim_end_matches('/');
494    if is_absolute {
495        UrlPartsBuilder::singleton(url)
496    } else {
497        let extra = depth.saturating_sub(1);
498        let mut b: UrlPartsBuilder = iter::repeat_n("..", extra).collect();
499        b.push(url);
500        b
501    }
502}
503
504fn url_parts(
505    cache: &Cache,
506    def_id: DefId,
507    module_fqp: &[Symbol],
508    relative_to: &[Symbol],
509) -> Result<(UrlPartsBuilder, bool), HrefError> {
510    match cache.extern_locations[&def_id.krate] {
511        ExternalLocation::Remote { ref url, is_absolute } => {
512            let mut builder = remote_url_prefix(url, is_absolute, relative_to.len());
513            builder.extend(module_fqp.iter().copied());
514            Ok((builder, is_absolute))
515        }
516        ExternalLocation::Local => Ok((href_relative_parts(module_fqp, relative_to), false)),
517        ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt),
518    }
519}
520
521fn make_href(
522    root_path: Option<&str>,
523    shortty: ItemType,
524    mut url_parts: UrlPartsBuilder,
525    fqp: &[Symbol],
526    is_absolute: bool,
527) -> String {
528    // FIXME: relative extern URLs may break when prefixed with root_path
529    if !is_absolute && let Some(root_path) = root_path {
530        let root = root_path.trim_end_matches('/');
531        url_parts.push_front(root);
532    }
533    debug!(?url_parts);
534    match shortty {
535        ItemType::Module => {
536            url_parts.push("index.html");
537        }
538        _ => {
539            let last = fqp.last().unwrap();
540            url_parts.push_fmt(format_args!("{shortty}.{last}.html"));
541        }
542    }
543    url_parts.finish()
544}
545
546pub(crate) fn href_with_root_path(
547    original_did: DefId,
548    cx: &Context<'_>,
549    root_path: Option<&str>,
550) -> Result<HrefInfo, HrefError> {
551    let tcx = cx.tcx();
552    let def_kind = tcx.def_kind(original_did);
553    let did = match def_kind {
554        DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
555            // documented on their parent's page
556            tcx.parent(original_did)
557        }
558        // If this a constructor, we get the parent (either a struct or a variant) and then
559        // generate the link for this item.
560        DefKind::Ctor(..) => return href_with_root_path(tcx.parent(original_did), cx, root_path),
561        DefKind::ExternCrate => {
562            // Link to the crate itself, not the `extern crate` item.
563            if let Some(local_did) = original_did.as_local() {
564                tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
565            } else {
566                original_did
567            }
568        }
569        _ => original_did,
570    };
571    if is_unnamable(cx.tcx(), did) {
572        return Err(HrefError::UnnamableItem);
573    }
574    let cache = cx.cache();
575    let relative_to = &cx.current;
576
577    if !original_did.is_local() {
578        // If we are generating an href for the "jump to def" feature, then the only case we want
579        // to ignore is if the item is `doc(hidden)` because we can't link to it.
580        if root_path.is_some() {
581            if tcx.is_doc_hidden(original_did) {
582                return Err(HrefError::Private);
583            }
584        } else if !cache.effective_visibilities.is_directly_public(tcx, did)
585            && !cache.document_private
586            && !cache.primitive_locations.values().any(|&id| id == did)
587        {
588            return Err(HrefError::Private);
589        }
590    }
591
592    let (fqp, shortty, url_parts, is_absolute) = match cache.paths.get(&did) {
593        Some(&(ref fqp, shortty)) => (
594            fqp,
595            shortty,
596            {
597                let module_fqp = to_module_fqp(shortty, fqp.as_slice());
598                debug!(?fqp, ?shortty, ?module_fqp);
599                href_relative_parts(module_fqp, relative_to)
600            },
601            false,
602        ),
603        None => {
604            // Associated items are handled differently with "jump to def". The anchor is generated
605            // directly here whereas for intra-doc links, we have some extra computation being
606            // performed there.
607            let def_id_to_get = if root_path.is_some() { original_did } else { did };
608            if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&def_id_to_get) {
609                let module_fqp = to_module_fqp(shortty, fqp);
610                let (parts, is_absolute) = url_parts(cache, did, module_fqp, relative_to)?;
611                (fqp, shortty, parts, is_absolute)
612            } else if matches!(def_kind, DefKind::Macro(_)) {
613                return generate_macro_def_id_path(did, cx, root_path);
614            } else if did.is_local() {
615                return Err(HrefError::Private);
616            } else {
617                return generate_item_def_id_path(did, original_did, cx, root_path);
618            }
619        }
620    };
621    Ok(HrefInfo {
622        url: make_href(root_path, shortty, url_parts, fqp, is_absolute),
623        kind: shortty,
624        rust_path: fqp.clone(),
625    })
626}
627
628pub(crate) fn href(did: DefId, cx: &Context<'_>) -> Result<HrefInfo, HrefError> {
629    href_with_root_path(did, cx, None)
630}
631
632/// Both paths should only be modules.
633/// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
634/// both need `../iter/trait.Iterator.html` to get at the iterator trait.
635pub(crate) fn href_relative_parts(fqp: &[Symbol], relative_to_fqp: &[Symbol]) -> UrlPartsBuilder {
636    for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
637        // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
638        if f != r {
639            let dissimilar_part_count = relative_to_fqp.len() - i;
640            let fqp_module = &fqp[i..];
641            return iter::repeat_n("..", dissimilar_part_count)
642                .chain(fqp_module.iter().map(|s| s.as_str()))
643                .collect();
644        }
645    }
646    match relative_to_fqp.len().cmp(&fqp.len()) {
647        Ordering::Less => {
648            // e.g. linking to std::sync::atomic from std::sync
649            fqp[relative_to_fqp.len()..fqp.len()].iter().copied().collect()
650        }
651        Ordering::Greater => {
652            // e.g. linking to std::sync from std::sync::atomic
653            let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
654            iter::repeat_n("..", dissimilar_part_count).collect()
655        }
656        Ordering::Equal => {
657            // linking to the same module
658            UrlPartsBuilder::new()
659        }
660    }
661}
662
663pub(crate) fn link_tooltip(
664    did: DefId,
665    fragment: &Option<UrlFragment>,
666    cx: &Context<'_>,
667) -> impl fmt::Display {
668    fmt::from_fn(move |f| {
669        let cache = cx.cache();
670        let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did))
671        else {
672            return Ok(());
673        };
674        let fqp = if *shortty == ItemType::Primitive {
675            // primitives are documented in a crate, but not actually part of it
676            slice::from_ref(fqp.last().unwrap())
677        } else {
678            fqp
679        };
680        if let &Some(UrlFragment::Item(id)) = fragment {
681            write!(f, "{} ", cx.tcx().def_descr(id))?;
682            for component in fqp {
683                write!(f, "{component}::")?;
684            }
685            write!(f, "{}", cx.tcx().item_name(id))?;
686        } else if !fqp.is_empty() {
687            write!(f, "{shortty} ")?;
688            write!(f, "{}", join_path_syms(fqp))?;
689        }
690        Ok(())
691    })
692}
693
694/// Used to render a [`clean::Path`].
695fn resolved_path(
696    w: &mut fmt::Formatter<'_>,
697    did: DefId,
698    path: &clean::Path,
699    print_all: bool,
700    use_absolute: bool,
701    cx: &Context<'_>,
702) -> fmt::Result {
703    let last = path.segments.last().unwrap();
704
705    if print_all {
706        for seg in &path.segments[..path.segments.len() - 1] {
707            write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
708        }
709    }
710    if w.alternate() {
711        write!(w, "{}{:#}", last.name, print_generic_args(&last.args, cx))?;
712    } else {
713        let path = fmt::from_fn(|f| {
714            if use_absolute {
715                if let Ok(HrefInfo { rust_path, .. }) = href(did, cx) {
716                    write!(
717                        f,
718                        "{path}::{anchor}",
719                        path = join_path_syms(&rust_path[..rust_path.len() - 1]),
720                        anchor = print_anchor(did, *rust_path.last().unwrap(), cx)
721                    )
722                } else {
723                    write!(f, "{}", last.name)
724                }
725            } else {
726                write!(f, "{}", print_anchor(did, last.name, cx))
727            }
728        });
729        write!(w, "{path}{args}", args = print_generic_args(&last.args, cx))?;
730    }
731    Ok(())
732}
733
734fn primitive_link(
735    f: &mut fmt::Formatter<'_>,
736    prim: clean::PrimitiveType,
737    name: fmt::Arguments<'_>,
738    cx: &Context<'_>,
739) -> fmt::Result {
740    primitive_link_fragment(f, prim, name, "", cx)
741}
742
743fn primitive_link_fragment(
744    f: &mut fmt::Formatter<'_>,
745    prim: clean::PrimitiveType,
746    name: fmt::Arguments<'_>,
747    fragment: &str,
748    cx: &Context<'_>,
749) -> fmt::Result {
750    let m = &cx.cache();
751    let mut needs_termination = false;
752    if !f.alternate() {
753        match m.primitive_locations.get(&prim) {
754            Some(&def_id) if def_id.is_local() => {
755                let len = cx.current.len();
756                let path = fmt::from_fn(|f| {
757                    if len == 0 {
758                        let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
759                        write!(f, "{cname_sym}/")?;
760                    } else {
761                        for _ in 0..(len - 1) {
762                            f.write_str("../")?;
763                        }
764                    }
765                    Ok(())
766                });
767                write!(
768                    f,
769                    "<a class=\"primitive\" href=\"{path}primitive.{}.html{fragment}\">",
770                    prim.as_sym()
771                )?;
772                needs_termination = true;
773            }
774            Some(&def_id) => {
775                let loc = match m.extern_locations[&def_id.krate] {
776                    ExternalLocation::Remote { ref url, is_absolute } => {
777                        let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
778                        let mut builder = remote_url_prefix(url, is_absolute, cx.current.len());
779                        builder.push(cname_sym.as_str());
780                        Some(builder)
781                    }
782                    ExternalLocation::Local => {
783                        let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
784                        Some(if cx.current.first() == Some(&cname_sym) {
785                            iter::repeat_n("..", cx.current.len() - 1).collect()
786                        } else {
787                            iter::repeat_n("..", cx.current.len())
788                                .chain(iter::once(cname_sym.as_str()))
789                                .collect()
790                        })
791                    }
792                    ExternalLocation::Unknown => None,
793                };
794                if let Some(mut loc) = loc {
795                    loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
796                    write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
797                    needs_termination = true;
798                }
799            }
800            None => {}
801        }
802    }
803    Display::fmt(&name, f)?;
804    if needs_termination {
805        write!(f, "</a>")?;
806    }
807    Ok(())
808}
809
810fn print_tybounds(
811    bounds: &[clean::PolyTrait],
812    lt: &Option<clean::Lifetime>,
813    cx: &Context<'_>,
814) -> impl Display {
815    fmt::from_fn(move |f| {
816        bounds.iter().map(|bound| print_poly_trait(bound, cx)).joined(" + ", f)?;
817        if let Some(lt) = lt {
818            // We don't need to check `alternate` since we can be certain that
819            // the lifetime doesn't contain any characters which need escaping.
820            write!(f, " + {}", print_lifetime(lt))?;
821        }
822        Ok(())
823    })
824}
825
826fn print_higher_ranked_params_with_space(
827    params: &[clean::GenericParamDef],
828    cx: &Context<'_>,
829    keyword: &'static str,
830) -> impl Display {
831    fmt::from_fn(move |f| {
832        if !params.is_empty() {
833            f.write_str(keyword)?;
834            Wrapped::with_angle_brackets()
835                .wrap_fn(|f| {
836                    params.iter().map(|lt| print_generic_param_def(lt, cx)).joined(", ", f)
837                })
838                .fmt(f)?;
839            f.write_char(' ')?;
840        }
841        Ok(())
842    })
843}
844
845pub(crate) fn fragment(did: DefId, tcx: TyCtxt<'_>) -> impl Display {
846    fmt::from_fn(move |f| {
847        let def_kind = tcx.def_kind(did);
848        match def_kind {
849            DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
850                let item_type = ItemType::from_def_id(did, tcx);
851                write!(f, "#{}.{}", item_type.as_str(), tcx.item_name(did))
852            }
853            DefKind::Field => {
854                let parent_def_id = tcx.parent(did);
855                f.write_char('#')?;
856                if tcx.def_kind(parent_def_id) == DefKind::Variant {
857                    write!(f, "variant.{}.field", tcx.item_name(parent_def_id).as_str())?;
858                } else {
859                    f.write_str("structfield")?;
860                };
861                write!(f, ".{}", tcx.item_name(did))
862            }
863            _ => Ok(()),
864        }
865    })
866}
867
868pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
869    fmt::from_fn(move |f| {
870        if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) {
871            write!(
872                f,
873                r#"<a class="{kind}" href="{url}{anchor}" title="{kind} {path}">{text}</a>"#,
874                anchor = fragment(did, cx.tcx()),
875                path = join_path_syms(rust_path),
876                text = EscapeBodyText(text.as_str()),
877            )
878        } else {
879            f.write_str(text.as_str())
880        }
881    })
882}
883
884fn fmt_type(
885    t: &clean::Type,
886    f: &mut fmt::Formatter<'_>,
887    use_absolute: bool,
888    cx: &Context<'_>,
889) -> fmt::Result {
890    trace!("fmt_type(t = {t:?})");
891
892    match t {
893        clean::Generic(name) => f.write_str(name.as_str()),
894        clean::SelfTy => f.write_str("Self"),
895        clean::Type::Path { path } => {
896            // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
897            let did = path.def_id();
898            resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
899        }
900        clean::DynTrait(bounds, lt) => {
901            f.write_str("dyn ")?;
902            print_tybounds(bounds, lt, cx).fmt(f)
903        }
904        clean::Infer => write!(f, "_"),
905        clean::Primitive(clean::PrimitiveType::Never) => {
906            primitive_link(f, PrimitiveType::Never, format_args!("!"), cx)
907        }
908        &clean::Primitive(prim) => primitive_link(f, prim, format_args!("{}", prim.as_sym()), cx),
909        clean::BareFunction(decl) => {
910            print_higher_ranked_params_with_space(&decl.generic_params, cx, "for").fmt(f)?;
911            decl.safety.print_with_space().fmt(f)?;
912            print_abi_with_space(decl.abi).fmt(f)?;
913            if f.alternate() {
914                f.write_str("fn")?;
915            } else {
916                primitive_link(f, PrimitiveType::Fn, format_args!("fn"), cx)?;
917            }
918            print_fn_decl(&decl.decl, cx).fmt(f)
919        }
920        clean::UnsafeBinder(binder) => {
921            print_higher_ranked_params_with_space(&binder.generic_params, cx, "unsafe").fmt(f)?;
922            print_type(&binder.ty, cx).fmt(f)
923        }
924        clean::Tuple(typs) => match &typs[..] {
925            &[] => primitive_link(f, PrimitiveType::Unit, format_args!("()"), cx),
926            [one] => {
927                if let clean::Generic(name) = one {
928                    primitive_link(f, PrimitiveType::Tuple, format_args!("({name},)"), cx)
929                } else {
930                    write!(f, "(")?;
931                    print_type(one, cx).fmt(f)?;
932                    write!(f, ",)")
933                }
934            }
935            many => {
936                let generic_names: Vec<Symbol> = many
937                    .iter()
938                    .filter_map(|t| match t {
939                        clean::Generic(name) => Some(*name),
940                        _ => None,
941                    })
942                    .collect();
943                let is_generic = generic_names.len() == many.len();
944                if is_generic {
945                    primitive_link(
946                        f,
947                        PrimitiveType::Tuple,
948                        format_args!(
949                            "{}",
950                            Wrapped::with_parens()
951                                .wrap_fn(|f| generic_names.iter().joined(", ", f))
952                        ),
953                        cx,
954                    )
955                } else {
956                    Wrapped::with_parens()
957                        .wrap_fn(|f| many.iter().map(|item| print_type(item, cx)).joined(", ", f))
958                        .fmt(f)
959                }
960            }
961        },
962        clean::Slice(box clean::Generic(name)) => {
963            primitive_link(f, PrimitiveType::Slice, format_args!("[{name}]"), cx)
964        }
965        clean::Slice(t) => Wrapped::with_square_brackets().wrap(print_type(t, cx)).fmt(f),
966        clean::Type::Pat(t, pat) => {
967            fmt::Display::fmt(&print_type(t, cx), f)?;
968            write!(f, " is {pat}")
969        }
970        clean::Array(box clean::Generic(name), n) if !f.alternate() => primitive_link(
971            f,
972            PrimitiveType::Array,
973            format_args!("[{name}; {n}]", n = Escape(n)),
974            cx,
975        ),
976        clean::Array(t, n) => Wrapped::with_square_brackets()
977            .wrap(fmt::from_fn(|f| {
978                print_type(t, cx).fmt(f)?;
979                f.write_str("; ")?;
980                if f.alternate() {
981                    f.write_str(n)
982                } else {
983                    primitive_link(f, PrimitiveType::Array, format_args!("{n}", n = Escape(n)), cx)
984                }
985            }))
986            .fmt(f),
987        clean::RawPointer(m, t) => {
988            let m = m.ptr_str();
989
990            if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
991                primitive_link(
992                    f,
993                    clean::PrimitiveType::RawPointer,
994                    format_args!("*{m} {ty}", ty = WithOpts::from(f).display(print_type(t, cx))),
995                    cx,
996                )
997            } else {
998                primitive_link(f, clean::PrimitiveType::RawPointer, format_args!("*{m} "), cx)?;
999                print_type(t, cx).fmt(f)
1000            }
1001        }
1002        clean::BorrowedRef { lifetime: l, mutability, type_: ty } => {
1003            let lt = fmt::from_fn(|f| match l {
1004                Some(l) => write!(f, "{} ", print_lifetime(l)),
1005                _ => Ok(()),
1006            });
1007            let m = mutability.print_with_space();
1008            let amp = if f.alternate() { "&" } else { "&amp;" };
1009
1010            if let clean::Generic(name) = **ty {
1011                return primitive_link(
1012                    f,
1013                    PrimitiveType::Reference,
1014                    format_args!("{amp}{lt}{m}{name}"),
1015                    cx,
1016                );
1017            }
1018
1019            write!(f, "{amp}{lt}{m}")?;
1020
1021            let needs_parens = match **ty {
1022                clean::DynTrait(ref bounds, ref trait_lt)
1023                    if bounds.len() > 1 || trait_lt.is_some() =>
1024                {
1025                    true
1026                }
1027                clean::ImplTrait(ref bounds) if bounds.len() > 1 => true,
1028                _ => false,
1029            };
1030            Wrapped::with_parens()
1031                .when(needs_parens)
1032                .wrap_fn(|f| fmt_type(ty, f, use_absolute, cx))
1033                .fmt(f)
1034        }
1035        clean::ImplTrait(bounds) => {
1036            f.write_str("impl ")?;
1037            print_generic_bounds(bounds, cx).fmt(f)
1038        }
1039        clean::QPath(qpath) => print_qpath_data(qpath, cx).fmt(f),
1040    }
1041}
1042
1043pub(crate) fn print_type(type_: &clean::Type, cx: &Context<'_>) -> impl Display {
1044    fmt::from_fn(move |f| fmt_type(type_, f, false, cx))
1045}
1046
1047pub(crate) fn print_path(path: &clean::Path, cx: &Context<'_>) -> impl Display {
1048    fmt::from_fn(move |f| resolved_path(f, path.def_id(), path, false, false, cx))
1049}
1050
1051fn print_qpath_data(qpath_data: &clean::QPathData, cx: &Context<'_>) -> impl Display {
1052    let clean::QPathData { ref assoc, ref self_type, should_fully_qualify, ref trait_ } =
1053        *qpath_data;
1054
1055    fmt::from_fn(move |f| {
1056        // FIXME(inherent_associated_types): Once we support non-ADT self-types (#106719),
1057        // we need to surround them with angle brackets in some cases (e.g. `<dyn …>::P`).
1058
1059        if let Some(trait_) = trait_
1060            && should_fully_qualify
1061        {
1062            let opts = WithOpts::from(f);
1063            Wrapped::with_angle_brackets()
1064                .wrap(format_args!(
1065                    "{} as {}",
1066                    opts.display(print_type(self_type, cx)),
1067                    opts.display(print_path(trait_, cx))
1068                ))
1069                .fmt(f)?
1070        } else {
1071            print_type(self_type, cx).fmt(f)?;
1072        }
1073        f.write_str("::")?;
1074        // It's pretty unsightly to look at `<A as B>::C` in output, and
1075        // we've got hyperlinking on our side, so try to avoid longer
1076        // notation as much as possible by making `C` a hyperlink to trait
1077        // `B` to disambiguate.
1078        //
1079        // FIXME: this is still a lossy conversion and there should probably
1080        //        be a better way of representing this in general? Most of
1081        //        the ugliness comes from inlining across crates where
1082        //        everything comes in as a fully resolved QPath (hard to
1083        //        look at).
1084        if !f.alternate() {
1085            // FIXME(inherent_associated_types): We always link to the very first associated
1086            // type (in respect to source order) that bears the given name (`assoc.name`) and that is
1087            // affiliated with the computed `DefId`. This is obviously incorrect when we have
1088            // multiple impl blocks. Ideally, we would thread the `DefId` of the assoc ty itself
1089            // through here and map it to the corresponding HTML ID that was generated by
1090            // `render::Context::derive_id` when the impl blocks were rendered.
1091            // There is no such mapping unfortunately.
1092            // As a hack, we could badly imitate `derive_id` here by keeping *count* when looking
1093            // for the assoc ty `DefId` in `tcx.associated_items(self_ty_did).in_definition_order()`
1094            // considering privacy, `doc(hidden)`, etc.
1095            // I don't feel like that right now :cold_sweat:.
1096
1097            let parent_href = match trait_ {
1098                Some(trait_) => href(trait_.def_id(), cx).ok(),
1099                None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()),
1100            };
1101
1102            if let Some(HrefInfo { url, rust_path, .. }) = parent_href {
1103                write!(
1104                    f,
1105                    "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1106                                title=\"type {path}::{name}\">{name}</a>",
1107                    shortty = ItemType::AssocType,
1108                    name = assoc.name,
1109                    path = join_path_syms(rust_path),
1110                )
1111            } else {
1112                write!(f, "{}", assoc.name)
1113            }
1114        } else {
1115            write!(f, "{}", assoc.name)
1116        }?;
1117
1118        print_generic_args(&assoc.args, cx).fmt(f)
1119    })
1120}
1121
1122pub(crate) fn print_impl(
1123    impl_: &clean::Impl,
1124    use_absolute: bool,
1125    cx: &Context<'_>,
1126) -> impl Display {
1127    fmt::from_fn(move |f| {
1128        f.write_str("impl")?;
1129        print_generics(&impl_.generics, cx).fmt(f)?;
1130        f.write_str(" ")?;
1131
1132        if let Some(ref ty) = impl_.trait_ {
1133            if impl_.is_negative_trait_impl() {
1134                f.write_char('!')?;
1135            }
1136            if impl_.kind.is_fake_variadic()
1137                && let Some(generics) = ty.generics()
1138                && let Ok(inner_type) = generics.exactly_one()
1139            {
1140                let last = ty.last();
1141                if f.alternate() {
1142                    write!(f, "{last}")?;
1143                } else {
1144                    write!(f, "{}", print_anchor(ty.def_id(), last, cx))?;
1145                };
1146                Wrapped::with_angle_brackets()
1147                    .wrap_fn(|f| impl_.print_type(inner_type, f, use_absolute, cx))
1148                    .fmt(f)?;
1149            } else {
1150                print_path(ty, cx).fmt(f)?;
1151            }
1152            f.write_str(" for ")?;
1153        }
1154
1155        if let Some(ty) = impl_.kind.as_blanket_ty() {
1156            fmt_type(ty, f, use_absolute, cx)?;
1157        } else {
1158            impl_.print_type(&impl_.for_, f, use_absolute, cx)?;
1159        }
1160
1161        print_where_clause(&impl_.generics, cx, 0, Ending::Newline).maybe_display().fmt(f)
1162    })
1163}
1164
1165impl clean::Impl {
1166    fn print_type(
1167        &self,
1168        type_: &clean::Type,
1169        f: &mut fmt::Formatter<'_>,
1170        use_absolute: bool,
1171        cx: &Context<'_>,
1172    ) -> Result<(), fmt::Error> {
1173        if let clean::Type::Tuple(types) = type_
1174            && let [clean::Type::Generic(name)] = &types[..]
1175            && (self.kind.is_fake_variadic() || self.kind.is_auto())
1176        {
1177            // Hardcoded anchor library/core/src/primitive_docs.rs
1178            // Link should match `# Trait implementations`
1179            primitive_link_fragment(
1180                f,
1181                PrimitiveType::Tuple,
1182                format_args!("({name}₁, {name}₂, …, {name}ₙ)"),
1183                "#trait-implementations-1",
1184                cx,
1185            )?;
1186        } else if let clean::Type::Array(ty, len) = type_
1187            && let clean::Type::Generic(name) = &**ty
1188            && &len[..] == "1"
1189            && (self.kind.is_fake_variadic() || self.kind.is_auto())
1190        {
1191            primitive_link(f, PrimitiveType::Array, format_args!("[{name}; N]"), cx)?;
1192        } else if let clean::BareFunction(bare_fn) = &type_
1193            && let [clean::Parameter { type_: clean::Type::Generic(name), .. }] =
1194                &bare_fn.decl.inputs[..]
1195            && (self.kind.is_fake_variadic() || self.kind.is_auto())
1196        {
1197            // Hardcoded anchor library/core/src/primitive_docs.rs
1198            // Link should match `# Trait implementations`
1199
1200            print_higher_ranked_params_with_space(&bare_fn.generic_params, cx, "for").fmt(f)?;
1201            bare_fn.safety.print_with_space().fmt(f)?;
1202            print_abi_with_space(bare_fn.abi).fmt(f)?;
1203            let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" };
1204            primitive_link_fragment(
1205                f,
1206                PrimitiveType::Tuple,
1207                format_args!("fn({name}₁, {name}₂, …, {name}ₙ{ellipsis})"),
1208                "#trait-implementations-1",
1209                cx,
1210            )?;
1211            // Write output.
1212            if !bare_fn.decl.output.is_unit() {
1213                write!(f, " -> ")?;
1214                fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?;
1215            }
1216        } else if let clean::Type::Path { path } = type_
1217            && let Some(generics) = path.generics()
1218            && let Ok(ty) = generics.exactly_one()
1219            && self.kind.is_fake_variadic()
1220        {
1221            print_anchor(path.def_id(), path.last(), cx).fmt(f)?;
1222            Wrapped::with_angle_brackets()
1223                .wrap_fn(|f| self.print_type(ty, f, use_absolute, cx))
1224                .fmt(f)?;
1225        } else {
1226            fmt_type(type_, f, use_absolute, cx)?;
1227        }
1228        Ok(())
1229    }
1230}
1231
1232pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> impl Display {
1233    fmt::from_fn(move |f| {
1234        params
1235            .iter()
1236            .map(|param| {
1237                fmt::from_fn(|f| {
1238                    if let Some(name) = param.name {
1239                        write!(f, "{name}: ")?;
1240                    }
1241                    print_type(&param.type_, cx).fmt(f)
1242                })
1243            })
1244            .joined(", ", f)
1245    })
1246}
1247
1248// Implements Write but only counts the bytes "written".
1249struct WriteCounter(usize);
1250
1251impl std::fmt::Write for WriteCounter {
1252    fn write_str(&mut self, s: &str) -> fmt::Result {
1253        self.0 += s.len();
1254        Ok(())
1255    }
1256}
1257
1258// Implements Display by emitting the given number of spaces.
1259#[derive(Clone, Copy)]
1260struct Indent(usize);
1261
1262impl Display for Indent {
1263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1264        for _ in 0..self.0 {
1265            f.write_char(' ')?;
1266        }
1267        Ok(())
1268    }
1269}
1270
1271fn print_parameter(parameter: &clean::Parameter, cx: &Context<'_>) -> impl fmt::Display {
1272    fmt::from_fn(move |f| {
1273        if let Some(self_ty) = parameter.to_receiver() {
1274            match self_ty {
1275                clean::SelfTy => f.write_str("self"),
1276                clean::BorrowedRef { lifetime, mutability, type_: box clean::SelfTy } => {
1277                    f.write_str(if f.alternate() { "&" } else { "&amp;" })?;
1278                    if let Some(lt) = lifetime {
1279                        write!(f, "{lt} ", lt = print_lifetime(lt))?;
1280                    }
1281                    write!(f, "{mutability}self", mutability = mutability.print_with_space())
1282                }
1283                _ => {
1284                    f.write_str("self: ")?;
1285                    print_type(self_ty, cx).fmt(f)
1286                }
1287            }
1288        } else {
1289            if parameter.is_const {
1290                write!(f, "const ")?;
1291            }
1292            if let Some(name) = parameter.name {
1293                write!(f, "{name}: ")?;
1294            }
1295            print_type(&parameter.type_, cx).fmt(f)
1296        }
1297    })
1298}
1299
1300fn print_fn_decl(fn_decl: &clean::FnDecl, cx: &Context<'_>) -> impl Display {
1301    fmt::from_fn(move |f| {
1302        let ellipsis = if fn_decl.c_variadic { ", ..." } else { "" };
1303        Wrapped::with_parens()
1304            .wrap_fn(|f| {
1305                print_params(&fn_decl.inputs, cx).fmt(f)?;
1306                f.write_str(ellipsis)
1307            })
1308            .fmt(f)?;
1309        fn_decl.print_output(cx).fmt(f)
1310    })
1311}
1312
1313/// * `header_len`: The length of the function header and name. In other words, the number of
1314///   characters in the function declaration up to but not including the parentheses.
1315///   This is expected to go into a `<pre>`/`code-header` block, so indentation and newlines
1316///   are preserved.
1317/// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1318///   necessary.
1319pub(crate) fn full_print_fn_decl(
1320    fn_decl: &clean::FnDecl,
1321    header_len: usize,
1322    indent: usize,
1323    cx: &Context<'_>,
1324) -> impl Display {
1325    fmt::from_fn(move |f| {
1326        // First, generate the text form of the declaration, with no line wrapping, and count the bytes.
1327        let mut counter = WriteCounter(0);
1328        write!(&mut counter, "{:#}", fmt::from_fn(|f| { fn_decl.inner_full_print(None, f, cx) }))?;
1329        // If the text form was over 80 characters wide, we will line-wrap our output.
1330        let line_wrapping_indent = if header_len + counter.0 > 80 { Some(indent) } else { None };
1331        // Generate the final output. This happens to accept `{:#}` formatting to get textual
1332        // output but in practice it is only formatted with `{}` to get HTML output.
1333        fn_decl.inner_full_print(line_wrapping_indent, f, cx)
1334    })
1335}
1336
1337impl clean::FnDecl {
1338    fn inner_full_print(
1339        &self,
1340        // For None, the declaration will not be line-wrapped. For Some(n),
1341        // the declaration will be line-wrapped, with an indent of n spaces.
1342        line_wrapping_indent: Option<usize>,
1343        f: &mut fmt::Formatter<'_>,
1344        cx: &Context<'_>,
1345    ) -> fmt::Result {
1346        Wrapped::with_parens()
1347            .wrap_fn(|f| {
1348                if !self.inputs.is_empty() {
1349                    let line_wrapping_indent = line_wrapping_indent.map(|n| Indent(n + 4));
1350
1351                    if let Some(indent) = line_wrapping_indent {
1352                        write!(f, "\n{indent}")?;
1353                    }
1354
1355                    let sep = fmt::from_fn(|f| {
1356                        if let Some(indent) = line_wrapping_indent {
1357                            write!(f, ",\n{indent}")
1358                        } else {
1359                            f.write_str(", ")
1360                        }
1361                    });
1362
1363                    self.inputs.iter().map(|param| print_parameter(param, cx)).joined(sep, f)?;
1364
1365                    if line_wrapping_indent.is_some() {
1366                        writeln!(f, ",")?
1367                    }
1368
1369                    if self.c_variadic {
1370                        match line_wrapping_indent {
1371                            None => write!(f, ", ...")?,
1372                            Some(indent) => writeln!(f, "{indent}...")?,
1373                        };
1374                    }
1375                }
1376
1377                if let Some(n) = line_wrapping_indent {
1378                    write!(f, "{}", Indent(n))?
1379                }
1380
1381                Ok(())
1382            })
1383            .fmt(f)?;
1384
1385        self.print_output(cx).fmt(f)
1386    }
1387
1388    fn print_output(&self, cx: &Context<'_>) -> impl Display {
1389        fmt::from_fn(move |f| {
1390            if self.output.is_unit() {
1391                return Ok(());
1392            }
1393
1394            f.write_str(if f.alternate() { " -> " } else { " -&gt; " })?;
1395            print_type(&self.output, cx).fmt(f)
1396        })
1397    }
1398}
1399
1400pub(crate) fn visibility_print_with_space(item: &clean::Item, cx: &Context<'_>) -> impl Display {
1401    fmt::from_fn(move |f| {
1402        let Some(vis) = item.visibility(cx.tcx()) else {
1403            return Ok(());
1404        };
1405
1406        match vis {
1407            ty::Visibility::Public => f.write_str("pub ")?,
1408            ty::Visibility::Restricted(vis_did) => {
1409                // FIXME(camelid): This may not work correctly if `item_did` is a module.
1410                //                 However, rustdoc currently never displays a module's
1411                //                 visibility, so it shouldn't matter.
1412                let parent_module =
1413                    find_nearest_parent_module(cx.tcx(), item.item_id.expect_def_id());
1414
1415                if vis_did.is_crate_root() {
1416                    f.write_str("pub(crate) ")?;
1417                } else if parent_module == Some(vis_did) {
1418                    // `pub(in foo)` where `foo` is the parent module
1419                    // is the same as no visibility modifier; do nothing
1420                } else if parent_module
1421                    .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1422                    == Some(vis_did)
1423                {
1424                    f.write_str("pub(super) ")?;
1425                } else {
1426                    let path = cx.tcx().def_path(vis_did);
1427                    debug!("path={path:?}");
1428                    // modified from `resolved_path()` to work with `DefPathData`
1429                    let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1430                    let anchor = print_anchor(vis_did, last_name, cx);
1431
1432                    f.write_str("pub(in ")?;
1433                    for seg in &path.data[..path.data.len() - 1] {
1434                        write!(f, "{}::", seg.data.get_opt_name().unwrap())?;
1435                    }
1436                    write!(f, "{anchor}) ")?;
1437                }
1438            }
1439        }
1440        Ok(())
1441    })
1442}
1443
1444pub(crate) trait PrintWithSpace {
1445    fn print_with_space(&self) -> &str;
1446}
1447
1448impl PrintWithSpace for hir::Safety {
1449    fn print_with_space(&self) -> &str {
1450        self.prefix_str()
1451    }
1452}
1453
1454impl PrintWithSpace for hir::HeaderSafety {
1455    fn print_with_space(&self) -> &str {
1456        match self {
1457            hir::HeaderSafety::SafeTargetFeatures => "",
1458            hir::HeaderSafety::Normal(safety) => safety.print_with_space(),
1459        }
1460    }
1461}
1462
1463impl PrintWithSpace for hir::IsAsync {
1464    fn print_with_space(&self) -> &str {
1465        match self {
1466            hir::IsAsync::Async(_) => "async ",
1467            hir::IsAsync::NotAsync => "",
1468        }
1469    }
1470}
1471
1472impl PrintWithSpace for hir::Mutability {
1473    fn print_with_space(&self) -> &str {
1474        match self {
1475            hir::Mutability::Not => "",
1476            hir::Mutability::Mut => "mut ",
1477        }
1478    }
1479}
1480
1481pub(crate) fn print_constness_with_space(
1482    c: &hir::Constness,
1483    overall_stab: Option<StableSince>,
1484    const_stab: Option<ConstStability>,
1485) -> &'static str {
1486    match c {
1487        hir::Constness::Const => match (overall_stab, const_stab) {
1488            // const stable...
1489            (_, Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }))
1490            // ...or when feature(staged_api) is not set...
1491            | (_, None)
1492            // ...or when const unstable, but overall unstable too
1493            | (None, Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => {
1494                "const "
1495            }
1496            // const unstable (and overall stable)
1497            (Some(_), Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => "",
1498        },
1499        // not const
1500        hir::Constness::NotConst => "",
1501    }
1502}
1503
1504pub(crate) fn print_import(import: &clean::Import, cx: &Context<'_>) -> impl Display {
1505    fmt::from_fn(move |f| match import.kind {
1506        clean::ImportKind::Simple(name) => {
1507            if name == import.source.path.last() {
1508                write!(f, "use {};", print_import_source(&import.source, cx))
1509            } else {
1510                write!(
1511                    f,
1512                    "use {source} as {name};",
1513                    source = print_import_source(&import.source, cx)
1514                )
1515            }
1516        }
1517        clean::ImportKind::Glob => {
1518            if import.source.path.segments.is_empty() {
1519                write!(f, "use *;")
1520            } else {
1521                write!(f, "use {}::*;", print_import_source(&import.source, cx))
1522            }
1523        }
1524    })
1525}
1526
1527fn print_import_source(import_source: &clean::ImportSource, cx: &Context<'_>) -> impl Display {
1528    fmt::from_fn(move |f| match import_source.did {
1529        Some(did) => resolved_path(f, did, &import_source.path, true, false, cx),
1530        _ => {
1531            for seg in &import_source.path.segments[..import_source.path.segments.len() - 1] {
1532                write!(f, "{}::", seg.name)?;
1533            }
1534            let name = import_source.path.last();
1535            if let hir::def::Res::PrimTy(p) = import_source.path.res {
1536                primitive_link(f, PrimitiveType::from(p), format_args!("{name}"), cx)?;
1537            } else {
1538                f.write_str(name.as_str())?;
1539            }
1540            Ok(())
1541        }
1542    })
1543}
1544
1545fn print_assoc_item_constraint(
1546    assoc_item_constraint: &clean::AssocItemConstraint,
1547    cx: &Context<'_>,
1548) -> impl Display {
1549    fmt::from_fn(move |f| {
1550        f.write_str(assoc_item_constraint.assoc.name.as_str())?;
1551        print_generic_args(&assoc_item_constraint.assoc.args, cx).fmt(f)?;
1552        match assoc_item_constraint.kind {
1553            clean::AssocItemConstraintKind::Equality { ref term } => {
1554                f.write_str(" = ")?;
1555                print_term(term, cx).fmt(f)?;
1556            }
1557            clean::AssocItemConstraintKind::Bound { ref bounds } => {
1558                if !bounds.is_empty() {
1559                    f.write_str(": ")?;
1560                    print_generic_bounds(bounds, cx).fmt(f)?;
1561                }
1562            }
1563        }
1564        Ok(())
1565    })
1566}
1567
1568pub(crate) fn print_abi_with_space(abi: ExternAbi) -> impl Display {
1569    fmt::from_fn(move |f| {
1570        let quot = if f.alternate() { "\"" } else { "&quot;" };
1571        match abi {
1572            ExternAbi::Rust => Ok(()),
1573            abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1574        }
1575    })
1576}
1577
1578fn print_generic_arg(generic_arg: &clean::GenericArg, cx: &Context<'_>) -> impl Display {
1579    fmt::from_fn(move |f| match generic_arg {
1580        clean::GenericArg::Lifetime(lt) => f.write_str(print_lifetime(lt)),
1581        clean::GenericArg::Type(ty) => print_type(ty, cx).fmt(f),
1582        clean::GenericArg::Const(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1583        clean::GenericArg::Infer => f.write_char('_'),
1584    })
1585}
1586
1587fn print_term(term: &clean::Term, cx: &Context<'_>) -> impl Display {
1588    fmt::from_fn(move |f| match term {
1589        clean::Term::Type(ty) => print_type(ty, cx).fmt(f),
1590        clean::Term::Constant(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1591    })
1592}