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