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