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