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