1use std::cmp::Ordering;
11use std::fmt::{self, Display, Write};
12use std::{iter, slice};
13
14use itertools::{Either, Itertools};
15use rustc_abi::ExternAbi;
16use rustc_ast::join_path_syms;
17use rustc_data_structures::fx::FxHashSet;
18use rustc_hir as hir;
19use rustc_hir::def::{DefKind, MacroKinds};
20use rustc_hir::def_id::{DefId, LOCAL_CRATE};
21use rustc_hir::{ConstStability, StabilityLevel, StableSince};
22use rustc_metadata::creader::CStore;
23use rustc_middle::ty::{self, TyCtxt, TypingMode};
24use rustc_span::Symbol;
25use rustc_span::symbol::kw;
26use tracing::{debug, trace};
27
28use super::url_parts_builder::UrlPartsBuilder;
29use crate::clean::types::ExternalLocation;
30use crate::clean::utils::find_nearest_parent_module;
31use crate::clean::{self, ExternalCrate, PrimitiveType};
32use crate::display::{Joined as _, MaybeDisplay as _, WithOpts, Wrapped};
33use crate::formats::cache::Cache;
34use crate::formats::item_type::ItemType;
35use crate::html::escape::{Escape, EscapeBodyText};
36use crate::html::render::Context;
37use crate::passes::collect_intra_doc_links::UrlFragment;
38
39pub(crate) fn print_generic_bounds(
40 bounds: &[clean::GenericBound],
41 cx: &Context<'_>,
42) -> impl Display {
43 fmt::from_fn(move |f| {
44 let mut bounds_dup = FxHashSet::default();
45
46 bounds
47 .iter()
48 .filter(move |b| bounds_dup.insert(*b))
49 .map(|bound| print_generic_bound(bound, cx))
50 .joined(" + ", f)
51 })
52}
53
54pub(crate) fn print_generic_param_def(
55 generic_param: &clean::GenericParamDef,
56 cx: &Context<'_>,
57) -> impl Display {
58 fmt::from_fn(move |f| match &generic_param.kind {
59 clean::GenericParamDefKind::Lifetime { outlives } => {
60 write!(f, "{}", generic_param.name)?;
61
62 if !outlives.is_empty() {
63 f.write_str(": ")?;
64 outlives.iter().map(|lt| print_lifetime(lt)).joined(" + ", f)?;
65 }
66
67 Ok(())
68 }
69 clean::GenericParamDefKind::Type { bounds, default, .. } => {
70 f.write_str(generic_param.name.as_str())?;
71
72 if !bounds.is_empty() {
73 f.write_str(": ")?;
74 print_generic_bounds(bounds, cx).fmt(f)?;
75 }
76
77 if let Some(ty) = default {
78 f.write_str(" = ")?;
79 print_type(ty, cx).fmt(f)?;
80 }
81
82 Ok(())
83 }
84 clean::GenericParamDefKind::Const { ty, default, .. } => {
85 write!(f, "const {}: ", generic_param.name)?;
86 print_type(ty, cx).fmt(f)?;
87
88 if let Some(default) = default {
89 f.write_str(" = ")?;
90 if f.alternate() {
91 write!(f, "{default}")?;
92 } else {
93 write!(f, "{}", Escape(default))?;
94 }
95 }
96
97 Ok(())
98 }
99 })
100}
101
102pub(crate) fn print_generics(generics: &clean::Generics, cx: &Context<'_>) -> impl Display {
103 let mut real_params = generics.params.iter().filter(|p| !p.is_synthetic_param()).peekable();
104 if real_params.peek().is_none() {
105 None
106 } else {
107 Some(Wrapped::with_angle_brackets().wrap_fn(move |f| {
108 real_params.clone().map(|g| print_generic_param_def(g, cx)).joined(", ", f)
109 }))
110 }
111 .maybe_display()
112}
113
114#[derive(Clone, Copy, PartialEq, Eq)]
115pub(crate) enum Ending {
116 Newline,
117 NoNewline,
118}
119
120fn print_where_predicate(predicate: &clean::WherePredicate, cx: &Context<'_>) -> impl Display {
121 fmt::from_fn(move |f| {
122 match predicate {
123 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
124 print_higher_ranked_params_with_space(bound_params, cx, "for").fmt(f)?;
125 print_type(ty, cx).fmt(f)?;
126 f.write_str(":")?;
127 if !bounds.is_empty() {
128 f.write_str(" ")?;
129 print_generic_bounds(bounds, cx).fmt(f)?;
130 }
131 Ok(())
132 }
133 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
134 write!(f, "{}:", print_lifetime(lifetime))?;
137 if !bounds.is_empty() {
138 write!(f, " {}", print_generic_bounds(bounds, cx))?;
139 }
140 Ok(())
141 }
142 clean::WherePredicate::EqPredicate { lhs, rhs } => {
143 let opts = WithOpts::from(f);
144 write!(
145 f,
146 "{} == {}",
147 opts.display(print_qpath_data(lhs, cx)),
148 opts.display(print_term(rhs, cx)),
149 )
150 }
151 }
152 })
153}
154
155pub(crate) fn print_where_clause(
159 gens: &clean::Generics,
160 cx: &Context<'_>,
161 indent: usize,
162 ending: Ending,
163) -> Option<impl Display> {
164 if gens.where_predicates.is_empty() {
165 return None;
166 }
167
168 Some(fmt::from_fn(move |f| {
169 let where_preds = fmt::from_fn(|f| {
170 gens.where_predicates
171 .iter()
172 .map(|predicate| {
173 fmt::from_fn(|f| {
174 if f.alternate() {
175 f.write_str(" ")?;
176 } else {
177 f.write_str("\n")?;
178 }
179 print_where_predicate(predicate, cx).fmt(f)
180 })
181 })
182 .joined(",", f)
183 });
184
185 let clause = if f.alternate() {
186 if ending == Ending::Newline {
187 format!(" where{where_preds},")
188 } else {
189 format!(" where{where_preds}")
190 }
191 } else {
192 let mut br_with_padding = String::with_capacity(6 * indent + 28);
193 br_with_padding.push('\n');
194
195 let where_indent = 3;
196 let padding_amount = if ending == Ending::Newline {
197 indent + 4
198 } else if indent == 0 {
199 4
200 } else {
201 indent + where_indent + "where ".len()
202 };
203
204 for _ in 0..padding_amount {
205 br_with_padding.push(' ');
206 }
207 let where_preds = where_preds.to_string().replace('\n', &br_with_padding);
208
209 if ending == Ending::Newline {
210 let mut clause = " ".repeat(indent.saturating_sub(1));
211 write!(clause, "<div class=\"where\">where{where_preds},</div>")?;
212 clause
213 } else {
214 if indent == 0 {
216 format!("\n<span class=\"where\">where{where_preds}</span>")
217 } else {
218 let where_preds = where_preds.replacen(&br_with_padding, " ", 1);
220
221 let mut clause = br_with_padding;
222 clause.truncate(indent + 1 + where_indent);
224
225 write!(clause, "<span class=\"where\">where{where_preds}</span>")?;
226 clause
227 }
228 }
229 };
230 write!(f, "{clause}")
231 }))
232}
233
234#[inline]
235pub(crate) fn print_lifetime(lt: &clean::Lifetime) -> &str {
236 lt.0.as_str()
237}
238
239pub(crate) fn print_constant_kind(
240 constant_kind: &clean::ConstantKind,
241 tcx: TyCtxt<'_>,
242) -> impl Display {
243 let expr = constant_kind.expr(tcx);
244 fmt::from_fn(
245 move |f| {
246 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
247 },
248 )
249}
250
251fn print_poly_trait(poly_trait: &clean::PolyTrait, cx: &Context<'_>) -> impl Display {
252 fmt::from_fn(move |f| {
253 print_higher_ranked_params_with_space(&poly_trait.generic_params, cx, "for").fmt(f)?;
254 print_path(&poly_trait.trait_, cx).fmt(f)
255 })
256}
257
258pub(crate) fn print_generic_bound(
259 generic_bound: &clean::GenericBound,
260 cx: &Context<'_>,
261) -> impl Display {
262 fmt::from_fn(move |f| match generic_bound {
263 clean::GenericBound::Outlives(lt) => f.write_str(print_lifetime(lt)),
264 clean::GenericBound::TraitBound(ty, modifiers) => {
265 let hir::TraitBoundModifiers { polarity, constness: _ } = modifiers;
267 f.write_str(match polarity {
268 hir::BoundPolarity::Positive => "",
269 hir::BoundPolarity::Maybe(_) => "?",
270 hir::BoundPolarity::Negative(_) => "!",
271 })?;
272 print_poly_trait(ty, cx).fmt(f)
273 }
274 clean::GenericBound::Use(args) => {
275 f.write_str("use")?;
276 Wrapped::with_angle_brackets()
277 .wrap_fn(|f| args.iter().map(|arg| arg.name()).joined(", ", f))
278 .fmt(f)
279 }
280 })
281}
282
283fn print_generic_args(generic_args: &clean::GenericArgs, cx: &Context<'_>) -> impl Display {
284 fmt::from_fn(move |f| {
285 match generic_args {
286 clean::GenericArgs::AngleBracketed { args, constraints } => {
287 if !args.is_empty() || !constraints.is_empty() {
288 Wrapped::with_angle_brackets()
289 .wrap_fn(|f| {
290 [Either::Left(args), Either::Right(constraints)]
291 .into_iter()
292 .flat_map(Either::factor_into_iter)
293 .map(|either| {
294 either.map_either(
295 |arg| print_generic_arg(arg, cx),
296 |constraint| print_assoc_item_constraint(constraint, cx),
297 )
298 })
299 .joined(", ", f)
300 })
301 .fmt(f)?;
302 }
303 }
304 clean::GenericArgs::Parenthesized { inputs, output } => {
305 Wrapped::with_parens()
306 .wrap_fn(|f| inputs.iter().map(|ty| print_type(ty, cx)).joined(", ", f))
307 .fmt(f)?;
308 if let Some(ref ty) = *output {
309 f.write_str(if f.alternate() { " -> " } else { " -> " })?;
310 print_type(ty, cx).fmt(f)?;
311 }
312 }
313 clean::GenericArgs::ReturnTypeNotation => {
314 f.write_str("(..)")?;
315 }
316 }
317 Ok(())
318 })
319}
320
321#[derive(PartialEq, Eq)]
323pub(crate) enum HrefError {
324 DocumentationNotBuilt,
343 Private,
345 NotInExternalCache,
347 UnnamableItem,
349}
350
351pub(crate) struct HrefInfo {
353 pub(crate) url: String,
355 pub(crate) kind: ItemType,
357 pub(crate) rust_path: Vec<Symbol>,
359}
360
361fn generate_macro_def_id_path(
364 def_id: DefId,
365 cx: &Context<'_>,
366 root_path: Option<&str>,
367) -> Result<HrefInfo, HrefError> {
368 let tcx = cx.tcx();
369 let crate_name = tcx.crate_name(def_id.krate);
370 let cache = cx.cache();
371
372 let cstore = CStore::from_tcx(tcx);
373 if !cstore.has_crate_data(def_id.krate) {
375 debug!("No data for crate {crate_name}");
376 return Err(HrefError::NotInExternalCache);
377 }
378 let DefKind::Macro(kinds) = tcx.def_kind(def_id) else {
379 unreachable!();
380 };
381 let item_type = if kinds == MacroKinds::DERIVE {
382 ItemType::ProcDerive
383 } else if kinds == MacroKinds::ATTR {
384 ItemType::ProcAttribute
385 } else {
386 ItemType::Macro
387 };
388 let path = clean::inline::get_item_path(tcx, def_id, item_type);
389 let [module_path @ .., last] = path.as_slice() else {
392 debug!("macro path is empty!");
393 return Err(HrefError::NotInExternalCache);
394 };
395 if module_path.is_empty() {
396 debug!("macro path too short: missing crate prefix (got 1 element, need at least 2)");
397 return Err(HrefError::NotInExternalCache);
398 }
399
400 let url = match cache.extern_locations[&def_id.krate] {
401 ExternalLocation::Remote { ref url, is_absolute } => {
402 let mut prefix = remote_url_prefix(url, is_absolute, cx.current.len());
403 prefix.extend(module_path.iter().copied());
404 prefix.push_fmt(format_args!("{}.{last}.html", item_type.as_str()));
405 prefix.finish()
406 }
407 ExternalLocation::Local => {
408 format!(
410 "{root_path}{path}/{item_type}.{last}.html",
411 root_path = root_path.unwrap_or(""),
412 path = fmt::from_fn(|f| module_path.iter().joined("/", f)),
413 item_type = item_type.as_str(),
414 )
415 }
416 ExternalLocation::Unknown => {
417 debug!("crate {crate_name} not in cache when linkifying macros");
418 return Err(HrefError::NotInExternalCache);
419 }
420 };
421 Ok(HrefInfo { url, kind: item_type, rust_path: path })
422}
423
424fn generate_item_def_id_path(
425 mut def_id: DefId,
426 original_def_id: DefId,
427 cx: &Context<'_>,
428 root_path: Option<&str>,
429) -> Result<HrefInfo, HrefError> {
430 use rustc_middle::traits::ObligationCause;
431 use rustc_trait_selection::infer::TyCtxtInferExt;
432 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
433
434 let tcx = cx.tcx();
435 let crate_name = tcx.crate_name(def_id.krate);
436 let mut prim = None;
437
438 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 let ty = tcx.type_of(def_id);
443 let ty = infcx
444 .at(&ObligationCause::dummy(), tcx.param_env(def_id))
445 .query_normalize(ty::Binder::dummy(ty.instantiate_identity().skip_norm_wip()))
446 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value).skip_binder())
447 .unwrap_or(ty.skip_binder());
448 if let Some(new_def_id) = ty.ty_adt_def().map(|adt| adt.did()) {
449 def_id = new_def_id;
450 } else {
451 prim = PrimitiveType::from_ty(ty);
452 }
453 }
454
455 let mut fqp = vec![crate_name];
456 let shortty = if let Some(prim) = prim {
457 fqp.push(prim.as_sym());
458 ItemType::Primitive
459 } else {
460 fqp.append(&mut clean::inline::item_relative_path(tcx, def_id));
461 ItemType::from_def_id(def_id, tcx)
462 };
463 let module_fqp = to_module_fqp(shortty, &fqp);
464
465 let (parts, is_absolute) = url_parts(cx.cache(), def_id, module_fqp, &cx.current)?;
466 let mut url = make_href(root_path, shortty, parts, &fqp, is_absolute);
467
468 if def_id != original_def_id {
469 let kind = ItemType::from_def_id(original_def_id, tcx);
470 url = format!("{url}#{kind}.{}", tcx.item_name(original_def_id))
471 };
472 Ok(HrefInfo { url, kind: shortty, rust_path: fqp })
473}
474
475fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool {
477 let mut cur_did = did;
478 while let Some(parent) = tcx.opt_parent(cur_did) {
479 match tcx.def_kind(parent) {
480 DefKind::Mod | DefKind::ForeignMod => cur_did = parent,
482 DefKind::Impl { .. } => return false,
488 _ => return true,
490 }
491 }
492 return false;
493}
494
495fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
496 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
497}
498
499fn remote_url_prefix(url: &str, is_absolute: bool, depth: usize) -> UrlPartsBuilder {
500 let url = url.trim_end_matches('/');
501 if is_absolute {
502 UrlPartsBuilder::singleton(url)
503 } else {
504 let extra = depth.saturating_sub(1);
505 let mut b: UrlPartsBuilder = iter::repeat_n("..", extra).collect();
506 b.push(url);
507 b
508 }
509}
510
511fn url_parts(
512 cache: &Cache,
513 def_id: DefId,
514 module_fqp: &[Symbol],
515 relative_to: &[Symbol],
516) -> Result<(UrlPartsBuilder, bool), HrefError> {
517 match cache.extern_locations[&def_id.krate] {
518 ExternalLocation::Remote { ref url, is_absolute } => {
519 let mut builder = remote_url_prefix(url, is_absolute, relative_to.len());
520 builder.extend(module_fqp.iter().copied());
521 Ok((builder, is_absolute))
522 }
523 ExternalLocation::Local => Ok((href_relative_parts(module_fqp, relative_to), false)),
524 ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt),
525 }
526}
527
528fn make_href(
529 root_path: Option<&str>,
530 shortty: ItemType,
531 mut url_parts: UrlPartsBuilder,
532 fqp: &[Symbol],
533 is_absolute: bool,
534) -> String {
535 if !is_absolute && let Some(root_path) = root_path {
537 let root = root_path.trim_end_matches('/');
538 url_parts.push_front(root);
539 }
540 debug!(?url_parts);
541 match shortty {
542 ItemType::Module => {
543 url_parts.push("index.html");
544 }
545 _ => {
546 let last = fqp.last().unwrap();
547 url_parts.push_fmt(format_args!("{shortty}.{last}.html"));
548 }
549 }
550 url_parts.finish()
551}
552
553pub(crate) fn href_with_root_path(
554 original_did: DefId,
555 cx: &Context<'_>,
556 root_path: Option<&str>,
557) -> Result<HrefInfo, HrefError> {
558 let tcx = cx.tcx();
559 let def_kind = tcx.def_kind(original_did);
560 let did = match def_kind {
561 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::Variant => {
562 tcx.parent(original_did)
564 }
565 DefKind::Ctor(..) => return href_with_root_path(tcx.parent(original_did), cx, root_path),
568 DefKind::ExternCrate => {
569 if let Some(local_did) = original_did.as_local() {
571 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
572 } else {
573 original_did
574 }
575 }
576 _ => original_did,
577 };
578 if is_unnamable(cx.tcx(), did) {
579 return Err(HrefError::UnnamableItem);
580 }
581 let cache = cx.cache();
582 let relative_to = &cx.current;
583
584 if !original_did.is_local() {
585 if root_path.is_some() {
588 if tcx.is_doc_hidden(original_did) {
589 return Err(HrefError::Private);
590 }
591 } else if !cache.effective_visibilities.is_directly_public(tcx, did)
592 && !cache.document_private
593 && !cache.primitive_locations.values().any(|&id| id == did)
594 {
595 return Err(HrefError::Private);
596 }
597 }
598
599 let (fqp, shortty, url_parts, is_absolute) = match cache.paths.get(&did) {
600 Some(&(ref fqp, shortty)) => (
601 fqp,
602 shortty,
603 {
604 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
605 debug!(?fqp, ?shortty, ?module_fqp);
606 href_relative_parts(module_fqp, relative_to)
607 },
608 false,
609 ),
610 None => {
611 let def_id_to_get = if root_path.is_some() { original_did } else { did };
615 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&def_id_to_get) {
616 let module_fqp = to_module_fqp(shortty, fqp);
617 let (parts, is_absolute) = url_parts(cache, did, module_fqp, relative_to)?;
618 (fqp, shortty, parts, is_absolute)
619 } else if matches!(def_kind, DefKind::Macro(_)) {
620 return generate_macro_def_id_path(did, cx, root_path);
621 } else if did.is_local() {
622 return Err(HrefError::Private);
623 } else {
624 return generate_item_def_id_path(did, original_did, cx, root_path);
625 }
626 }
627 };
628 Ok(HrefInfo {
629 url: make_href(root_path, shortty, url_parts, fqp, is_absolute),
630 kind: shortty,
631 rust_path: fqp.clone(),
632 })
633}
634
635pub(crate) fn href(did: DefId, cx: &Context<'_>) -> Result<HrefInfo, HrefError> {
636 href_with_root_path(did, cx, None)
637}
638
639pub(crate) fn href_relative_parts(fqp: &[Symbol], relative_to_fqp: &[Symbol]) -> UrlPartsBuilder {
643 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
644 if f != r {
646 let dissimilar_part_count = relative_to_fqp.len() - i;
647 let fqp_module = &fqp[i..];
648 return iter::repeat_n("..", dissimilar_part_count)
649 .chain(fqp_module.iter().map(|s| s.as_str()))
650 .collect();
651 }
652 }
653 match relative_to_fqp.len().cmp(&fqp.len()) {
654 Ordering::Less => {
655 fqp[relative_to_fqp.len()..fqp.len()].iter().copied().collect()
657 }
658 Ordering::Greater => {
659 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
661 iter::repeat_n("..", dissimilar_part_count).collect()
662 }
663 Ordering::Equal => {
664 UrlPartsBuilder::new()
666 }
667 }
668}
669
670pub(crate) fn link_tooltip(
671 did: DefId,
672 fragment: &Option<UrlFragment>,
673 cx: &Context<'_>,
674) -> impl fmt::Display {
675 fmt::from_fn(move |f| {
676 let cache = cx.cache();
677 let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did))
678 else {
679 return Ok(());
680 };
681 let fqp = if *shortty == ItemType::Primitive {
682 slice::from_ref(fqp.last().unwrap())
684 } else {
685 fqp
686 };
687 if let &Some(UrlFragment::Item(id)) = fragment {
688 write!(f, "{} ", cx.tcx().def_descr(id))?;
689 for component in fqp {
690 write!(f, "{component}::")?;
691 }
692 write!(f, "{}", cx.tcx().item_name(id))?;
693 } else if !fqp.is_empty() {
694 write!(f, "{shortty} ")?;
695 write!(f, "{}", join_path_syms(fqp))?;
696 }
697 Ok(())
698 })
699}
700
701fn resolved_path(
703 w: &mut fmt::Formatter<'_>,
704 did: DefId,
705 path: &clean::Path,
706 print_all: bool,
707 use_absolute: bool,
708 cx: &Context<'_>,
709) -> fmt::Result {
710 let last = path.segments.last().unwrap();
711
712 if print_all {
713 for seg in &path.segments[..path.segments.len() - 1] {
714 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
715 }
716 }
717 if w.alternate() {
718 write!(w, "{}{:#}", last.name, print_generic_args(&last.args, cx))?;
719 } else {
720 let path = fmt::from_fn(|f| {
721 if use_absolute {
722 if let Ok(HrefInfo { rust_path, .. }) = href(did, cx) {
723 write!(
724 f,
725 "{path}::{anchor}",
726 path = join_path_syms(&rust_path[..rust_path.len() - 1]),
727 anchor = print_anchor(did, *rust_path.last().unwrap(), cx)
728 )
729 } else {
730 write!(f, "{}", last.name)
731 }
732 } else {
733 write!(f, "{}", print_anchor(did, last.name, cx))
734 }
735 });
736 write!(w, "{path}{args}", args = print_generic_args(&last.args, cx))?;
737 }
738 Ok(())
739}
740
741fn primitive_link(
742 f: &mut fmt::Formatter<'_>,
743 prim: clean::PrimitiveType,
744 name: fmt::Arguments<'_>,
745 cx: &Context<'_>,
746) -> fmt::Result {
747 primitive_link_fragment(f, prim, name, "", cx)
748}
749
750fn primitive_link_fragment(
751 f: &mut fmt::Formatter<'_>,
752 prim: clean::PrimitiveType,
753 name: fmt::Arguments<'_>,
754 fragment: &str,
755 cx: &Context<'_>,
756) -> fmt::Result {
757 let m = &cx.cache();
758 let mut needs_termination = false;
759 if !f.alternate() {
760 match m.primitive_locations.get(&prim) {
761 Some(&def_id) if def_id.is_local() => {
762 let len = cx.current.len();
763 let path = fmt::from_fn(|f| {
764 if len == 0 {
765 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
766 write!(f, "{cname_sym}/")?;
767 } else {
768 for _ in 0..(len - 1) {
769 f.write_str("../")?;
770 }
771 }
772 Ok(())
773 });
774 write!(
775 f,
776 "<a class=\"primitive\" href=\"{path}primitive.{}.html{fragment}\">",
777 prim.as_sym()
778 )?;
779 needs_termination = true;
780 }
781 Some(&def_id) => {
782 let loc = match m.extern_locations[&def_id.krate] {
783 ExternalLocation::Remote { ref url, is_absolute } => {
784 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
785 let mut builder = remote_url_prefix(url, is_absolute, cx.current.len());
786 builder.push(cname_sym.as_str());
787 Some(builder)
788 }
789 ExternalLocation::Local => {
790 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
791 Some(if cx.current.first() == Some(&cname_sym) {
792 iter::repeat_n("..", cx.current.len() - 1).collect()
793 } else {
794 iter::repeat_n("..", cx.current.len())
795 .chain(iter::once(cname_sym.as_str()))
796 .collect()
797 })
798 }
799 ExternalLocation::Unknown => None,
800 };
801 if let Some(mut loc) = loc {
802 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
803 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
804 needs_termination = true;
805 }
806 }
807 None => {}
808 }
809 }
810 Display::fmt(&name, f)?;
811 if needs_termination {
812 write!(f, "</a>")?;
813 }
814 Ok(())
815}
816
817fn print_tybounds(
818 bounds: &[clean::PolyTrait],
819 lt: &Option<clean::Lifetime>,
820 cx: &Context<'_>,
821) -> impl Display {
822 fmt::from_fn(move |f| {
823 bounds.iter().map(|bound| print_poly_trait(bound, cx)).joined(" + ", f)?;
824 if let Some(lt) = lt {
825 write!(f, " + {}", print_lifetime(lt))?;
828 }
829 Ok(())
830 })
831}
832
833fn print_higher_ranked_params_with_space(
834 params: &[clean::GenericParamDef],
835 cx: &Context<'_>,
836 keyword: &'static str,
837) -> impl Display {
838 fmt::from_fn(move |f| {
839 if !params.is_empty() {
840 f.write_str(keyword)?;
841 Wrapped::with_angle_brackets()
842 .wrap_fn(|f| {
843 params.iter().map(|lt| print_generic_param_def(lt, cx)).joined(", ", f)
844 })
845 .fmt(f)?;
846 f.write_char(' ')?;
847 }
848 Ok(())
849 })
850}
851
852pub(crate) fn fragment(did: DefId, tcx: TyCtxt<'_>) -> impl Display {
853 fmt::from_fn(move |f| {
854 let def_kind = tcx.def_kind(did);
855 match def_kind {
856 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::Variant => {
857 let item_type = ItemType::from_def_id(did, tcx);
858 write!(f, "#{}.{}", item_type.as_str(), tcx.item_name(did))
859 }
860 DefKind::Field => {
861 let parent_def_id = tcx.parent(did);
862 f.write_char('#')?;
863 if tcx.def_kind(parent_def_id) == DefKind::Variant {
864 write!(f, "variant.{}.field", tcx.item_name(parent_def_id).as_str())?;
865 } else {
866 f.write_str("structfield")?;
867 };
868 write!(f, ".{}", tcx.item_name(did))
869 }
870 _ => Ok(()),
871 }
872 })
873}
874
875pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
876 fmt::from_fn(move |f| {
877 if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) {
878 write!(
879 f,
880 r#"<a class="{kind}" href="{url}{anchor}" title="{kind} {path}">{text}</a>"#,
881 anchor = fragment(did, cx.tcx()),
882 path = join_path_syms(rust_path),
883 text = EscapeBodyText(text.as_str()),
884 )
885 } else {
886 f.write_str(text.as_str())
887 }
888 })
889}
890
891fn fmt_type(
892 t: &clean::Type,
893 f: &mut fmt::Formatter<'_>,
894 use_absolute: bool,
895 cx: &Context<'_>,
896) -> fmt::Result {
897 trace!("fmt_type(t = {t:?})");
898
899 match t {
900 clean::Generic(name) => f.write_str(name.as_str()),
901 clean::SelfTy => f.write_str("Self"),
902 clean::Type::Path { path } => {
903 let did = path.def_id();
905 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
906 }
907 clean::DynTrait(bounds, lt) => {
908 f.write_str("dyn ")?;
909 print_tybounds(bounds, lt, cx).fmt(f)
910 }
911 clean::Infer => write!(f, "_"),
912 clean::Primitive(clean::PrimitiveType::Never) => {
913 primitive_link(f, PrimitiveType::Never, format_args!("!"), cx)
914 }
915 &clean::Primitive(prim) => primitive_link(f, prim, format_args!("{}", prim.as_sym()), cx),
916 clean::BareFunction(decl) => {
917 print_higher_ranked_params_with_space(&decl.generic_params, cx, "for").fmt(f)?;
918 decl.safety.print_with_space().fmt(f)?;
919 print_abi_with_space(decl.abi).fmt(f)?;
920 if f.alternate() {
921 f.write_str("fn")?;
922 } else {
923 primitive_link(f, PrimitiveType::Fn, format_args!("fn"), cx)?;
924 }
925 print_fn_decl(&decl.decl, cx).fmt(f)
926 }
927 clean::UnsafeBinder(binder) => {
928 print_higher_ranked_params_with_space(&binder.generic_params, cx, "unsafe").fmt(f)?;
929 print_type(&binder.ty, cx).fmt(f)
930 }
931 clean::Tuple(typs) => match &typs[..] {
932 &[] => primitive_link(f, PrimitiveType::Unit, format_args!("()"), cx),
933 [one] => {
934 if let clean::Generic(name) = one {
935 primitive_link(f, PrimitiveType::Tuple, format_args!("({name},)"), cx)
936 } else {
937 write!(f, "(")?;
938 print_type(one, cx).fmt(f)?;
939 write!(f, ",)")
940 }
941 }
942 many => {
943 let generic_names: Vec<Symbol> = many
944 .iter()
945 .filter_map(|t| match t {
946 clean::Generic(name) => Some(*name),
947 _ => None,
948 })
949 .collect();
950 let is_generic = generic_names.len() == many.len();
951 if is_generic {
952 primitive_link(
953 f,
954 PrimitiveType::Tuple,
955 format_args!(
956 "{}",
957 Wrapped::with_parens()
958 .wrap_fn(|f| generic_names.iter().joined(", ", f))
959 ),
960 cx,
961 )
962 } else {
963 Wrapped::with_parens()
964 .wrap_fn(|f| many.iter().map(|item| print_type(item, cx)).joined(", ", f))
965 .fmt(f)
966 }
967 }
968 },
969 clean::Slice(clean::Generic(name)) => {
970 primitive_link(f, PrimitiveType::Slice, format_args!("[{name}]"), cx)
971 }
972 clean::Slice(t) => Wrapped::with_square_brackets().wrap(print_type(t, cx)).fmt(f),
973 clean::Type::Pat(t, pat) => {
974 fmt::Display::fmt(&print_type(t, cx), f)?;
975 write!(f, " is {pat}")
976 }
977 clean::Type::FieldOf(t, field) => {
978 write!(f, "field_of!(")?;
979 fmt::Display::fmt(&print_type(t, cx), f)?;
980 write!(f, ", {field})")
981 }
982 clean::Array(clean::Generic(name), n) if !f.alternate() => primitive_link(
983 f,
984 PrimitiveType::Array,
985 format_args!("[{name}; {n}]", n = Escape(n)),
986 cx,
987 ),
988 clean::Array(t, n) => Wrapped::with_square_brackets()
989 .wrap(fmt::from_fn(|f| {
990 print_type(t, cx).fmt(f)?;
991 f.write_str("; ")?;
992 if f.alternate() {
993 f.write_str(n)
994 } else {
995 primitive_link(f, PrimitiveType::Array, format_args!("{n}", n = Escape(n)), cx)
996 }
997 }))
998 .fmt(f),
999 clean::RawPointer(m, t) => {
1000 let m = m.ptr_str();
1001
1002 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1003 primitive_link(
1004 f,
1005 clean::PrimitiveType::RawPointer,
1006 format_args!("*{m} {ty}", ty = WithOpts::from(f).display(print_type(t, cx))),
1007 cx,
1008 )
1009 } else {
1010 primitive_link(f, clean::PrimitiveType::RawPointer, format_args!("*{m} "), cx)?;
1011 print_type(t, cx).fmt(f)
1012 }
1013 }
1014 clean::BorrowedRef { lifetime: l, mutability, type_: ty } => {
1015 let lt = fmt::from_fn(|f| match l {
1016 Some(l) => write!(f, "{} ", print_lifetime(l)),
1017 _ => Ok(()),
1018 });
1019 let m = mutability.print_with_space();
1020 let amp = if f.alternate() { "&" } else { "&" };
1021
1022 if let clean::Generic(name) = **ty {
1023 return primitive_link(
1024 f,
1025 PrimitiveType::Reference,
1026 format_args!("{amp}{lt}{m}{name}"),
1027 cx,
1028 );
1029 }
1030
1031 write!(f, "{amp}{lt}{m}")?;
1032
1033 let needs_parens = match **ty {
1034 clean::DynTrait(ref bounds, ref trait_lt)
1035 if bounds.len() > 1 || trait_lt.is_some() =>
1036 {
1037 true
1038 }
1039 clean::ImplTrait(ref bounds) if bounds.len() > 1 => true,
1040 _ => false,
1041 };
1042 Wrapped::with_parens()
1043 .when(needs_parens)
1044 .wrap_fn(|f| fmt_type(ty, f, use_absolute, cx))
1045 .fmt(f)
1046 }
1047 clean::ImplTrait(bounds) => {
1048 f.write_str("impl ")?;
1049 print_generic_bounds(bounds, cx).fmt(f)
1050 }
1051 clean::QPath(qpath) => print_qpath_data(qpath, cx).fmt(f),
1052 }
1053}
1054
1055pub(crate) fn print_type(type_: &clean::Type, cx: &Context<'_>) -> impl Display {
1056 fmt::from_fn(move |f| fmt_type(type_, f, false, cx))
1057}
1058
1059pub(crate) fn print_path(path: &clean::Path, cx: &Context<'_>) -> impl Display {
1060 fmt::from_fn(move |f| resolved_path(f, path.def_id(), path, false, false, cx))
1061}
1062
1063fn print_qpath_data(qpath_data: &clean::QPathData, cx: &Context<'_>) -> impl Display {
1064 let clean::QPathData { ref assoc, ref self_type, should_fully_qualify, ref trait_ } =
1065 *qpath_data;
1066
1067 fmt::from_fn(move |f| {
1068 if let Some(trait_) = trait_
1072 && should_fully_qualify
1073 {
1074 let opts = WithOpts::from(f);
1075 Wrapped::with_angle_brackets()
1076 .wrap(format_args!(
1077 "{} as {}",
1078 opts.display(print_type(self_type, cx)),
1079 opts.display(print_path(trait_, cx))
1080 ))
1081 .fmt(f)?
1082 } else {
1083 print_type(self_type, cx).fmt(f)?;
1084 }
1085 f.write_str("::")?;
1086 if !f.alternate() {
1097 let parent_href = match trait_ {
1110 Some(trait_) => href(trait_.def_id(), cx).ok(),
1111 None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()),
1112 };
1113
1114 if let Some(HrefInfo { url, rust_path, .. }) = parent_href {
1115 write!(
1116 f,
1117 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1118 title=\"type {path}::{name}\">{name}</a>",
1119 shortty = ItemType::AssocType,
1120 name = assoc.name,
1121 path = join_path_syms(rust_path),
1122 )
1123 } else {
1124 write!(f, "{}", assoc.name)
1125 }
1126 } else {
1127 write!(f, "{}", assoc.name)
1128 }?;
1129
1130 print_generic_args(&assoc.args, cx).fmt(f)
1131 })
1132}
1133
1134pub(crate) fn print_impl(
1135 impl_: &clean::Impl,
1136 use_absolute: bool,
1137 cx: &Context<'_>,
1138) -> impl Display {
1139 fmt::from_fn(move |f| {
1140 f.write_str("impl")?;
1141 print_generics(&impl_.generics, cx).fmt(f)?;
1142 f.write_str(" ")?;
1143
1144 if let Some(ref ty) = impl_.trait_ {
1145 if impl_.is_negative_trait_impl() {
1146 f.write_char('!')?;
1147 }
1148 if impl_.kind.is_fake_variadic()
1149 && let Some(generics) = ty.generics()
1150 && let Ok(inner_type) = generics.exactly_one()
1151 {
1152 let last = ty.last();
1153 if f.alternate() {
1154 write!(f, "{last}")?;
1155 } else {
1156 write!(f, "{}", print_anchor(ty.def_id(), last, cx))?;
1157 };
1158 Wrapped::with_angle_brackets()
1159 .wrap_fn(|f| impl_.print_type(inner_type, f, use_absolute, cx))
1160 .fmt(f)?;
1161 } else {
1162 print_path(ty, cx).fmt(f)?;
1163 }
1164 f.write_str(" for ")?;
1165 }
1166
1167 if let Some(ty) = impl_.kind.as_blanket_ty() {
1168 fmt_type(ty, f, use_absolute, cx)?;
1169 } else {
1170 impl_.print_type(&impl_.for_, f, use_absolute, cx)?;
1171 }
1172
1173 print_where_clause(&impl_.generics, cx, 0, Ending::Newline).maybe_display().fmt(f)
1174 })
1175}
1176
1177impl clean::Impl {
1178 fn print_type(
1179 &self,
1180 type_: &clean::Type,
1181 f: &mut fmt::Formatter<'_>,
1182 use_absolute: bool,
1183 cx: &Context<'_>,
1184 ) -> Result<(), fmt::Error> {
1185 if let clean::Type::Tuple(types) = type_
1186 && let [clean::Type::Generic(name)] = &types[..]
1187 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1188 {
1189 primitive_link_fragment(
1192 f,
1193 PrimitiveType::Tuple,
1194 format_args!("({name}₁, {name}₂, …, {name}ₙ)"),
1195 "#trait-implementations-1",
1196 cx,
1197 )?;
1198 } else if let clean::Type::Array(ty, len) = type_
1199 && let clean::Type::Generic(name) = &**ty
1200 && &len[..] == "1"
1201 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1202 {
1203 primitive_link(f, PrimitiveType::Array, format_args!("[{name}; N]"), cx)?;
1204 } else if let clean::BareFunction(bare_fn) = &type_
1205 && let [clean::Parameter { type_: clean::Type::Generic(name), .. }] =
1206 &bare_fn.decl.inputs[..]
1207 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1208 {
1209 print_higher_ranked_params_with_space(&bare_fn.generic_params, cx, "for").fmt(f)?;
1213 bare_fn.safety.print_with_space().fmt(f)?;
1214 print_abi_with_space(bare_fn.abi).fmt(f)?;
1215 let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" };
1216 primitive_link_fragment(
1217 f,
1218 PrimitiveType::Tuple,
1219 format_args!("fn({name}₁, {name}₂, …, {name}ₙ{ellipsis})"),
1220 "#trait-implementations-1",
1221 cx,
1222 )?;
1223 if !bare_fn.decl.output.is_unit() {
1225 write!(f, " -> ")?;
1226 fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?;
1227 }
1228 } else if let clean::Type::Path { path } = type_
1229 && let Some(generics) = path.generics()
1230 && let Ok(ty) = generics.exactly_one()
1231 && self.kind.is_fake_variadic()
1232 {
1233 print_anchor(path.def_id(), path.last(), cx).fmt(f)?;
1234 Wrapped::with_angle_brackets()
1235 .wrap_fn(|f| self.print_type(ty, f, use_absolute, cx))
1236 .fmt(f)?;
1237 } else {
1238 fmt_type(type_, f, use_absolute, cx)?;
1239 }
1240 Ok(())
1241 }
1242}
1243
1244pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> impl Display {
1245 fmt::from_fn(move |f| {
1246 params
1247 .iter()
1248 .map(|param| {
1249 fmt::from_fn(|f| {
1250 if let Some(name) = param.name {
1251 write!(f, "{name}: ")?;
1252 }
1253 print_type(¶m.type_, cx).fmt(f)
1254 })
1255 })
1256 .joined(", ", f)
1257 })
1258}
1259
1260struct WriteCounter(usize);
1262
1263impl std::fmt::Write for WriteCounter {
1264 fn write_str(&mut self, s: &str) -> fmt::Result {
1265 self.0 += s.len();
1266 Ok(())
1267 }
1268}
1269
1270#[derive(Clone, Copy)]
1272struct Indent(usize);
1273
1274impl Display for Indent {
1275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276 for _ in 0..self.0 {
1277 f.write_char(' ')?;
1278 }
1279 Ok(())
1280 }
1281}
1282
1283fn print_parameter(parameter: &clean::Parameter, cx: &Context<'_>) -> impl fmt::Display {
1284 fmt::from_fn(move |f| {
1285 if let Some(self_ty) = parameter.to_receiver() {
1286 match self_ty {
1287 clean::SelfTy => f.write_str("self"),
1288 clean::BorrowedRef { lifetime, mutability, type_: clean::SelfTy } => {
1289 f.write_str(if f.alternate() { "&" } else { "&" })?;
1290 if let Some(lt) = lifetime {
1291 write!(f, "{lt} ", lt = print_lifetime(lt))?;
1292 }
1293 write!(f, "{mutability}self", mutability = mutability.print_with_space())
1294 }
1295 _ => {
1296 f.write_str("self: ")?;
1297 print_type(self_ty, cx).fmt(f)
1298 }
1299 }
1300 } else {
1301 if parameter.is_const {
1302 write!(f, "const ")?;
1303 }
1304 if let Some(name) = parameter.name {
1305 write!(f, "{name}: ")?;
1306 }
1307 print_type(¶meter.type_, cx).fmt(f)
1308 }
1309 })
1310}
1311
1312fn print_fn_decl(fn_decl: &clean::FnDecl, cx: &Context<'_>) -> impl Display {
1313 fmt::from_fn(move |f| {
1314 let ellipsis = if fn_decl.c_variadic { ", ..." } else { "" };
1315 Wrapped::with_parens()
1316 .wrap_fn(|f| {
1317 print_params(&fn_decl.inputs, cx).fmt(f)?;
1318 f.write_str(ellipsis)
1319 })
1320 .fmt(f)?;
1321 fn_decl.print_output(cx).fmt(f)
1322 })
1323}
1324
1325pub(crate) fn full_print_fn_decl(
1332 fn_decl: &clean::FnDecl,
1333 header_len: usize,
1334 indent: usize,
1335 cx: &Context<'_>,
1336) -> impl Display {
1337 fmt::from_fn(move |f| {
1338 let mut counter = WriteCounter(0);
1340 write!(&mut counter, "{:#}", fmt::from_fn(|f| { fn_decl.inner_full_print(None, f, cx) }))?;
1341 let line_wrapping_indent = if header_len + counter.0 > 80 { Some(indent) } else { None };
1343 fn_decl.inner_full_print(line_wrapping_indent, f, cx)
1346 })
1347}
1348
1349impl clean::FnDecl {
1350 fn inner_full_print(
1351 &self,
1352 line_wrapping_indent: Option<usize>,
1355 f: &mut fmt::Formatter<'_>,
1356 cx: &Context<'_>,
1357 ) -> fmt::Result {
1358 Wrapped::with_parens()
1359 .wrap_fn(|f| {
1360 if !self.inputs.is_empty() {
1361 let line_wrapping_indent = line_wrapping_indent.map(|n| Indent(n + 4));
1362
1363 if let Some(indent) = line_wrapping_indent {
1364 write!(f, "\n{indent}")?;
1365 }
1366
1367 let sep = fmt::from_fn(|f| {
1368 if let Some(indent) = line_wrapping_indent {
1369 write!(f, ",\n{indent}")
1370 } else {
1371 f.write_str(", ")
1372 }
1373 });
1374
1375 self.inputs.iter().map(|param| print_parameter(param, cx)).joined(sep, f)?;
1376
1377 if line_wrapping_indent.is_some() {
1378 writeln!(f, ",")?
1379 }
1380
1381 if self.c_variadic {
1382 match line_wrapping_indent {
1383 None => write!(f, ", ...")?,
1384 Some(indent) => writeln!(f, "{indent}...")?,
1385 };
1386 }
1387 }
1388
1389 if let Some(n) = line_wrapping_indent {
1390 write!(f, "{}", Indent(n))?
1391 }
1392
1393 Ok(())
1394 })
1395 .fmt(f)?;
1396
1397 self.print_output(cx).fmt(f)
1398 }
1399
1400 fn print_output(&self, cx: &Context<'_>) -> impl Display {
1401 fmt::from_fn(move |f| {
1402 if self.output.is_unit() {
1403 return Ok(());
1404 }
1405
1406 f.write_str(if f.alternate() { " -> " } else { " -> " })?;
1407 print_type(&self.output, cx).fmt(f)
1408 })
1409 }
1410}
1411
1412pub(crate) fn visibility_print_with_space(item: &clean::Item, cx: &Context<'_>) -> impl Display {
1413 fmt::from_fn(move |f| {
1414 let Some(vis) = item.visibility(cx.tcx()) else {
1415 return Ok(());
1416 };
1417
1418 match vis {
1419 ty::Visibility::Public => f.write_str("pub ")?,
1420 ty::Visibility::Restricted(vis_did) => {
1421 let parent_module =
1425 find_nearest_parent_module(cx.tcx(), item.item_id.expect_def_id());
1426
1427 if vis_did.is_crate_root() {
1428 f.write_str("pub(crate) ")?;
1429 } else if parent_module == Some(vis_did) {
1430 } else if parent_module
1433 .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1434 == Some(vis_did)
1435 {
1436 f.write_str("pub(super) ")?;
1437 } else {
1438 let path = cx.tcx().def_path(vis_did);
1439 debug!("path={path:?}");
1440 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1442 let anchor = print_anchor(vis_did, last_name, cx);
1443
1444 f.write_str("pub(in ")?;
1445 for seg in &path.data[..path.data.len() - 1] {
1446 write!(f, "{}::", seg.data.get_opt_name().unwrap())?;
1447 }
1448 write!(f, "{anchor}) ")?;
1449 }
1450 }
1451 }
1452 Ok(())
1453 })
1454}
1455
1456pub(crate) trait PrintWithSpace {
1457 fn print_with_space(&self) -> &str;
1458}
1459
1460impl PrintWithSpace for hir::Safety {
1461 fn print_with_space(&self) -> &str {
1462 self.prefix_str()
1463 }
1464}
1465
1466impl PrintWithSpace for hir::HeaderSafety {
1467 fn print_with_space(&self) -> &str {
1468 match self {
1469 hir::HeaderSafety::SafeTargetFeatures => "",
1470 hir::HeaderSafety::Normal(safety) => safety.print_with_space(),
1471 }
1472 }
1473}
1474
1475impl PrintWithSpace for hir::IsAsync {
1476 fn print_with_space(&self) -> &str {
1477 match self {
1478 hir::IsAsync::Async(_) => "async ",
1479 hir::IsAsync::NotAsync => "",
1480 }
1481 }
1482}
1483
1484impl PrintWithSpace for hir::Mutability {
1485 fn print_with_space(&self) -> &str {
1486 match self {
1487 hir::Mutability::Not => "",
1488 hir::Mutability::Mut => "mut ",
1489 }
1490 }
1491}
1492
1493pub(crate) fn print_constness_with_space(
1494 c: &hir::Constness,
1495 overall_stab: Option<StableSince>,
1496 const_stab: Option<ConstStability>,
1497) -> &'static str {
1498 match c {
1499 hir::Constness::Const => match (overall_stab, const_stab) {
1500 (_, Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }))
1502 | (_, None)
1504 | (None, Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => {
1506 "const "
1507 }
1508 (Some(_), Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => "",
1510 },
1511 hir::Constness::NotConst => "",
1513 }
1514}
1515
1516pub(crate) fn print_import(import: &clean::Import, cx: &Context<'_>) -> impl Display {
1517 fmt::from_fn(move |f| match import.kind {
1518 clean::ImportKind::Simple(name) => {
1519 if name == import.source.path.last() {
1520 write!(f, "use {};", print_import_source(&import.source, cx))
1521 } else {
1522 write!(
1523 f,
1524 "use {source} as {name};",
1525 source = print_import_source(&import.source, cx)
1526 )
1527 }
1528 }
1529 clean::ImportKind::Glob => {
1530 if import.source.path.segments.is_empty() {
1531 write!(f, "use *;")
1532 } else {
1533 write!(f, "use {}::*;", print_import_source(&import.source, cx))
1534 }
1535 }
1536 })
1537}
1538
1539fn print_import_source(import_source: &clean::ImportSource, cx: &Context<'_>) -> impl Display {
1540 fmt::from_fn(move |f| match import_source.did {
1541 Some(did) => resolved_path(f, did, &import_source.path, true, false, cx),
1542 _ => {
1543 for seg in &import_source.path.segments[..import_source.path.segments.len() - 1] {
1544 write!(f, "{}::", seg.name)?;
1545 }
1546 let name = import_source.path.last();
1547 if let hir::def::Res::PrimTy(p) = import_source.path.res {
1548 primitive_link(f, PrimitiveType::from(p), format_args!("{name}"), cx)?;
1549 } else {
1550 f.write_str(name.as_str())?;
1551 }
1552 Ok(())
1553 }
1554 })
1555}
1556
1557fn print_assoc_item_constraint(
1558 assoc_item_constraint: &clean::AssocItemConstraint,
1559 cx: &Context<'_>,
1560) -> impl Display {
1561 fmt::from_fn(move |f| {
1562 f.write_str(assoc_item_constraint.assoc.name.as_str())?;
1563 print_generic_args(&assoc_item_constraint.assoc.args, cx).fmt(f)?;
1564 match assoc_item_constraint.kind {
1565 clean::AssocItemConstraintKind::Equality { ref term } => {
1566 f.write_str(" = ")?;
1567 print_term(term, cx).fmt(f)?;
1568 }
1569 clean::AssocItemConstraintKind::Bound { ref bounds } => {
1570 if !bounds.is_empty() {
1571 f.write_str(": ")?;
1572 print_generic_bounds(bounds, cx).fmt(f)?;
1573 }
1574 }
1575 }
1576 Ok(())
1577 })
1578}
1579
1580pub(crate) fn print_abi_with_space(abi: ExternAbi) -> impl Display {
1581 fmt::from_fn(move |f| {
1582 let quot = if f.alternate() { "\"" } else { """ };
1583 match abi {
1584 ExternAbi::Rust => Ok(()),
1585 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1586 }
1587 })
1588}
1589
1590fn print_generic_arg(generic_arg: &clean::GenericArg, cx: &Context<'_>) -> impl Display {
1591 fmt::from_fn(move |f| match generic_arg {
1592 clean::GenericArg::Lifetime(lt) => f.write_str(print_lifetime(lt)),
1593 clean::GenericArg::Type(ty) => print_type(ty, cx).fmt(f),
1594 clean::GenericArg::Const(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1595 clean::GenericArg::Infer => f.write_char('_'),
1596 })
1597}
1598
1599fn print_term(term: &clean::Term, cx: &Context<'_>) -> impl Display {
1600 fmt::from_fn(move |f| match term {
1601 clean::Term::Type(ty) => print_type(ty, cx).fmt(f),
1602 clean::Term::Constant(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1603 })
1604}