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::kw;
26use rustc_span::{Symbol, sym};
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 mut path = clean::inline::get_item_path(tcx, def_id, item_type);
390 if path.len() < 2 {
391 debug!("macro path cannot be empty!");
394 return Err(HrefError::NotInExternalCache);
395 }
396
397 let mut prev = None;
399 if let Some(last) = path.pop() {
400 path.push(Symbol::intern(&format!("{}.{last}.html", item_type.as_str())));
401 prev = Some(last);
402 }
403
404 let url = match cache.extern_locations[&def_id.krate] {
405 ExternalLocation::Remote(ref s) => {
406 format!("{s}{path}", path = fmt::from_fn(|f| path.iter().joined("/", f)))
408 }
409 ExternalLocation::Local => {
410 format!(
412 "{root_path}{path}",
413 root_path = root_path.unwrap_or(""),
414 path = fmt::from_fn(|f| path.iter().joined("/", f))
415 )
416 }
417 ExternalLocation::Unknown => {
418 debug!("crate {crate_name} not in cache when linkifying macros");
419 return Err(HrefError::NotInExternalCache);
420 }
421 };
422 if let Some(prev) = prev {
423 path.pop();
424 path.push(prev);
425 }
426 Ok(HrefInfo { url, kind: item_type, rust_path: path })
427}
428
429fn generate_item_def_id_path(
430 mut def_id: DefId,
431 original_def_id: DefId,
432 cx: &Context<'_>,
433 root_path: Option<&str>,
434) -> Result<HrefInfo, HrefError> {
435 use rustc_middle::traits::ObligationCause;
436 use rustc_trait_selection::infer::TyCtxtInferExt;
437 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
438
439 let tcx = cx.tcx();
440 let crate_name = tcx.crate_name(def_id.krate);
441
442 if def_id != original_def_id && matches!(tcx.def_kind(def_id), DefKind::Impl { .. }) {
445 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
446 def_id = infcx
447 .at(&ObligationCause::dummy(), tcx.param_env(def_id))
448 .query_normalize(ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()))
449 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
450 .ok()
451 .and_then(|normalized| normalized.skip_binder().ty_adt_def())
452 .map(|adt| adt.did())
453 .unwrap_or(def_id);
454 }
455
456 let relative = clean::inline::item_relative_path(tcx, def_id);
457 let fqp: Vec<Symbol> = once(crate_name).chain(relative).collect();
458
459 let shortty = ItemType::from_def_id(def_id, tcx);
460 let module_fqp = to_module_fqp(shortty, &fqp);
461 let mut is_remote = false;
462
463 let url_parts = url_parts(cx.cache(), def_id, module_fqp, &cx.current, &mut is_remote)?;
464 let mut url_parts = make_href(root_path, shortty, url_parts, &fqp, is_remote);
465 if def_id != original_def_id {
466 let kind = ItemType::from_def_id(original_def_id, tcx);
467 url_parts = format!("{url_parts}#{kind}.{}", tcx.item_name(original_def_id))
468 };
469 Ok(HrefInfo { url: url_parts, kind: shortty, rust_path: fqp })
470}
471
472fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool {
474 let mut cur_did = did;
475 while let Some(parent) = tcx.opt_parent(cur_did) {
476 match tcx.def_kind(parent) {
477 DefKind::Mod | DefKind::ForeignMod => cur_did = parent,
479 DefKind::Impl { .. } => return false,
485 _ => return true,
487 }
488 }
489 return false;
490}
491
492fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
493 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
494}
495
496fn url_parts(
497 cache: &Cache,
498 def_id: DefId,
499 module_fqp: &[Symbol],
500 relative_to: &[Symbol],
501 is_remote: &mut bool,
502) -> Result<UrlPartsBuilder, HrefError> {
503 match cache.extern_locations[&def_id.krate] {
504 ExternalLocation::Remote(ref s) => {
505 *is_remote = true;
506 let s = s.trim_end_matches('/');
507 let mut builder = UrlPartsBuilder::singleton(s);
508 builder.extend(module_fqp.iter().copied());
509 Ok(builder)
510 }
511 ExternalLocation::Local => Ok(href_relative_parts(module_fqp, relative_to)),
512 ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt),
513 }
514}
515
516fn make_href(
517 root_path: Option<&str>,
518 shortty: ItemType,
519 mut url_parts: UrlPartsBuilder,
520 fqp: &[Symbol],
521 is_remote: bool,
522) -> String {
523 if !is_remote && let Some(root_path) = root_path {
524 let root = root_path.trim_end_matches('/');
525 url_parts.push_front(root);
526 }
527 debug!(?url_parts);
528 match shortty {
529 ItemType::Module => {
530 url_parts.push("index.html");
531 }
532 _ => {
533 let last = fqp.last().unwrap();
534 url_parts.push_fmt(format_args!("{shortty}.{last}.html"));
535 }
536 }
537 url_parts.finish()
538}
539
540pub(crate) fn href_with_root_path(
541 original_did: DefId,
542 cx: &Context<'_>,
543 root_path: Option<&str>,
544) -> Result<HrefInfo, HrefError> {
545 let tcx = cx.tcx();
546 let def_kind = tcx.def_kind(original_did);
547 let did = match def_kind {
548 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
549 tcx.parent(original_did)
551 }
552 DefKind::Ctor(..) => return href_with_root_path(tcx.parent(original_did), cx, root_path),
555 DefKind::ExternCrate => {
556 if let Some(local_did) = original_did.as_local() {
558 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
559 } else {
560 original_did
561 }
562 }
563 _ => original_did,
564 };
565 if is_unnamable(cx.tcx(), did) {
566 return Err(HrefError::UnnamableItem);
567 }
568 let cache = cx.cache();
569 let relative_to = &cx.current;
570
571 if !original_did.is_local() {
572 if root_path.is_some() {
575 if tcx.is_doc_hidden(original_did) {
576 return Err(HrefError::Private);
577 }
578 } else if !cache.effective_visibilities.is_directly_public(tcx, did)
579 && !cache.document_private
580 && !cache.primitive_locations.values().any(|&id| id == did)
581 {
582 return Err(HrefError::Private);
583 }
584 }
585
586 let mut is_remote = false;
587 let (fqp, shortty, url_parts) = match cache.paths.get(&did) {
588 Some(&(ref fqp, shortty)) => (fqp, shortty, {
589 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
590 debug!(?fqp, ?shortty, ?module_fqp);
591 href_relative_parts(module_fqp, relative_to)
592 }),
593 None => {
594 let def_id_to_get = if root_path.is_some() { original_did } else { did };
598 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&def_id_to_get) {
599 let module_fqp = to_module_fqp(shortty, fqp);
600 (fqp, shortty, url_parts(cache, did, module_fqp, relative_to, &mut is_remote)?)
601 } else if matches!(def_kind, DefKind::Macro(_)) {
602 return generate_macro_def_id_path(did, cx, root_path);
603 } else if did.is_local() {
604 return Err(HrefError::Private);
605 } else {
606 return generate_item_def_id_path(did, original_did, cx, root_path);
607 }
608 }
609 };
610 Ok(HrefInfo {
611 url: make_href(root_path, shortty, url_parts, fqp, is_remote),
612 kind: shortty,
613 rust_path: fqp.clone(),
614 })
615}
616
617pub(crate) fn href(did: DefId, cx: &Context<'_>) -> Result<HrefInfo, HrefError> {
618 href_with_root_path(did, cx, None)
619}
620
621pub(crate) fn href_relative_parts(fqp: &[Symbol], relative_to_fqp: &[Symbol]) -> UrlPartsBuilder {
625 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
626 if f != r {
628 let dissimilar_part_count = relative_to_fqp.len() - i;
629 let fqp_module = &fqp[i..];
630 return iter::repeat_n(sym::dotdot, dissimilar_part_count)
631 .chain(fqp_module.iter().copied())
632 .collect();
633 }
634 }
635 match relative_to_fqp.len().cmp(&fqp.len()) {
636 Ordering::Less => {
637 fqp[relative_to_fqp.len()..fqp.len()].iter().copied().collect()
639 }
640 Ordering::Greater => {
641 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
643 iter::repeat_n(sym::dotdot, dissimilar_part_count).collect()
644 }
645 Ordering::Equal => {
646 UrlPartsBuilder::new()
648 }
649 }
650}
651
652pub(crate) fn link_tooltip(
653 did: DefId,
654 fragment: &Option<UrlFragment>,
655 cx: &Context<'_>,
656) -> impl fmt::Display {
657 fmt::from_fn(move |f| {
658 let cache = cx.cache();
659 let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did))
660 else {
661 return Ok(());
662 };
663 let fqp = if *shortty == ItemType::Primitive {
664 slice::from_ref(fqp.last().unwrap())
666 } else {
667 fqp
668 };
669 if let &Some(UrlFragment::Item(id)) = fragment {
670 write!(f, "{} ", cx.tcx().def_descr(id))?;
671 for component in fqp {
672 write!(f, "{component}::")?;
673 }
674 write!(f, "{}", cx.tcx().item_name(id))?;
675 } else if !fqp.is_empty() {
676 write!(f, "{shortty} ")?;
677 write!(f, "{}", join_path_syms(fqp))?;
678 }
679 Ok(())
680 })
681}
682
683fn resolved_path(
685 w: &mut fmt::Formatter<'_>,
686 did: DefId,
687 path: &clean::Path,
688 print_all: bool,
689 use_absolute: bool,
690 cx: &Context<'_>,
691) -> fmt::Result {
692 let last = path.segments.last().unwrap();
693
694 if print_all {
695 for seg in &path.segments[..path.segments.len() - 1] {
696 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
697 }
698 }
699 if w.alternate() {
700 write!(w, "{}{:#}", last.name, print_generic_args(&last.args, cx))?;
701 } else {
702 let path = fmt::from_fn(|f| {
703 if use_absolute {
704 if let Ok(HrefInfo { rust_path, .. }) = href(did, cx) {
705 write!(
706 f,
707 "{path}::{anchor}",
708 path = join_path_syms(&rust_path[..rust_path.len() - 1]),
709 anchor = print_anchor(did, *rust_path.last().unwrap(), cx)
710 )
711 } else {
712 write!(f, "{}", last.name)
713 }
714 } else {
715 write!(f, "{}", print_anchor(did, last.name, cx))
716 }
717 });
718 write!(w, "{path}{args}", args = print_generic_args(&last.args, cx))?;
719 }
720 Ok(())
721}
722
723fn primitive_link(
724 f: &mut fmt::Formatter<'_>,
725 prim: clean::PrimitiveType,
726 name: fmt::Arguments<'_>,
727 cx: &Context<'_>,
728) -> fmt::Result {
729 primitive_link_fragment(f, prim, name, "", cx)
730}
731
732fn primitive_link_fragment(
733 f: &mut fmt::Formatter<'_>,
734 prim: clean::PrimitiveType,
735 name: fmt::Arguments<'_>,
736 fragment: &str,
737 cx: &Context<'_>,
738) -> fmt::Result {
739 let m = &cx.cache();
740 let mut needs_termination = false;
741 if !f.alternate() {
742 match m.primitive_locations.get(&prim) {
743 Some(&def_id) if def_id.is_local() => {
744 let len = cx.current.len();
745 let path = fmt::from_fn(|f| {
746 if len == 0 {
747 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
748 write!(f, "{cname_sym}/")?;
749 } else {
750 for _ in 0..(len - 1) {
751 f.write_str("../")?;
752 }
753 }
754 Ok(())
755 });
756 write!(
757 f,
758 "<a class=\"primitive\" href=\"{path}primitive.{}.html{fragment}\">",
759 prim.as_sym()
760 )?;
761 needs_termination = true;
762 }
763 Some(&def_id) => {
764 let loc = match m.extern_locations[&def_id.krate] {
765 ExternalLocation::Remote(ref s) => {
766 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
767 let builder: UrlPartsBuilder =
768 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
769 .into_iter()
770 .collect();
771 Some(builder)
772 }
773 ExternalLocation::Local => {
774 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
775 Some(if cx.current.first() == Some(&cname_sym) {
776 iter::repeat_n(sym::dotdot, cx.current.len() - 1).collect()
777 } else {
778 iter::repeat_n(sym::dotdot, cx.current.len())
779 .chain(iter::once(cname_sym))
780 .collect()
781 })
782 }
783 ExternalLocation::Unknown => None,
784 };
785 if let Some(mut loc) = loc {
786 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
787 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
788 needs_termination = true;
789 }
790 }
791 None => {}
792 }
793 }
794 Display::fmt(&name, f)?;
795 if needs_termination {
796 write!(f, "</a>")?;
797 }
798 Ok(())
799}
800
801fn print_tybounds(
802 bounds: &[clean::PolyTrait],
803 lt: &Option<clean::Lifetime>,
804 cx: &Context<'_>,
805) -> impl Display {
806 fmt::from_fn(move |f| {
807 bounds.iter().map(|bound| print_poly_trait(bound, cx)).joined(" + ", f)?;
808 if let Some(lt) = lt {
809 write!(f, " + {}", print_lifetime(lt))?;
812 }
813 Ok(())
814 })
815}
816
817fn print_higher_ranked_params_with_space(
818 params: &[clean::GenericParamDef],
819 cx: &Context<'_>,
820 keyword: &'static str,
821) -> impl Display {
822 fmt::from_fn(move |f| {
823 if !params.is_empty() {
824 f.write_str(keyword)?;
825 Wrapped::with_angle_brackets()
826 .wrap_fn(|f| {
827 params.iter().map(|lt| print_generic_param_def(lt, cx)).joined(", ", f)
828 })
829 .fmt(f)?;
830 f.write_char(' ')?;
831 }
832 Ok(())
833 })
834}
835
836pub(crate) fn fragment(did: DefId, tcx: TyCtxt<'_>) -> impl Display {
837 fmt::from_fn(move |f| {
838 let def_kind = tcx.def_kind(did);
839 match def_kind {
840 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
841 let item_type = ItemType::from_def_id(did, tcx);
842 write!(f, "#{}.{}", item_type.as_str(), tcx.item_name(did))
843 }
844 DefKind::Field => {
845 let parent_def_id = tcx.parent(did);
846 f.write_char('#')?;
847 if tcx.def_kind(parent_def_id) == DefKind::Variant {
848 write!(f, "variant.{}.field", tcx.item_name(parent_def_id).as_str())?;
849 } else {
850 f.write_str("structfield")?;
851 };
852 write!(f, ".{}", tcx.item_name(did))
853 }
854 _ => Ok(()),
855 }
856 })
857}
858
859pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
860 fmt::from_fn(move |f| {
861 if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) {
862 write!(
863 f,
864 r#"<a class="{kind}" href="{url}{anchor}" title="{kind} {path}">{text}</a>"#,
865 anchor = fragment(did, cx.tcx()),
866 path = join_path_syms(rust_path),
867 text = EscapeBodyText(text.as_str()),
868 )
869 } else {
870 f.write_str(text.as_str())
871 }
872 })
873}
874
875fn fmt_type(
876 t: &clean::Type,
877 f: &mut fmt::Formatter<'_>,
878 use_absolute: bool,
879 cx: &Context<'_>,
880) -> fmt::Result {
881 trace!("fmt_type(t = {t:?})");
882
883 match t {
884 clean::Generic(name) => f.write_str(name.as_str()),
885 clean::SelfTy => f.write_str("Self"),
886 clean::Type::Path { path } => {
887 let did = path.def_id();
889 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
890 }
891 clean::DynTrait(bounds, lt) => {
892 f.write_str("dyn ")?;
893 print_tybounds(bounds, lt, cx).fmt(f)
894 }
895 clean::Infer => write!(f, "_"),
896 clean::Primitive(clean::PrimitiveType::Never) => {
897 primitive_link(f, PrimitiveType::Never, format_args!("!"), cx)
898 }
899 &clean::Primitive(prim) => primitive_link(f, prim, format_args!("{}", prim.as_sym()), cx),
900 clean::BareFunction(decl) => {
901 print_higher_ranked_params_with_space(&decl.generic_params, cx, "for").fmt(f)?;
902 decl.safety.print_with_space().fmt(f)?;
903 print_abi_with_space(decl.abi).fmt(f)?;
904 if f.alternate() {
905 f.write_str("fn")?;
906 } else {
907 primitive_link(f, PrimitiveType::Fn, format_args!("fn"), cx)?;
908 }
909 print_fn_decl(&decl.decl, cx).fmt(f)
910 }
911 clean::UnsafeBinder(binder) => {
912 print_higher_ranked_params_with_space(&binder.generic_params, cx, "unsafe").fmt(f)?;
913 print_type(&binder.ty, cx).fmt(f)
914 }
915 clean::Tuple(typs) => match &typs[..] {
916 &[] => primitive_link(f, PrimitiveType::Unit, format_args!("()"), cx),
917 [one] => {
918 if let clean::Generic(name) = one {
919 primitive_link(f, PrimitiveType::Tuple, format_args!("({name},)"), cx)
920 } else {
921 write!(f, "(")?;
922 print_type(one, cx).fmt(f)?;
923 write!(f, ",)")
924 }
925 }
926 many => {
927 let generic_names: Vec<Symbol> = many
928 .iter()
929 .filter_map(|t| match t {
930 clean::Generic(name) => Some(*name),
931 _ => None,
932 })
933 .collect();
934 let is_generic = generic_names.len() == many.len();
935 if is_generic {
936 primitive_link(
937 f,
938 PrimitiveType::Tuple,
939 format_args!(
940 "{}",
941 Wrapped::with_parens()
942 .wrap_fn(|f| generic_names.iter().joined(", ", f))
943 ),
944 cx,
945 )
946 } else {
947 Wrapped::with_parens()
948 .wrap_fn(|f| many.iter().map(|item| print_type(item, cx)).joined(", ", f))
949 .fmt(f)
950 }
951 }
952 },
953 clean::Slice(box clean::Generic(name)) => {
954 primitive_link(f, PrimitiveType::Slice, format_args!("[{name}]"), cx)
955 }
956 clean::Slice(t) => Wrapped::with_square_brackets().wrap(print_type(t, cx)).fmt(f),
957 clean::Type::Pat(t, pat) => {
958 fmt::Display::fmt(&print_type(t, cx), f)?;
959 write!(f, " is {pat}")
960 }
961 clean::Array(box clean::Generic(name), n) if !f.alternate() => primitive_link(
962 f,
963 PrimitiveType::Array,
964 format_args!("[{name}; {n}]", n = Escape(n)),
965 cx,
966 ),
967 clean::Array(t, n) => Wrapped::with_square_brackets()
968 .wrap(fmt::from_fn(|f| {
969 print_type(t, cx).fmt(f)?;
970 f.write_str("; ")?;
971 if f.alternate() {
972 f.write_str(n)
973 } else {
974 primitive_link(f, PrimitiveType::Array, format_args!("{n}", n = Escape(n)), cx)
975 }
976 }))
977 .fmt(f),
978 clean::RawPointer(m, t) => {
979 let m = m.ptr_str();
980
981 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
982 primitive_link(
983 f,
984 clean::PrimitiveType::RawPointer,
985 format_args!("*{m} {ty}", ty = WithOpts::from(f).display(print_type(t, cx))),
986 cx,
987 )
988 } else {
989 primitive_link(f, clean::PrimitiveType::RawPointer, format_args!("*{m} "), cx)?;
990 print_type(t, cx).fmt(f)
991 }
992 }
993 clean::BorrowedRef { lifetime: l, mutability, type_: ty } => {
994 let lt = fmt::from_fn(|f| match l {
995 Some(l) => write!(f, "{} ", print_lifetime(l)),
996 _ => Ok(()),
997 });
998 let m = mutability.print_with_space();
999 let amp = if f.alternate() { "&" } else { "&" };
1000
1001 if let clean::Generic(name) = **ty {
1002 return primitive_link(
1003 f,
1004 PrimitiveType::Reference,
1005 format_args!("{amp}{lt}{m}{name}"),
1006 cx,
1007 );
1008 }
1009
1010 write!(f, "{amp}{lt}{m}")?;
1011
1012 let needs_parens = match **ty {
1013 clean::DynTrait(ref bounds, ref trait_lt)
1014 if bounds.len() > 1 || trait_lt.is_some() =>
1015 {
1016 true
1017 }
1018 clean::ImplTrait(ref bounds) if bounds.len() > 1 => true,
1019 _ => false,
1020 };
1021 Wrapped::with_parens()
1022 .when(needs_parens)
1023 .wrap_fn(|f| fmt_type(ty, f, use_absolute, cx))
1024 .fmt(f)
1025 }
1026 clean::ImplTrait(bounds) => {
1027 f.write_str("impl ")?;
1028 print_generic_bounds(bounds, cx).fmt(f)
1029 }
1030 clean::QPath(qpath) => print_qpath_data(qpath, cx).fmt(f),
1031 }
1032}
1033
1034pub(crate) fn print_type(type_: &clean::Type, cx: &Context<'_>) -> impl Display {
1035 fmt::from_fn(move |f| fmt_type(type_, f, false, cx))
1036}
1037
1038pub(crate) fn print_path(path: &clean::Path, cx: &Context<'_>) -> impl Display {
1039 fmt::from_fn(move |f| resolved_path(f, path.def_id(), path, false, false, cx))
1040}
1041
1042fn print_qpath_data(qpath_data: &clean::QPathData, cx: &Context<'_>) -> impl Display {
1043 let clean::QPathData { ref assoc, ref self_type, should_fully_qualify, ref trait_ } =
1044 *qpath_data;
1045
1046 fmt::from_fn(move |f| {
1047 if let Some(trait_) = trait_
1051 && should_fully_qualify
1052 {
1053 let opts = WithOpts::from(f);
1054 Wrapped::with_angle_brackets()
1055 .wrap(format_args!(
1056 "{} as {}",
1057 opts.display(print_type(self_type, cx)),
1058 opts.display(print_path(trait_, cx))
1059 ))
1060 .fmt(f)?
1061 } else {
1062 print_type(self_type, cx).fmt(f)?;
1063 }
1064 f.write_str("::")?;
1065 if !f.alternate() {
1076 let parent_href = match trait_ {
1089 Some(trait_) => href(trait_.def_id(), cx).ok(),
1090 None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()),
1091 };
1092
1093 if let Some(HrefInfo { url, rust_path, .. }) = parent_href {
1094 write!(
1095 f,
1096 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1097 title=\"type {path}::{name}\">{name}</a>",
1098 shortty = ItemType::AssocType,
1099 name = assoc.name,
1100 path = join_path_syms(rust_path),
1101 )
1102 } else {
1103 write!(f, "{}", assoc.name)
1104 }
1105 } else {
1106 write!(f, "{}", assoc.name)
1107 }?;
1108
1109 print_generic_args(&assoc.args, cx).fmt(f)
1110 })
1111}
1112
1113pub(crate) fn print_impl(
1114 impl_: &clean::Impl,
1115 use_absolute: bool,
1116 cx: &Context<'_>,
1117) -> impl Display {
1118 fmt::from_fn(move |f| {
1119 f.write_str("impl")?;
1120 print_generics(&impl_.generics, cx).fmt(f)?;
1121 f.write_str(" ")?;
1122
1123 if let Some(ref ty) = impl_.trait_ {
1124 if impl_.is_negative_trait_impl() {
1125 f.write_char('!')?;
1126 }
1127 if impl_.kind.is_fake_variadic()
1128 && let Some(generics) = ty.generics()
1129 && let Ok(inner_type) = Itertools::exactly_one(generics)
1131 {
1132 let last = ty.last();
1133 if f.alternate() {
1134 write!(f, "{last}")?;
1135 } else {
1136 write!(f, "{}", print_anchor(ty.def_id(), last, cx))?;
1137 };
1138 Wrapped::with_angle_brackets()
1139 .wrap_fn(|f| impl_.print_type(inner_type, f, use_absolute, cx))
1140 .fmt(f)?;
1141 } else {
1142 print_path(ty, cx).fmt(f)?;
1143 }
1144 f.write_str(" for ")?;
1145 }
1146
1147 if let Some(ty) = impl_.kind.as_blanket_ty() {
1148 fmt_type(ty, f, use_absolute, cx)?;
1149 } else {
1150 impl_.print_type(&impl_.for_, f, use_absolute, cx)?;
1151 }
1152
1153 print_where_clause(&impl_.generics, cx, 0, Ending::Newline).maybe_display().fmt(f)
1154 })
1155}
1156
1157impl clean::Impl {
1158 fn print_type(
1159 &self,
1160 type_: &clean::Type,
1161 f: &mut fmt::Formatter<'_>,
1162 use_absolute: bool,
1163 cx: &Context<'_>,
1164 ) -> Result<(), fmt::Error> {
1165 if let clean::Type::Tuple(types) = type_
1166 && let [clean::Type::Generic(name)] = &types[..]
1167 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1168 {
1169 primitive_link_fragment(
1172 f,
1173 PrimitiveType::Tuple,
1174 format_args!("({name}₁, {name}₂, …, {name}ₙ)"),
1175 "#trait-implementations-1",
1176 cx,
1177 )?;
1178 } else if let clean::Type::Array(ty, len) = type_
1179 && let clean::Type::Generic(name) = &**ty
1180 && &len[..] == "1"
1181 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1182 {
1183 primitive_link(f, PrimitiveType::Array, format_args!("[{name}; N]"), cx)?;
1184 } else if let clean::BareFunction(bare_fn) = &type_
1185 && let [clean::Parameter { type_: clean::Type::Generic(name), .. }] =
1186 &bare_fn.decl.inputs[..]
1187 && (self.kind.is_fake_variadic() || self.kind.is_auto())
1188 {
1189 print_higher_ranked_params_with_space(&bare_fn.generic_params, cx, "for").fmt(f)?;
1193 bare_fn.safety.print_with_space().fmt(f)?;
1194 print_abi_with_space(bare_fn.abi).fmt(f)?;
1195 let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" };
1196 primitive_link_fragment(
1197 f,
1198 PrimitiveType::Tuple,
1199 format_args!("fn({name}₁, {name}₂, …, {name}ₙ{ellipsis})"),
1200 "#trait-implementations-1",
1201 cx,
1202 )?;
1203 if !bare_fn.decl.output.is_unit() {
1205 write!(f, " -> ")?;
1206 fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?;
1207 }
1208 } else if let clean::Type::Path { path } = type_
1209 && let Some(generics) = path.generics()
1210 && let Ok(ty) = Itertools::exactly_one(generics)
1212 && self.kind.is_fake_variadic()
1213 {
1214 print_anchor(path.def_id(), path.last(), cx).fmt(f)?;
1215 Wrapped::with_angle_brackets()
1216 .wrap_fn(|f| self.print_type(ty, f, use_absolute, cx))
1217 .fmt(f)?;
1218 } else {
1219 fmt_type(type_, f, use_absolute, cx)?;
1220 }
1221 Ok(())
1222 }
1223}
1224
1225pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> impl Display {
1226 fmt::from_fn(move |f| {
1227 params
1228 .iter()
1229 .map(|param| {
1230 fmt::from_fn(|f| {
1231 if let Some(name) = param.name {
1232 write!(f, "{name}: ")?;
1233 }
1234 print_type(¶m.type_, cx).fmt(f)
1235 })
1236 })
1237 .joined(", ", f)
1238 })
1239}
1240
1241struct WriteCounter(usize);
1243
1244impl std::fmt::Write for WriteCounter {
1245 fn write_str(&mut self, s: &str) -> fmt::Result {
1246 self.0 += s.len();
1247 Ok(())
1248 }
1249}
1250
1251#[derive(Clone, Copy)]
1253struct Indent(usize);
1254
1255impl Display for Indent {
1256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257 for _ in 0..self.0 {
1258 f.write_char(' ')?;
1259 }
1260 Ok(())
1261 }
1262}
1263
1264fn print_parameter(parameter: &clean::Parameter, cx: &Context<'_>) -> impl fmt::Display {
1265 fmt::from_fn(move |f| {
1266 if let Some(self_ty) = parameter.to_receiver() {
1267 match self_ty {
1268 clean::SelfTy => f.write_str("self"),
1269 clean::BorrowedRef { lifetime, mutability, type_: box clean::SelfTy } => {
1270 f.write_str(if f.alternate() { "&" } else { "&" })?;
1271 if let Some(lt) = lifetime {
1272 write!(f, "{lt} ", lt = print_lifetime(lt))?;
1273 }
1274 write!(f, "{mutability}self", mutability = mutability.print_with_space())
1275 }
1276 _ => {
1277 f.write_str("self: ")?;
1278 print_type(self_ty, cx).fmt(f)
1279 }
1280 }
1281 } else {
1282 if parameter.is_const {
1283 write!(f, "const ")?;
1284 }
1285 if let Some(name) = parameter.name {
1286 write!(f, "{name}: ")?;
1287 }
1288 print_type(¶meter.type_, cx).fmt(f)
1289 }
1290 })
1291}
1292
1293fn print_fn_decl(fn_decl: &clean::FnDecl, cx: &Context<'_>) -> impl Display {
1294 fmt::from_fn(move |f| {
1295 let ellipsis = if fn_decl.c_variadic { ", ..." } else { "" };
1296 Wrapped::with_parens()
1297 .wrap_fn(|f| {
1298 print_params(&fn_decl.inputs, cx).fmt(f)?;
1299 f.write_str(ellipsis)
1300 })
1301 .fmt(f)?;
1302 fn_decl.print_output(cx).fmt(f)
1303 })
1304}
1305
1306pub(crate) fn full_print_fn_decl(
1313 fn_decl: &clean::FnDecl,
1314 header_len: usize,
1315 indent: usize,
1316 cx: &Context<'_>,
1317) -> impl Display {
1318 fmt::from_fn(move |f| {
1319 let mut counter = WriteCounter(0);
1321 write!(&mut counter, "{:#}", fmt::from_fn(|f| { fn_decl.inner_full_print(None, f, cx) }))?;
1322 let line_wrapping_indent = if header_len + counter.0 > 80 { Some(indent) } else { None };
1324 fn_decl.inner_full_print(line_wrapping_indent, f, cx)
1327 })
1328}
1329
1330impl clean::FnDecl {
1331 fn inner_full_print(
1332 &self,
1333 line_wrapping_indent: Option<usize>,
1336 f: &mut fmt::Formatter<'_>,
1337 cx: &Context<'_>,
1338 ) -> fmt::Result {
1339 Wrapped::with_parens()
1340 .wrap_fn(|f| {
1341 if !self.inputs.is_empty() {
1342 let line_wrapping_indent = line_wrapping_indent.map(|n| Indent(n + 4));
1343
1344 if let Some(indent) = line_wrapping_indent {
1345 write!(f, "\n{indent}")?;
1346 }
1347
1348 let sep = fmt::from_fn(|f| {
1349 if let Some(indent) = line_wrapping_indent {
1350 write!(f, ",\n{indent}")
1351 } else {
1352 f.write_str(", ")
1353 }
1354 });
1355
1356 self.inputs.iter().map(|param| print_parameter(param, cx)).joined(sep, f)?;
1357
1358 if line_wrapping_indent.is_some() {
1359 writeln!(f, ",")?
1360 }
1361
1362 if self.c_variadic {
1363 match line_wrapping_indent {
1364 None => write!(f, ", ...")?,
1365 Some(indent) => writeln!(f, "{indent}...")?,
1366 };
1367 }
1368 }
1369
1370 if let Some(n) = line_wrapping_indent {
1371 write!(f, "{}", Indent(n))?
1372 }
1373
1374 Ok(())
1375 })
1376 .fmt(f)?;
1377
1378 self.print_output(cx).fmt(f)
1379 }
1380
1381 fn print_output(&self, cx: &Context<'_>) -> impl Display {
1382 fmt::from_fn(move |f| {
1383 if self.output.is_unit() {
1384 return Ok(());
1385 }
1386
1387 f.write_str(if f.alternate() { " -> " } else { " -> " })?;
1388 print_type(&self.output, cx).fmt(f)
1389 })
1390 }
1391}
1392
1393pub(crate) fn visibility_print_with_space(item: &clean::Item, cx: &Context<'_>) -> impl Display {
1394 fmt::from_fn(move |f| {
1395 if item.is_doc_hidden() {
1396 f.write_str("#[doc(hidden)] ")?;
1397 }
1398
1399 let Some(vis) = item.visibility(cx.tcx()) else {
1400 return Ok(());
1401 };
1402
1403 match vis {
1404 ty::Visibility::Public => f.write_str("pub ")?,
1405 ty::Visibility::Restricted(vis_did) => {
1406 let parent_module =
1410 find_nearest_parent_module(cx.tcx(), item.item_id.expect_def_id());
1411
1412 if vis_did.is_crate_root() {
1413 f.write_str("pub(crate) ")?;
1414 } else if parent_module == Some(vis_did) {
1415 } else if parent_module
1418 .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1419 == Some(vis_did)
1420 {
1421 f.write_str("pub(super) ")?;
1422 } else {
1423 let path = cx.tcx().def_path(vis_did);
1424 debug!("path={path:?}");
1425 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1427 let anchor = print_anchor(vis_did, last_name, cx);
1428
1429 f.write_str("pub(in ")?;
1430 for seg in &path.data[..path.data.len() - 1] {
1431 write!(f, "{}::", seg.data.get_opt_name().unwrap())?;
1432 }
1433 write!(f, "{anchor}) ")?;
1434 }
1435 }
1436 }
1437 Ok(())
1438 })
1439}
1440
1441pub(crate) trait PrintWithSpace {
1442 fn print_with_space(&self) -> &str;
1443}
1444
1445impl PrintWithSpace for hir::Safety {
1446 fn print_with_space(&self) -> &str {
1447 self.prefix_str()
1448 }
1449}
1450
1451impl PrintWithSpace for hir::HeaderSafety {
1452 fn print_with_space(&self) -> &str {
1453 match self {
1454 hir::HeaderSafety::SafeTargetFeatures => "",
1455 hir::HeaderSafety::Normal(safety) => safety.print_with_space(),
1456 }
1457 }
1458}
1459
1460impl PrintWithSpace for hir::IsAsync {
1461 fn print_with_space(&self) -> &str {
1462 match self {
1463 hir::IsAsync::Async(_) => "async ",
1464 hir::IsAsync::NotAsync => "",
1465 }
1466 }
1467}
1468
1469impl PrintWithSpace for hir::Mutability {
1470 fn print_with_space(&self) -> &str {
1471 match self {
1472 hir::Mutability::Not => "",
1473 hir::Mutability::Mut => "mut ",
1474 }
1475 }
1476}
1477
1478pub(crate) fn print_constness_with_space(
1479 c: &hir::Constness,
1480 overall_stab: Option<StableSince>,
1481 const_stab: Option<ConstStability>,
1482) -> &'static str {
1483 match c {
1484 hir::Constness::Const => match (overall_stab, const_stab) {
1485 (_, Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }))
1487 | (_, None)
1489 | (None, Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => {
1491 "const "
1492 }
1493 (Some(_), Some(ConstStability { level: StabilityLevel::Unstable { .. }, .. })) => "",
1495 },
1496 hir::Constness::NotConst => "",
1498 }
1499}
1500
1501pub(crate) fn print_import(import: &clean::Import, cx: &Context<'_>) -> impl Display {
1502 fmt::from_fn(move |f| match import.kind {
1503 clean::ImportKind::Simple(name) => {
1504 if name == import.source.path.last() {
1505 write!(f, "use {};", print_import_source(&import.source, cx))
1506 } else {
1507 write!(
1508 f,
1509 "use {source} as {name};",
1510 source = print_import_source(&import.source, cx)
1511 )
1512 }
1513 }
1514 clean::ImportKind::Glob => {
1515 if import.source.path.segments.is_empty() {
1516 write!(f, "use *;")
1517 } else {
1518 write!(f, "use {}::*;", print_import_source(&import.source, cx))
1519 }
1520 }
1521 })
1522}
1523
1524fn print_import_source(import_source: &clean::ImportSource, cx: &Context<'_>) -> impl Display {
1525 fmt::from_fn(move |f| match import_source.did {
1526 Some(did) => resolved_path(f, did, &import_source.path, true, false, cx),
1527 _ => {
1528 for seg in &import_source.path.segments[..import_source.path.segments.len() - 1] {
1529 write!(f, "{}::", seg.name)?;
1530 }
1531 let name = import_source.path.last();
1532 if let hir::def::Res::PrimTy(p) = import_source.path.res {
1533 primitive_link(f, PrimitiveType::from(p), format_args!("{name}"), cx)?;
1534 } else {
1535 f.write_str(name.as_str())?;
1536 }
1537 Ok(())
1538 }
1539 })
1540}
1541
1542fn print_assoc_item_constraint(
1543 assoc_item_constraint: &clean::AssocItemConstraint,
1544 cx: &Context<'_>,
1545) -> impl Display {
1546 fmt::from_fn(move |f| {
1547 f.write_str(assoc_item_constraint.assoc.name.as_str())?;
1548 print_generic_args(&assoc_item_constraint.assoc.args, cx).fmt(f)?;
1549 match assoc_item_constraint.kind {
1550 clean::AssocItemConstraintKind::Equality { ref term } => {
1551 f.write_str(" = ")?;
1552 print_term(term, cx).fmt(f)?;
1553 }
1554 clean::AssocItemConstraintKind::Bound { ref bounds } => {
1555 if !bounds.is_empty() {
1556 f.write_str(": ")?;
1557 print_generic_bounds(bounds, cx).fmt(f)?;
1558 }
1559 }
1560 }
1561 Ok(())
1562 })
1563}
1564
1565pub(crate) fn print_abi_with_space(abi: ExternAbi) -> impl Display {
1566 fmt::from_fn(move |f| {
1567 let quot = if f.alternate() { "\"" } else { """ };
1568 match abi {
1569 ExternAbi::Rust => Ok(()),
1570 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1571 }
1572 })
1573}
1574
1575pub(crate) fn print_default_space(v: bool) -> &'static str {
1576 if v { "default " } else { "" }
1577}
1578
1579fn print_generic_arg(generic_arg: &clean::GenericArg, cx: &Context<'_>) -> impl Display {
1580 fmt::from_fn(move |f| match generic_arg {
1581 clean::GenericArg::Lifetime(lt) => f.write_str(print_lifetime(lt)),
1582 clean::GenericArg::Type(ty) => print_type(ty, cx).fmt(f),
1583 clean::GenericArg::Const(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1584 clean::GenericArg::Infer => f.write_char('_'),
1585 })
1586}
1587
1588fn print_term(term: &clean::Term, cx: &Context<'_>) -> impl Display {
1589 fmt::from_fn(move |f| match term {
1590 clean::Term::Type(ty) => print_type(ty, cx).fmt(f),
1591 clean::Term::Constant(ct) => print_constant_kind(ct, cx.tcx()).fmt(f),
1592 })
1593}