1use std::cmp::Ordering;
10use std::fmt::{self, Display, Write};
11use std::{iter, slice};
12
13use itertools::{Either, Itertools};
14use rustc_abi::ExternAbi;
15use rustc_ast::join_path_syms;
16use rustc_data_structures::fx::FxHashSet;
17use rustc_hir as hir;
18use rustc_hir::def::{DefKind, MacroKinds};
19use rustc_hir::def_id::{DefId, LOCAL_CRATE};
20use rustc_hir::{ConstStability, StabilityLevel, StableSince};
21use rustc_metadata::creader::CStore;
22use rustc_middle::ty::{self, TyCtxt, TypingMode};
23use rustc_span::symbol::kw;
24use rustc_span::{Ident, Symbol};
25use tracing::{debug, trace};
26
27use super::url_parts_builder::UrlPartsBuilder;
28use crate::clean::types::ExternalLocation;
29use crate::clean::utils::find_nearest_parent_module;
30use crate::clean::{self, ExternalCrate, PrimitiveType, WherePredicate};
31use crate::display::{Joined as _, MaybeDisplay as _, WithOpts, Wrapped};
32use crate::formats::cache::Cache;
33use crate::formats::item_type::ItemType;
34use crate::html::escape::{Escape, EscapeBodyText};
35use crate::html::render::Context;
36use crate::passes::collect_intra_doc_links::UrlFragment;
37
38pub(crate) fn print_generic_bounds(
39 bounds: &[clean::GenericBound],
40 cx: &Context<'_>,
41) -> impl Display {
42 fmt::from_fn(move |f| {
43 let mut bounds_dup = FxHashSet::default();
44
45 bounds
46 .iter()
47 .filter(move |b| bounds_dup.insert(*b))
48 .map(|bound| print_generic_bound(bound, cx))
49 .joined(" + ", f)
50 })
51}
52
53pub(crate) fn print_generic_param_def(
54 generic_param: &clean::GenericParamDef,
55 cx: &Context<'_>,
56) -> impl Display {
57 fmt::from_fn(move |f| match &generic_param.kind {
58 clean::GenericParamDefKind::Lifetime { outlives } => {
59 write!(f, "{}", generic_param.name)?;
60
61 if !outlives.is_empty() {
62 f.write_str(": ")?;
63 outlives.iter().map(|lt| print_lifetime(lt)).joined(" + ", f)?;
64 }
65
66 Ok(())
67 }
68 clean::GenericParamDefKind::Type { bounds, default, .. } => {
69 f.write_str(generic_param.name.as_str())?;
70
71 if !bounds.is_empty() {
72 f.write_str(": ")?;
73 print_generic_bounds(bounds, cx).fmt(f)?;
74 }
75
76 if let Some(ty) = default {
77 f.write_str(" = ")?;
78 print_type(ty, cx).fmt(f)?;
79 }
80
81 Ok(())
82 }
83 clean::GenericParamDefKind::Const { ty, default, .. } => {
84 write!(f, "const {}: ", generic_param.name)?;
85 print_type(ty, cx).fmt(f)?;
86
87 if let Some(default) = default {
88 f.write_str(" = ")?;
89 if f.alternate() {
90 write!(f, "{default}")?;
91 } else {
92 write!(f, "{}", Escape(default))?;
93 }
94 }
95
96 Ok(())
97 }
98 })
99}
100
101pub(crate) fn print_generics(generics: &clean::Generics, cx: &Context<'_>) -> impl Display {
102 let mut real_params = generics.params.iter().filter(|p| !p.is_synthetic_param()).peekable();
103 if real_params.peek().is_none() {
104 None
105 } else {
106 Some(Wrapped::with_angle_brackets().wrap_fn(move |f| {
107 real_params.clone().map(|g| print_generic_param_def(g, cx)).joined(", ", f)
108 }))
109 }
110 .maybe_display()
111}
112
113#[derive(Clone, Copy, PartialEq, Eq)]
114pub(crate) enum Ending {
115 Newline,
116 NoNewline,
117}
118
119fn print_where_predicate(predicate: &clean::WherePredicate, cx: &Context<'_>) -> impl Display {
120 fmt::from_fn(move |f| {
121 match predicate {
122 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
123 print_higher_ranked_params_with_space(bound_params, cx, "for").fmt(f)?;
124 print_type(ty, cx).fmt(f)?;
125 f.write_str(":")?;
126 if !bounds.is_empty() {
127 f.write_str(" ")?;
128 print_generic_bounds(bounds, cx).fmt(f)?;
129 }
130 Ok(())
131 }
132 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
133 write!(f, "{}:", print_lifetime(lifetime))?;
136 if !bounds.is_empty() {
137 write!(f, " {}", print_generic_bounds(bounds, cx))?;
138 }
139 Ok(())
140 }
141 clean::WherePredicate::ProjectionPredicate { lhs, rhs } => {
142 let opts = WithOpts::from(f);
143 write!(
144 f,
145 "{} == {}",
146 opts.display(print_qpath_data(lhs, cx)),
147 opts.display(print_term(rhs, cx)),
148 )
149 }
150 }
151 })
152}
153
154pub(crate) fn print_where_clause(
158 gens: &clean::Generics,
159 cx: &Context<'_>,
160 indent: usize,
161 ending: Ending,
162) -> Option<impl Display> {
163 if gens.where_predicates.is_empty() {
164 return None;
165 }
166
167 fn where_preds(
168 predicates: &[WherePredicate],
169 cx: &Context<'_>,
170 sep: impl Display,
171 ) -> impl Display {
172 fmt::from_fn(move |f| {
173 predicates.iter().map(|predicate| print_where_predicate(predicate, cx)).joined(&sep, f)
174 })
175 }
176
177 let spaces = |n: usize| crate::display::repeat(' ', n);
178
179 Some(fmt::from_fn(move |f| {
180 if f.alternate() {
181 write!(f, " where {:#}", where_preds(&gens.where_predicates, cx, ", "))?;
182 if ending == Ending::Newline {
183 f.write_char(',')?;
184 }
185 return Ok(());
186 }
187
188 const WHERE_INDENT: usize = 3;
189
190 let padding = {
191 let padding_amount = if ending == Ending::Newline {
192 indent + 4
193 } else if indent == 0 {
194 4
195 } else {
196 indent + WHERE_INDENT + "where ".len()
197 };
198 spaces(padding_amount)
199 };
200
201 let br_with_padding = format_args!("\n{padding}");
202 let sep = format_args!(",{br_with_padding}");
203 let where_preds = where_preds(&gens.where_predicates, cx, sep);
204
205 if ending == Ending::Newline {
206 write!(
207 f,
208 "{indent}<div class=\"where\">where{br_with_padding}{where_preds},</div>",
209 indent = spaces(indent.saturating_sub(1)),
210 )
211 } else if indent == 0 {
212 write!(f, "\n<span class=\"where\">where{br_with_padding}{where_preds}</span>")
213 } else {
214 write!(
215 f,
216 "\n{indent}<span class=\"where\">where {where_preds}</span>",
217 indent = spaces(indent + WHERE_INDENT),
218 )
219 }
220 }))
221}
222
223#[inline]
224pub(crate) fn print_lifetime(lt: &clean::Lifetime) -> &str {
225 lt.0.as_str()
226}
227
228pub(crate) fn print_constant_kind(
229 constant_kind: &clean::ConstantKind,
230 tcx: TyCtxt<'_>,
231) -> impl Display {
232 let expr = constant_kind.expr(tcx);
233 fmt::from_fn(
234 move |f| {
235 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
236 },
237 )
238}
239
240fn print_poly_trait(poly_trait: &clean::PolyTrait, cx: &Context<'_>) -> impl Display {
241 fmt::from_fn(move |f| {
242 print_higher_ranked_params_with_space(&poly_trait.generic_params, cx, "for").fmt(f)?;
243 print_path(&poly_trait.trait_, cx).fmt(f)
244 })
245}
246
247pub(crate) fn print_generic_bound(
248 generic_bound: &clean::GenericBound,
249 cx: &Context<'_>,
250) -> impl Display {
251 fmt::from_fn(move |f| match generic_bound {
252 clean::GenericBound::Outlives(lt) => f.write_str(print_lifetime(lt)),
253 clean::GenericBound::TraitBound(ty, modifiers) => {
254 let hir::TraitBoundModifiers { polarity, constness: _ } = modifiers;
256 f.write_str(match polarity {
257 hir::BoundPolarity::Positive => "",
258 hir::BoundPolarity::Maybe(_) => "?",
259 hir::BoundPolarity::Negative(_) => "!",
260 })?;
261 print_poly_trait(ty, cx).fmt(f)
262 }
263 clean::GenericBound::Use(args) => {
264 f.write_str("use")?;
265 Wrapped::with_angle_brackets()
266 .wrap_fn(|f| args.iter().map(|arg| arg.name()).joined(", ", f))
267 .fmt(f)
268 }
269 })
270}
271
272fn print_generic_args(generic_args: &clean::GenericArgs, cx: &Context<'_>) -> impl Display {
273 fmt::from_fn(move |f| {
274 match generic_args {
275 clean::GenericArgs::AngleBracketed { args, constraints } => {
276 if !args.is_empty() || !constraints.is_empty() {
277 Wrapped::with_angle_brackets()
278 .wrap_fn(|f| {
279 [Either::Left(args), Either::Right(constraints)]
280 .into_iter()
281 .flat_map(Either::factor_into_iter)
282 .map(|either| {
283 either.map_either(
284 |arg| print_generic_arg(arg, cx),
285 |constraint| print_assoc_item_constraint(constraint, cx),
286 )
287 })
288 .joined(", ", f)
289 })
290 .fmt(f)?;
291 }
292 }
293 clean::GenericArgs::Parenthesized { inputs, output } => {
294 Wrapped::with_parens()
295 .wrap_fn(|f| inputs.iter().map(|ty| print_type(ty, cx)).joined(", ", f))
296 .fmt(f)?;
297 if let Some(ref ty) = *output {
298 f.write_str(if f.alternate() { " -> " } else { " -> " })?;
299 print_type(ty, cx).fmt(f)?;
300 }
301 }
302 clean::GenericArgs::ReturnTypeNotation => {
303 f.write_str("(..)")?;
304 }
305 }
306 Ok(())
307 })
308}
309
310#[derive(PartialEq, Eq)]
312pub(crate) enum HrefError {
313 DocumentationNotBuilt,
332 Private,
334 NotInExternalCache,
336 UnnamableItem,
338}
339
340pub(crate) struct HrefInfo {
342 pub(crate) url: String,
344 pub(crate) kind: ItemType,
346 pub(crate) rust_path: Vec<Symbol>,
348}
349
350fn generate_macro_def_id_path(
353 def_id: DefId,
354 cx: &Context<'_>,
355 root_path: Option<&str>,
356) -> Result<HrefInfo, HrefError> {
357 let tcx = cx.tcx();
358 let crate_name = tcx.crate_name(def_id.krate);
359 let cache = cx.cache();
360
361 let cstore = CStore::from_tcx(tcx);
362 if !cstore.has_crate_data(def_id.krate) {
364 debug!("No data for crate {crate_name}");
365 return Err(HrefError::NotInExternalCache);
366 }
367 let DefKind::Macro(kinds) = tcx.def_kind(def_id) else {
368 unreachable!();
369 };
370 let item_type = if kinds == MacroKinds::DERIVE {
371 ItemType::ProcDerive
372 } else if kinds == MacroKinds::ATTR {
373 ItemType::ProcAttribute
374 } else {
375 ItemType::Macro
376 };
377 let path = clean::inline::get_item_path(tcx, def_id, item_type);
378 let [module_path @ .., last] = path.as_slice() else {
381 debug!("macro path is empty!");
382 return Err(HrefError::NotInExternalCache);
383 };
384 if module_path.is_empty() {
385 debug!("macro path too short: missing crate prefix (got 1 element, need at least 2)");
386 return Err(HrefError::NotInExternalCache);
387 }
388
389 let url = match cache.extern_locations[&def_id.krate] {
390 ExternalLocation::Remote { ref url, is_absolute } => {
391 let mut prefix = remote_url_prefix(url, is_absolute, cx.current.len());
392 prefix.extend(module_path.iter().copied());
393 prefix.push_fmt(format_args!("{}.{last}.html", item_type.as_str()));
394 prefix.finish()
395 }
396 ExternalLocation::Local => {
397 format!(
399 "{root_path}{path}/{item_type}.{last}.html",
400 root_path = root_path.unwrap_or(""),
401 path = fmt::from_fn(|f| module_path.iter().joined("/", f)),
402 item_type = item_type.as_str(),
403 )
404 }
405 ExternalLocation::Unknown => {
406 debug!("crate {crate_name} not in cache when linkifying macros");
407 return Err(HrefError::NotInExternalCache);
408 }
409 };
410 Ok(HrefInfo { url, kind: item_type, rust_path: path })
411}
412
413fn generate_item_def_id_path(
414 mut def_id: DefId,
415 original_def_id: DefId,
416 cx: &Context<'_>,
417 root_path: Option<&str>,
418) -> Result<HrefInfo, HrefError> {
419 use rustc_middle::traits::ObligationCause;
420 use rustc_trait_selection::infer::TyCtxtInferExt;
421 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
422
423 let tcx = cx.tcx();
424 let crate_name = tcx.crate_name(def_id.krate);
425 let mut prim = None;
426
427 if def_id != original_def_id && matches!(tcx.def_kind(def_id), DefKind::Impl { .. }) {
430 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
431 let ty = tcx.type_of(def_id);
432 let ty = infcx
433 .at(&ObligationCause::dummy(), tcx.param_env(def_id))
434 .query_normalize(ty::Binder::dummy(ty.instantiate_identity().skip_norm_wip()))
435 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value).skip_binder())
436 .unwrap_or(ty.skip_binder());
437 if let Some(new_def_id) = ty.ty_adt_def().map(|adt| adt.did()) {
438 def_id = new_def_id;
439 } else {
440 prim = PrimitiveType::from_ty(ty);
441 }
442 }
443
444 let mut fqp = vec![crate_name];
445 let shortty = if let Some(prim) = prim {
446 fqp.push(prim.as_sym());
447 ItemType::Primitive
448 } else {
449 fqp.append(&mut clean::inline::item_relative_path(tcx, def_id));
450 ItemType::from_def_id(def_id, tcx)
451 };
452 let module_fqp = to_module_fqp(shortty, &fqp);
453
454 let (parts, is_absolute) = url_parts(cx.cache(), def_id, module_fqp, &cx.current)?;
455 let mut url = make_href(root_path, shortty, parts, &fqp, is_absolute);
456
457 if def_id != original_def_id {
458 let kind = ItemType::from_def_id(original_def_id, tcx);
459 url = format!("{url}#{kind}.{}", tcx.item_name(original_def_id))
460 };
461 Ok(HrefInfo { url, kind: shortty, rust_path: fqp })
462}
463
464fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool {
466 let mut cur_did = did;
467 while let Some(parent) = tcx.opt_parent(cur_did) {
468 match tcx.def_kind(parent) {
469 DefKind::Mod | DefKind::ForeignMod => cur_did = parent,
471 DefKind::Impl { .. } => return false,
477 _ => return true,
479 }
480 }
481 return false;
482}
483
484fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
485 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
486}
487
488fn remote_url_prefix(url: &str, is_absolute: bool, depth: usize) -> UrlPartsBuilder {
489 let url = url.trim_end_matches('/');
490 if is_absolute {
491 UrlPartsBuilder::singleton(url)
492 } else {
493 let extra = depth.saturating_sub(1);
494 let mut b: UrlPartsBuilder = iter::repeat_n("..", extra).collect();
495 b.push(url);
496 b
497 }
498}
499
500fn url_parts(
501 cache: &Cache,
502 def_id: DefId,
503 module_fqp: &[Symbol],
504 relative_to: &[Symbol],
505) -> Result<(UrlPartsBuilder, bool), HrefError> {
506 match cache.extern_locations[&def_id.krate] {
507 ExternalLocation::Remote { ref url, is_absolute } => {
508 let mut builder = remote_url_prefix(url, is_absolute, relative_to.len());
509 builder.extend(module_fqp.iter().copied());
510 Ok((builder, is_absolute))
511 }
512 ExternalLocation::Local => Ok((href_relative_parts(module_fqp, relative_to), false)),
513 ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt),
514 }
515}
516
517fn make_href(
518 root_path: Option<&str>,
519 shortty: ItemType,
520 mut url_parts: UrlPartsBuilder,
521 fqp: &[Symbol],
522 is_absolute: bool,
523) -> String {
524 if !is_absolute && let Some(root_path) = root_path {
526 let root = root_path.trim_end_matches('/');
527 url_parts.push_front(root);
528 }
529 debug!(?url_parts);
530 match shortty {
531 ItemType::Module => {
532 url_parts.push("index.html");
533 }
534 _ => {
535 let last = fqp.last().unwrap();
536 url_parts.push_fmt(format_args!("{shortty}.{last}.html"));
537 }
538 }
539 url_parts.finish()
540}
541
542pub(crate) fn href_with_root_path(
543 original_did: DefId,
544 cx: &Context<'_>,
545 root_path: Option<&str>,
546) -> Result<HrefInfo, HrefError> {
547 let tcx = cx.tcx();
548 let def_kind = tcx.def_kind(original_did);
549 let did = match def_kind {
550 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::Variant => {
551 tcx.parent(original_did)
553 }
554 DefKind::Ctor(..) => return href_with_root_path(tcx.parent(original_did), cx, root_path),
557 DefKind::ExternCrate => {
558 if let Some(local_did) = original_did.as_local() {
560 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
561 } else {
562 original_did
563 }
564 }
565 _ => original_did,
566 };
567 if is_unnamable(cx.tcx(), did) {
568 return Err(HrefError::UnnamableItem);
569 }
570 let cache = cx.cache();
571 let relative_to = &cx.current;
572
573 if !original_did.is_local() {
574 if root_path.is_some() {
577 if tcx.is_doc_hidden(original_did) {
578 return Err(HrefError::Private);
579 }
580 } else if !cache.effective_visibilities.is_directly_public(tcx, did)
581 && !cache.document_private
582 && !cache.primitive_locations.values().any(|&id| id == did)
583 {
584 return Err(HrefError::Private);
585 }
586 }
587
588 let (fqp, shortty, url_parts, is_absolute) = match cache.paths.get(&did) {
589 Some(&(ref fqp, shortty)) => (
590 fqp,
591 shortty,
592 {
593 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
594 debug!(?fqp, ?shortty, ?module_fqp);
595 href_relative_parts(module_fqp, relative_to)
596 },
597 false,
598 ),
599 None => {
600 let def_id_to_get = if root_path.is_some() { original_did } else { did };
604 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&def_id_to_get) {
605 let module_fqp = to_module_fqp(shortty, fqp);
606 let (parts, is_absolute) = url_parts(cache, did, module_fqp, relative_to)?;
607 (fqp, shortty, parts, is_absolute)
608 } else if matches!(def_kind, DefKind::Macro(_)) {
609 return generate_macro_def_id_path(did, cx, root_path);
610 } else if did.is_local() {
611 return Err(HrefError::Private);
612 } else {
613 return generate_item_def_id_path(did, original_did, cx, root_path);
614 }
615 }
616 };
617 Ok(HrefInfo {
618 url: make_href(root_path, shortty, url_parts, fqp, is_absolute),
619 kind: shortty,
620 rust_path: fqp.clone(),
621 })
622}
623
624pub(crate) fn href(did: DefId, cx: &Context<'_>) -> Result<HrefInfo, HrefError> {
625 href_with_root_path(did, cx, None)
626}
627
628pub(crate) fn href_relative_parts(fqp: &[Symbol], relative_to_fqp: &[Symbol]) -> UrlPartsBuilder {
632 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
633 if f != r {
635 let dissimilar_part_count = relative_to_fqp.len() - i;
636 let fqp_module = &fqp[i..];
637 return iter::repeat_n("..", dissimilar_part_count)
638 .chain(fqp_module.iter().map(|s| s.as_str()))
639 .collect();
640 }
641 }
642 match relative_to_fqp.len().cmp(&fqp.len()) {
643 Ordering::Less => {
644 fqp[relative_to_fqp.len()..fqp.len()].iter().copied().collect()
646 }
647 Ordering::Greater => {
648 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
650 iter::repeat_n("..", dissimilar_part_count).collect()
651 }
652 Ordering::Equal => {
653 UrlPartsBuilder::new()
655 }
656 }
657}
658
659pub(crate) fn link_tooltip(
660 did: DefId,
661 fragment: &Option<UrlFragment>,
662 cx: &Context<'_>,
663) -> impl fmt::Display {
664 fmt::from_fn(move |f| {
665 let cache = cx.cache();
666 let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did))
667 else {
668 return Ok(());
669 };
670 let fqp = if *shortty == ItemType::Primitive {
671 slice::from_ref(fqp.last().unwrap())
673 } else {
674 fqp
675 };
676 if let &Some(UrlFragment::Item(id)) = fragment {
677 let tcx = cx.tcx();
678 write!(f, "{} ", tcx.def_descr(id))?;
679 for component in fqp {
680 write!(f, "{component}::")?;
681 }
682 if *shortty == ItemType::Enum && tcx.def_kind(id) == DefKind::Field {
683 write!(f, "{}::", tcx.item_name(tcx.parent(id)))?;
684 }
685 write!(f, "{}", 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
694fn 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 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 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(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::Type::FieldOf(t, field) => {
971 write!(f, "field_of!(")?;
972 fmt::Display::fmt(&print_type(t, cx), f)?;
973 write!(f, ", {field})")
974 }
975 clean::Array(clean::Generic(name), n) if !f.alternate() => primitive_link(
976 f,
977 PrimitiveType::Array,
978 format_args!("[{name}; {n}]", n = Escape(n)),
979 cx,
980 ),
981 clean::Array(t, n) => Wrapped::with_square_brackets()
982 .wrap(fmt::from_fn(|f| {
983 print_type(t, cx).fmt(f)?;
984 f.write_str("; ")?;
985 if f.alternate() {
986 f.write_str(n)
987 } else {
988 primitive_link(f, PrimitiveType::Array, format_args!("{n}", n = Escape(n)), cx)
989 }
990 }))
991 .fmt(f),
992 clean::RawPointer(m, t) => {
993 let m = m.ptr_str();
994
995 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
996 primitive_link(
997 f,
998 clean::PrimitiveType::RawPointer,
999 format_args!("*{m} {ty}", ty = WithOpts::from(f).display(print_type(t, cx))),
1000 cx,
1001 )
1002 } else {
1003 primitive_link(f, clean::PrimitiveType::RawPointer, format_args!("*{m} "), cx)?;
1004 print_type(t, cx).fmt(f)
1005 }
1006 }
1007 clean::BorrowedRef { lifetime: l, mutability, type_: ty } => {
1008 let lt = fmt::from_fn(|f| match l {
1009 Some(l) => write!(f, "{} ", print_lifetime(l)),
1010 _ => Ok(()),
1011 });
1012 let m = mutability.print_with_space();
1013 let amp = if f.alternate() { "&" } else { "&" };
1014
1015 if let clean::Generic(name) = **ty {
1016 return primitive_link(
1017 f,
1018 PrimitiveType::Reference,
1019 format_args!("{amp}{lt}{m}{name}"),
1020 cx,
1021 );
1022 }
1023
1024 write!(f, "{amp}{lt}{m}")?;
1025
1026 let needs_parens = match **ty {
1027 clean::DynTrait(ref bounds, ref trait_lt)
1028 if bounds.len() > 1 || trait_lt.is_some() =>
1029 {
1030 true
1031 }
1032 clean::ImplTrait(ref bounds) if bounds.len() > 1 => true,
1033 _ => false,
1034 };
1035 Wrapped::with_parens()
1036 .when(needs_parens)
1037 .wrap_fn(|f| fmt_type(ty, f, use_absolute, cx))
1038 .fmt(f)
1039 }
1040 clean::ImplTrait(bounds) => {
1041 f.write_str("impl ")?;
1042 print_generic_bounds(bounds, cx).fmt(f)
1043 }
1044 clean::QPath(qpath) => print_qpath_data(qpath, cx).fmt(f),
1045 }
1046}
1047
1048pub(crate) fn print_type(type_: &clean::Type, cx: &Context<'_>) -> impl Display {
1049 fmt::from_fn(move |f| fmt_type(type_, f, false, cx))
1050}
1051
1052pub(crate) fn print_path(path: &clean::Path, cx: &Context<'_>) -> impl Display {
1053 fmt::from_fn(move |f| resolved_path(f, path.def_id(), path, false, false, cx))
1054}
1055
1056fn print_qpath_data(qpath_data: &clean::QPathData, cx: &Context<'_>) -> impl Display {
1057 let clean::QPathData { ref assoc, ref self_type, should_fully_qualify, ref trait_ } =
1058 *qpath_data;
1059
1060 fmt::from_fn(move |f| {
1061 if let Some(trait_) = trait_
1065 && should_fully_qualify
1066 {
1067 let opts = WithOpts::from(f);
1068 Wrapped::with_angle_brackets()
1069 .wrap(format_args!(
1070 "{} as {}",
1071 opts.display(print_type(self_type, cx)),
1072 opts.display(print_path(trait_, cx))
1073 ))
1074 .fmt(f)?
1075 } else {
1076 print_type(self_type, cx).fmt(f)?;
1077 }
1078 f.write_str("::")?;
1079 if !f.alternate() {
1090 let parent_href = match trait_ {
1103 Some(trait_) => href(trait_.def_id(), cx).ok(),
1104 None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()),
1105 };
1106 let tcx = cx.tcx();
1107 let assoc_type_is_hidden = !cx.cache().document_hidden
1108 && trait_.as_ref().is_some_and(|trait_| {
1109 let trait_did = trait_.def_id();
1110 tcx.associated_items(trait_did)
1111 .find_by_ident_and_kind(
1112 tcx,
1113 Ident::with_dummy_span(assoc.name),
1114 ty::AssocTag::Type,
1115 trait_did,
1116 )
1117 .is_some_and(|assoc_item| tcx.is_doc_hidden(assoc_item.def_id))
1118 });
1119
1120 if let Some(HrefInfo { url, rust_path, .. }) = parent_href
1121 && !assoc_type_is_hidden
1122 {
1123 write!(
1124 f,
1125 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1126 title=\"type {path}::{name}\">{name}</a>",
1127 shortty = ItemType::AssocType,
1128 name = assoc.name,
1129 path = join_path_syms(rust_path),
1130 )
1131 } else {
1132 write!(f, "{}", assoc.name)
1133 }
1134 } else {
1135 write!(f, "{}", assoc.name)
1136 }?;
1137
1138 print_generic_args(&assoc.args, cx).fmt(f)
1139 })
1140}
1141
1142pub(crate) fn print_impl(
1143 impl_: &clean::Impl,
1144 use_absolute: bool,
1145 cx: &Context<'_>,
1146) -> impl Display {
1147 fmt::from_fn(move |f| {
1148 f.write_str("impl")?;
1149 print_generics(&impl_.generics, cx).fmt(f)?;
1150 f.write_str(" ")?;
1151
1152 if let Some(ref ty) = impl_.trait_ {
1153 if impl_.is_negative_trait_impl() {
1154 f.write_char('!')?;
1155 }
1156 if impl_.kind.is_fake_variadic()
1157 && let Some(generics) = ty.generics()
1158 && let Ok(inner_type) = generics.exactly_one()
1159 {
1160 let last = ty.last();
1161 if f.alternate() {
1162 write!(f, "{last}")?;
1163 } else {
1164 write!(f, "{}", print_anchor(ty.def_id(), last, cx))?;
1165 };
1166 Wrapped::with_angle_brackets()
1167 .wrap_fn(|f| impl_.print_type(inner_type, f, use_absolute, cx))
1168 .fmt(f)?;
1169 } else {
1170 print_path(ty, cx).fmt(f)?;
1171 }
1172 f.write_str(" for ")?;
1173 }
1174
1175 if let Some(ty) = impl_.kind.as_blanket_ty() {
1176 fmt_type(ty, f, use_absolute, cx)?;
1177 } else {
1178 impl_.print_type(&impl_.for_, f, use_absolute, cx)?;
1179 }
1180
1181 print_where_clause(&impl_.generics, cx, 0, Ending::Newline).maybe_display().fmt(f)
1182 })
1183}
1184
1185impl clean::Impl {
1186 fn print_type(
1187 &self,
1188 type_: &clean::Type,
1189 f: &mut fmt::Formatter<'_>,
1190 use_absolute: bool,
1191 cx: &Context<'_>,
1192 ) -> Result<(), fmt::Error> {
1193 if let clean::Type::Tuple(types) = type_
1194 && let [clean::Type::Generic(name)] = &types[..]
1195 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1196 {
1197 primitive_link_fragment(
1200 f,
1201 PrimitiveType::Tuple,
1202 format_args!("({name}₁, {name}₂, …, {name}ₙ)"),
1203 "#trait-implementations-1",
1204 cx,
1205 )?;
1206 } else if let clean::Type::Array(ty, len) = type_
1207 && let clean::Type::Generic(name) = &**ty
1208 && &len[..] == "1"
1209 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1210 {
1211 primitive_link(f, PrimitiveType::Array, format_args!("[{name}; N]"), cx)?;
1212 } else if let clean::BareFunction(bare_fn) = &type_
1213 && let [clean::Parameter { type_: clean::Type::Generic(name), .. }] =
1214 &bare_fn.decl.inputs[..]
1215 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1216 {
1217 print_higher_ranked_params_with_space(&bare_fn.generic_params, cx, "for").fmt(f)?;
1221 bare_fn.safety.print_with_space().fmt(f)?;
1222 print_abi_with_space(bare_fn.abi).fmt(f)?;
1223 let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" };
1224 primitive_link_fragment(
1225 f,
1226 PrimitiveType::Tuple,
1227 format_args!("fn({name}₁, {name}₂, …, {name}ₙ{ellipsis})"),
1228 "#trait-implementations-1",
1229 cx,
1230 )?;
1231 if !bare_fn.decl.output.is_unit() {
1233 write!(f, " -> ")?;
1234 fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?;
1235 }
1236 } else if let clean::Type::Path { path } = type_
1237 && let Some(generics) = path.generics()
1238 && let Ok(ty) = generics.exactly_one()
1239 && self.kind.is_fake_variadic()
1240 {
1241 print_anchor(path.def_id(), path.last(), cx).fmt(f)?;
1242 Wrapped::with_angle_brackets()
1243 .wrap_fn(|f| self.print_type(ty, f, use_absolute, cx))
1244 .fmt(f)?;
1245 } else {
1246 fmt_type(type_, f, use_absolute, cx)?;
1247 }
1248 Ok(())
1249 }
1250}
1251
1252pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> impl Display {
1253 fmt::from_fn(move |f| {
1254 params
1255 .iter()
1256 .map(|param| {
1257 fmt::from_fn(|f| {
1258 if param.is_splat {
1259 write!(f, "…: ")?;
1260 } else if let Some(name) = param.name {
1261 write!(f, "{name}: ")?;
1262 }
1263 print_type(¶m.type_, cx).fmt(f)
1264 })
1265 })
1266 .joined(", ", f)
1267 })
1268}
1269
1270struct WriteCounter(usize);
1272
1273impl std::fmt::Write for WriteCounter {
1274 fn write_str(&mut self, s: &str) -> fmt::Result {
1275 self.0 += s.len();
1276 Ok(())
1277 }
1278}
1279
1280#[derive(Clone, Copy)]
1282struct Indent(usize);
1283
1284impl Display for Indent {
1285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1286 for _ in 0..self.0 {
1287 f.write_char(' ')?;
1288 }
1289 Ok(())
1290 }
1291}
1292
1293fn print_parameter(parameter: &clean::Parameter, cx: &Context<'_>) -> impl fmt::Display {
1294 fmt::from_fn(move |f| {
1295 if let Some(self_ty) = parameter.to_receiver() {
1296 match self_ty {
1297 clean::SelfTy => f.write_str("self"),
1298 clean::BorrowedRef { lifetime, mutability, type_: clean::SelfTy } => {
1299 f.write_str(if f.alternate() { "&" } else { "&" })?;
1300 if let Some(lt) = lifetime {
1301 write!(f, "{lt} ", lt = print_lifetime(lt))?;
1302 }
1303 write!(f, "{mutability}self", mutability = mutability.print_with_space())
1304 }
1305 _ => {
1306 f.write_str("self: ")?;
1307 print_type(self_ty, cx).fmt(f)
1308 }
1309 }
1310 } else {
1311 if parameter.is_const {
1312 write!(f, "const ")?;
1313 }
1314 if parameter.is_splat {
1315 write!(f, "…: ")?;
1316 } else if let Some(name) = parameter.name {
1317 write!(f, "{name}: ")?;
1318 }
1319 print_type(¶meter.type_, cx).fmt(f)
1320 }
1321 })
1322}
1323
1324fn print_fn_decl(fn_decl: &clean::FnDecl, cx: &Context<'_>) -> impl Display {
1325 fmt::from_fn(move |f| {
1326 let ellipsis = if fn_decl.c_variadic { ", ..." } else { "" };
1327 Wrapped::with_parens()
1328 .wrap_fn(|f| {
1329 print_params(&fn_decl.inputs, cx).fmt(f)?;
1330 f.write_str(ellipsis)
1331 })
1332 .fmt(f)?;
1333 fn_decl.print_output(cx).fmt(f)
1334 })
1335}
1336
1337pub(crate) fn full_print_fn_decl(
1344 fn_decl: &clean::FnDecl,
1345 header_len: usize,
1346 indent: usize,
1347 cx: &Context<'_>,
1348) -> impl Display {
1349 fmt::from_fn(move |f| {
1350 let mut counter = WriteCounter(0);
1352 write!(&mut counter, "{:#}", fmt::from_fn(|f| { fn_decl.inner_full_print(None, f, cx) }))?;
1353 let line_wrapping_indent = if header_len + counter.0 > 80 { Some(indent) } else { None };
1355 fn_decl.inner_full_print(line_wrapping_indent, f, cx)
1358 })
1359}
1360
1361impl clean::FnDecl {
1362 fn inner_full_print(
1363 &self,
1364 line_wrapping_indent: Option<usize>,
1367 f: &mut fmt::Formatter<'_>,
1368 cx: &Context<'_>,
1369 ) -> fmt::Result {
1370 Wrapped::with_parens()
1371 .wrap_fn(|f| {
1372 if !self.inputs.is_empty() {
1373 let line_wrapping_indent = line_wrapping_indent.map(|n| Indent(n + 4));
1374
1375 if let Some(indent) = line_wrapping_indent {
1376 write!(f, "\n{indent}")?;
1377 }
1378
1379 let sep = fmt::from_fn(|f| {
1380 if let Some(indent) = line_wrapping_indent {
1381 write!(f, ",\n{indent}")
1382 } else {
1383 f.write_str(", ")
1384 }
1385 });
1386
1387 self.inputs.iter().map(|param| print_parameter(param, cx)).joined(sep, f)?;
1388
1389 if line_wrapping_indent.is_some() {
1390 writeln!(f, ",")?
1391 }
1392
1393 if self.c_variadic {
1394 match line_wrapping_indent {
1395 None => write!(f, ", ...")?,
1396 Some(indent) => writeln!(f, "{indent}...")?,
1397 };
1398 }
1399 }
1400
1401 if let Some(n) = line_wrapping_indent {
1402 write!(f, "{}", Indent(n))?
1403 }
1404
1405 Ok(())
1406 })
1407 .fmt(f)?;
1408
1409 self.print_output(cx).fmt(f)
1410 }
1411
1412 fn print_output(&self, cx: &Context<'_>) -> impl Display {
1413 fmt::from_fn(move |f| {
1414 if self.output.is_unit() {
1415 return Ok(());
1416 }
1417
1418 f.write_str(if f.alternate() { " -> " } else { " -> " })?;
1419 print_type(&self.output, cx).fmt(f)
1420 })
1421 }
1422}
1423
1424pub(crate) fn visibility_print_with_space(item: &clean::Item, cx: &Context<'_>) -> impl Display {
1425 fmt::from_fn(move |f| {
1426 let Some(vis) = item.visibility(cx.tcx()) else {
1427 return Ok(());
1428 };
1429
1430 match vis {
1431 ty::Visibility::Public => f.write_str("pub ")?,
1432 ty::Visibility::Restricted(vis_mod_id) => {
1433 let parent_module =
1437 find_nearest_parent_module(cx.tcx(), item.item_id.expect_def_id());
1438
1439 if vis_mod_id.is_crate_root() {
1440 f.write_str("pub(crate) ")?;
1441 } else if parent_module == Some(vis_mod_id) {
1442 } else if parent_module
1445 .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent.to_def_id()))
1446 == Some(vis_mod_id)
1447 {
1448 f.write_str("pub(super) ")?;
1449 } else {
1450 let path = cx.tcx().def_path(vis_mod_id.to_def_id());
1451 debug!("path={path:?}");
1452 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1454 let anchor = print_anchor(vis_mod_id.to_def_id(), last_name, cx);
1455
1456 f.write_str("pub(in ")?;
1457 for seg in &path.data[..path.data.len() - 1] {
1458 write!(f, "{}::", seg.data.get_opt_name().unwrap())?;
1459 }
1460 write!(f, "{anchor}) ")?;
1461 }
1462 }
1463 }
1464 Ok(())
1465 })
1466}
1467
1468pub(crate) trait PrintWithSpace {
1469 fn print_with_space(&self) -> &str;
1470}
1471
1472impl PrintWithSpace for hir::Safety {
1473 fn print_with_space(&self) -> &str {
1474 self.prefix_str()
1475 }
1476}
1477
1478impl PrintWithSpace for hir::HeaderSafety {
1479 fn print_with_space(&self) -> &str {
1480 match self {
1481 hir::HeaderSafety::SafeTargetFeatures => "",
1482 hir::HeaderSafety::Normal(safety) => safety.print_with_space(),
1483 }
1484 }
1485}
1486
1487impl PrintWithSpace for hir::IsAsync {
1488 fn print_with_space(&self) -> &str {
1489 match self {
1490 hir::IsAsync::Async(_) => "async ",
1491 hir::IsAsync::NotAsync => "",
1492 }
1493 }
1494}
1495
1496impl PrintWithSpace for hir::Mutability {
1497 fn print_with_space(&self) -> &str {
1498 match self {
1499 hir::Mutability::Not => "",
1500 hir::Mutability::Mut => "mut ",
1501 }
1502 }
1503}
1504
1505pub(crate) fn print_constness_with_space(
1506 c: &hir::Constness,
1507 overall_stab: Option<StableSince>,
1508 const_stab: Option<ConstStability>,
1509) -> &'static str {
1510 match *c {
1511 hir::Constness::Const { always } => match (overall_stab, const_stab) {
1512 (_, Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }))
1514 | (_, None)
1516 | (None, Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => {
1518 if always {
1519 ""
1522 } else {
1523 "const "
1524 }
1525 }
1526 (Some(_), Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => "",
1528 },
1529 hir::Constness::NotConst => "",
1531 }
1532}
1533
1534pub(crate) fn print_import(import: &clean::Import, cx: &Context<'_>) -> impl Display {
1535 fmt::from_fn(move |f| match import.kind {
1536 clean::ImportKind::Simple(name) => {
1537 if name == import.source.path.last() {
1538 write!(f, "use {};", print_import_source(&import.source, cx))
1539 } else {
1540 write!(
1541 f,
1542 "use {source} as {name};",
1543 source = print_import_source(&import.source, cx)
1544 )
1545 }
1546 }
1547 clean::ImportKind::Glob => {
1548 if import.source.path.segments.is_empty() {
1549 write!(f, "use *;")
1550 } else {
1551 write!(f, "use {}::*;", print_import_source(&import.source, cx))
1552 }
1553 }
1554 })
1555}
1556
1557fn print_import_source(import_source: &clean::ImportSource, cx: &Context<'_>) -> impl Display {
1558 fmt::from_fn(move |f| match import_source.did {
1559 Some(did) => resolved_path(f, did, &import_source.path, true, false, cx),
1560 _ => {
1561 for seg in &import_source.path.segments[..import_source.path.segments.len() - 1] {
1562 write!(f, "{}::", seg.name)?;
1563 }
1564 let name = import_source.path.last();
1565 if let hir::def::Res::PrimTy(p) = import_source.path.res {
1566 primitive_link(f, PrimitiveType::from(p), format_args!("{name}"), cx)?;
1567 } else {
1568 f.write_str(name.as_str())?;
1569 }
1570 Ok(())
1571 }
1572 })
1573}
1574
1575fn print_assoc_item_constraint(
1576 assoc_item_constraint: &clean::AssocItemConstraint,
1577 cx: &Context<'_>,
1578) -> impl Display {
1579 fmt::from_fn(move |f| {
1580 f.write_str(assoc_item_constraint.assoc.name.as_str())?;
1581 print_generic_args(&assoc_item_constraint.assoc.args, cx).fmt(f)?;
1582 match assoc_item_constraint.kind {
1583 clean::AssocItemConstraintKind::Equality { ref term } => {
1584 f.write_str(" = ")?;
1585 print_term(term, cx).fmt(f)?;
1586 }
1587 clean::AssocItemConstraintKind::Bound { ref bounds } => {
1588 if !bounds.is_empty() {
1589 f.write_str(": ")?;
1590 print_generic_bounds(bounds, cx).fmt(f)?;
1591 }
1592 }
1593 }
1594 Ok(())
1595 })
1596}
1597
1598pub(crate) fn print_abi_with_space(abi: ExternAbi) -> impl Display {
1599 fmt::from_fn(move |f| {
1600 let quot = if f.alternate() { "\"" } else { """ };
1601 match abi {
1602 ExternAbi::Rust => Ok(()),
1603 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1604 }
1605 })
1606}
1607
1608fn print_generic_arg(generic_arg: &clean::GenericArg, cx: &Context<'_>) -> impl Display {
1609 fmt::from_fn(move |f| match generic_arg {
1610 clean::GenericArg::Lifetime(lt) => f.write_str(print_lifetime(lt)),
1611 clean::GenericArg::Type(ty) => print_type(ty, cx).fmt(f),
1612 clean::GenericArg::Const(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1613 clean::GenericArg::Infer => f.write_char('_'),
1614 })
1615}
1616
1617fn print_term(term: &clean::Term, cx: &Context<'_>) -> impl Display {
1618 fmt::from_fn(move |f| match term {
1619 clean::Term::Type(ty) => print_type(ty, cx).fmt(f),
1620 clean::Term::Constant(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1621 })
1622}