]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/html/format.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / src / librustdoc / html / format.rs
CommitLineData
1a4d82fc
JJ
1//! HTML formatting module
2//!
85aaf69f 3//! This module contains a large number of `fmt::Display` implementations for
353b0b11
FG
4//! various types in `rustdoc::clean`.
5//!
6//! These implementations all emit HTML. As an internal implementation detail,
7//! some of them support an alternate format that emits text, but that should
8//! not be used external to this module.
1a4d82fc 9
923072b8 10use std::borrow::Cow;
e1599b0c 11use std::cell::Cell;
353b0b11 12use std::fmt::{self, Write};
923072b8 13use std::iter::{self, once};
1a4d82fc 14
923072b8 15use rustc_ast as ast;
136023e0 16use rustc_attr::{ConstStability, StabilityLevel};
cdc7bbd5 17use rustc_data_structures::captures::Captures;
dfeec247
XL
18use rustc_data_structures::fx::FxHashSet;
19use rustc_hir as hir;
3c0e092e 20use rustc_hir::def::DefKind;
17df50a5 21use rustc_hir::def_id::DefId;
923072b8 22use rustc_metadata::creader::{CStore, LoadedMacro};
3c0e092e 23use rustc_middle::ty;
fc512014 24use rustc_middle::ty::TyCtxt;
04454e1e 25use rustc_span::symbol::kw;
5099ac24 26use rustc_span::{sym, Symbol};
83c7162d 27use rustc_target::spec::abi::Abi;
1a4d82fc 28
923072b8
FG
29use itertools::Itertools;
30
a2a8927a
XL
31use crate::clean::{
32 self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
33 PrimitiveType,
34};
3dfed10e 35use crate::formats::item_type::ItemType;
dfeec247 36use crate::html::escape::Escape;
cdc7bbd5 37use crate::html::render::Context;
9ffffee4 38use crate::passes::collect_intra_doc_links::UrlFragment;
e1599b0c 39
5099ac24 40use super::url_parts_builder::estimate_item_path_byte_length;
a2a8927a
XL
41use super::url_parts_builder::UrlPartsBuilder;
42
923072b8 43pub(crate) trait Print {
e1599b0c
XL
44 fn print(self, buffer: &mut Buffer);
45}
46
47impl<F> Print for F
dfeec247
XL
48where
49 F: FnOnce(&mut Buffer),
e1599b0c
XL
50{
51 fn print(self, buffer: &mut Buffer) {
52 (self)(buffer)
53 }
54}
55
56impl Print for String {
57 fn print(self, buffer: &mut Buffer) {
58 buffer.write_str(&self);
59 }
60}
61
62impl Print for &'_ str {
63 fn print(self, buffer: &mut Buffer) {
64 buffer.write_str(self);
65 }
66}
67
68#[derive(Debug, Clone)]
923072b8 69pub(crate) struct Buffer {
e1599b0c
XL
70 for_html: bool,
71 buffer: String,
72}
73
5099ac24
FG
74impl core::fmt::Write for Buffer {
75 #[inline]
76 fn write_str(&mut self, s: &str) -> fmt::Result {
77 self.buffer.write_str(s)
78 }
79
80 #[inline]
81 fn write_char(&mut self, c: char) -> fmt::Result {
82 self.buffer.write_char(c)
83 }
84
85 #[inline]
86 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
87 self.buffer.write_fmt(args)
88 }
89}
90
e1599b0c 91impl Buffer {
923072b8 92 pub(crate) fn empty_from(v: &Buffer) -> Buffer {
dfeec247 93 Buffer { for_html: v.for_html, buffer: String::new() }
e1599b0c
XL
94 }
95
923072b8 96 pub(crate) fn html() -> Buffer {
dfeec247 97 Buffer { for_html: true, buffer: String::new() }
e1599b0c
XL
98 }
99
923072b8 100 pub(crate) fn new() -> Buffer {
dfeec247 101 Buffer { for_html: false, buffer: String::new() }
60c5eb7d
XL
102 }
103
923072b8 104 pub(crate) fn is_empty(&self) -> bool {
3dfed10e
XL
105 self.buffer.is_empty()
106 }
107
923072b8 108 pub(crate) fn into_inner(self) -> String {
e1599b0c
XL
109 self.buffer
110 }
111
923072b8 112 pub(crate) fn push_str(&mut self, s: &str) {
3dfed10e
XL
113 self.buffer.push_str(s);
114 }
115
923072b8 116 pub(crate) fn push_buffer(&mut self, other: Buffer) {
cdc7bbd5
XL
117 self.buffer.push_str(&other.buffer);
118 }
119
e1599b0c
XL
120 // Intended for consumption by write! and writeln! (std::fmt) but without
121 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
122 // import).
923072b8 123 pub(crate) fn write_str(&mut self, s: &str) {
e1599b0c
XL
124 self.buffer.push_str(s);
125 }
126
127 // Intended for consumption by write! and writeln! (std::fmt) but without
128 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
129 // import).
923072b8 130 pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
e1599b0c
XL
131 self.buffer.write_fmt(v).unwrap();
132 }
133
923072b8 134 pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
e1599b0c
XL
135 t.print(&mut self);
136 self.into_inner()
137 }
138
923072b8 139 pub(crate) fn reserve(&mut self, additional: usize) {
cdc7bbd5
XL
140 self.buffer.reserve(additional)
141 }
064997fb
FG
142
143 pub(crate) fn len(&self) -> usize {
144 self.buffer.len()
145 }
cc61c64b
XL
146}
147
f2b60f7d 148pub(crate) fn comma_sep<T: fmt::Display>(
5e7ed085
FG
149 items: impl Iterator<Item = T>,
150 space_after_comma: bool,
151) -> impl fmt::Display {
e1599b0c 152 display_fn(move |f| {
e74abb32 153 for (i, item) in items.enumerate() {
dfeec247 154 if i != 0 {
5e7ed085 155 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
dfeec247 156 }
e74abb32 157 fmt::Display::fmt(&item, f)?;
1a4d82fc
JJ
158 }
159 Ok(())
e1599b0c 160 })
1a4d82fc
JJ
161}
162
923072b8 163pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
5869c6ff 164 bounds: &'a [clean::GenericBound],
cdc7bbd5
XL
165 cx: &'a Context<'tcx>,
166) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32 167 display_fn(move |f| {
dc9dc135 168 let mut bounds_dup = FxHashSet::default();
dc9dc135 169
a2a8927a 170 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
1a4d82fc 171 if i > 0 {
54a0048b 172 f.write_str(" + ")?;
1a4d82fc 173 }
cdc7bbd5 174 fmt::Display::fmt(&bound.print(cx), f)?;
1a4d82fc
JJ
175 }
176 Ok(())
e74abb32 177 })
1a4d82fc
JJ
178}
179
e74abb32 180impl clean::GenericParamDef {
923072b8 181 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
182 &'a self,
183 cx: &'a Context<'tcx>,
184 ) -> impl fmt::Display + 'a + Captures<'tcx> {
c295e0f8
XL
185 display_fn(move |f| match &self.kind {
186 clean::GenericParamDefKind::Lifetime { outlives } => {
187 write!(f, "{}", self.name)?;
188
189 if !outlives.is_empty() {
190 f.write_str(": ")?;
191 for (i, lt) in outlives.iter().enumerate() {
192 if i != 0 {
193 f.write_str(" + ")?;
194 }
195 write!(f, "{}", lt.print())?;
196 }
197 }
198
199 Ok(())
200 }
201 clean::GenericParamDefKind::Type { bounds, default, .. } => {
a2a8927a 202 f.write_str(self.name.as_str())?;
1a4d82fc 203
dfeec247
XL
204 if !bounds.is_empty() {
205 if f.alternate() {
cdc7bbd5 206 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
dfeec247 207 } else {
9ffffee4 208 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
c30ab7b3 209 }
1a4d82fc
JJ
210 }
211
dfeec247 212 if let Some(ref ty) = default {
c30ab7b3 213 if f.alternate() {
cdc7bbd5 214 write!(f, " = {:#}", ty.print(cx))?;
c30ab7b3 215 } else {
9ffffee4 216 write!(f, " = {}", ty.print(cx))?;
c30ab7b3 217 }
ff7c6d11 218 }
dfeec247
XL
219
220 Ok(())
221 }
c295e0f8 222 clean::GenericParamDefKind::Const { ty, default, .. } => {
dfeec247 223 if f.alternate() {
17df50a5 224 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
dfeec247 225 } else {
9ffffee4 226 write!(f, "const {}: {}", self.name, ty.print(cx))?;
dfeec247 227 }
17df50a5
XL
228
229 if let Some(default) = default {
230 if f.alternate() {
231 write!(f, " = {:#}", default)?;
232 } else {
9ffffee4 233 write!(f, " = {}", default)?;
17df50a5
XL
234 }
235 }
236
237 Ok(())
1a4d82fc 238 }
e74abb32 239 })
ff7c6d11
XL
240 }
241}
242
e74abb32 243impl clean::Generics {
923072b8 244 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
245 &'a self,
246 cx: &'a Context<'tcx>,
247 ) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32 248 display_fn(move |f| {
a2a8927a
XL
249 let mut real_params =
250 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
251 if real_params.peek().is_none() {
e74abb32
XL
252 return Ok(());
253 }
a2a8927a 254
e74abb32 255 if f.alternate() {
5e7ed085 256 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
e74abb32 257 } else {
5e7ed085 258 write!(f, "&lt;{}&gt;", comma_sep(real_params.map(|g| g.print(cx)), true))
e74abb32
XL
259 }
260 })
1a4d82fc
JJ
261 }
262}
263
064997fb
FG
264#[derive(Clone, Copy, PartialEq, Eq)]
265pub(crate) enum Ending {
266 Newline,
267 NoNewline,
268}
269
cdc7bbd5
XL
270/// * The Generics from which to emit a where-clause.
271/// * The number of spaces to indent each line with.
272/// * Whether the where-clause needs to add a comma and newline after the last bound.
923072b8 273pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
cdc7bbd5
XL
274 gens: &'a clean::Generics,
275 cx: &'a Context<'tcx>,
276 indent: usize,
064997fb 277 ending: Ending,
cdc7bbd5
XL
278) -> impl fmt::Display + 'a + Captures<'tcx> {
279 display_fn(move |f| {
5e7ed085
FG
280 let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
281 !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
282 }).map(|pred| {
283 display_fn(move |f| {
284 if f.alternate() {
285 f.write_str(" ")?;
286 } else {
9ffffee4 287 f.write_str("\n")?;
5e7ed085
FG
288 }
289
290 match pred {
291 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
04454e1e
FG
292 let ty_cx = ty.print(cx);
293 let generic_bounds = print_generic_bounds(bounds, cx);
5e7ed085 294
04454e1e
FG
295 if bound_params.is_empty() {
296 if f.alternate() {
297 write!(f, "{ty_cx:#}: {generic_bounds:#}")
298 } else {
299 write!(f, "{ty_cx}: {generic_bounds}")
300 }
5e7ed085 301 } else {
04454e1e
FG
302 if f.alternate() {
303 write!(
304 f,
305 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
353b0b11 306 comma_sep(bound_params.iter().map(|lt| lt.print(cx)), true)
04454e1e
FG
307 )
308 } else {
309 write!(
310 f,
311 "for&lt;{}&gt; {ty_cx}: {generic_bounds}",
353b0b11 312 comma_sep(bound_params.iter().map(|lt| lt.print(cx)), true)
04454e1e
FG
313 )
314 }
5e7ed085
FG
315 }
316 }
317 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
04454e1e
FG
318 let mut bounds_display = String::new();
319 for bound in bounds.iter().map(|b| b.print(cx)) {
320 write!(bounds_display, "{bound} + ")?;
321 }
322 bounds_display.truncate(bounds_display.len() - " + ".len());
323 write!(f, "{}: {bounds_display}", lifetime.print())
5e7ed085 324 }
2b03887a
FG
325 // FIXME(fmease): Render bound params.
326 clean::WherePredicate::EqPredicate { lhs, rhs, bound_params: _ } => {
5e7ed085 327 if f.alternate() {
04454e1e 328 write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
5e7ed085 329 } else {
04454e1e 330 write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
5e7ed085
FG
331 }
332 }
333 }
334 })
335 }).peekable();
336
337 if where_predicates.peek().is_none() {
cdc7bbd5
XL
338 return Ok(());
339 }
5e7ed085 340
04454e1e
FG
341 let where_preds = comma_sep(where_predicates, false);
342 let clause = if f.alternate() {
064997fb 343 if ending == Ending::Newline {
f2b60f7d 344 format!(" where{where_preds},")
cdc7bbd5 345 } else {
04454e1e 346 format!(" where{where_preds}")
cc61c64b 347 }
04454e1e
FG
348 } else {
349 let mut br_with_padding = String::with_capacity(6 * indent + 28);
9ffffee4
FG
350 br_with_padding.push_str("\n");
351
353b0b11 352 let padding_amount =
9ffffee4
FG
353 if ending == Ending::Newline { indent + 4 } else { indent + "fn where ".len() };
354
353b0b11 355 for _ in 0..padding_amount {
9ffffee4 356 br_with_padding.push_str(" ");
cc61c64b 357 }
9ffffee4 358 let where_preds = where_preds.to_string().replace('\n', &br_with_padding);
cc61c64b 359
064997fb 360 if ending == Ending::Newline {
9ffffee4 361 let mut clause = " ".repeat(indent.saturating_sub(1));
f2b60f7d 362 write!(clause, "<span class=\"where fmt-newline\">where{where_preds},</span>")?;
04454e1e
FG
363 clause
364 } else {
9ffffee4 365 // insert a newline after a single space but before multiple spaces at the start
04454e1e 366 if indent == 0 {
9ffffee4 367 format!("\n<span class=\"where\">where{where_preds}</span>")
04454e1e 368 } else {
9ffffee4
FG
369 // put the first one on the same line as the 'where' keyword
370 let where_preds = where_preds.replacen(&br_with_padding, " ", 1);
371
04454e1e 372 let mut clause = br_with_padding;
9ffffee4
FG
373 clause.truncate(clause.len() - "where ".len());
374
f2b60f7d 375 write!(clause, "<span class=\"where\">where{where_preds}</span>")?;
04454e1e
FG
376 clause
377 }
476ff2be 378 }
04454e1e
FG
379 };
380 write!(f, "{clause}")
cdc7bbd5 381 })
1a4d82fc
JJ
382}
383
e74abb32 384impl clean::Lifetime {
923072b8 385 pub(crate) fn print(&self) -> impl fmt::Display + '_ {
a2a8927a 386 self.0.as_str()
1a4d82fc
JJ
387 }
388}
389
e74abb32 390impl clean::Constant {
923072b8 391 pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
cdc7bbd5
XL
392 let expr = self.expr(tcx);
393 display_fn(
394 move |f| {
395 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
396 },
397 )
532ac7d7
XL
398 }
399}
400
e74abb32 401impl clean::PolyTrait {
cdc7bbd5
XL
402 fn print<'a, 'tcx: 'a>(
403 &'a self,
404 cx: &'a Context<'tcx>,
405 ) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32
XL
406 display_fn(move |f| {
407 if !self.generic_params.is_empty() {
408 if f.alternate() {
dfeec247
XL
409 write!(
410 f,
411 "for<{:#}> ",
5e7ed085 412 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
dfeec247 413 )?;
e74abb32 414 } else {
dfeec247
XL
415 write!(
416 f,
417 "for&lt;{}&gt; ",
5e7ed085 418 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
dfeec247 419 )?;
e74abb32
XL
420 }
421 }
c30ab7b3 422 if f.alternate() {
cdc7bbd5 423 write!(f, "{:#}", self.trait_.print(cx))
c30ab7b3 424 } else {
cdc7bbd5 425 write!(f, "{}", self.trait_.print(cx))
c30ab7b3 426 }
e74abb32 427 })
1a4d82fc
JJ
428 }
429}
430
e74abb32 431impl clean::GenericBound {
923072b8 432 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
433 &'a self,
434 cx: &'a Context<'tcx>,
435 ) -> impl fmt::Display + 'a + Captures<'tcx> {
dfeec247
XL
436 display_fn(move |f| match self {
437 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
438 clean::GenericBound::TraitBound(ty, modifier) => {
439 let modifier_str = match modifier {
440 hir::TraitBoundModifier::None => "",
441 hir::TraitBoundModifier::Maybe => "?",
5e7ed085
FG
442 // ~const is experimental; do not display those bounds in rustdoc
443 hir::TraitBoundModifier::MaybeConst => "",
dfeec247
XL
444 };
445 if f.alternate() {
cdc7bbd5 446 write!(f, "{}{:#}", modifier_str, ty.print(cx))
dfeec247 447 } else {
cdc7bbd5 448 write!(f, "{}{}", modifier_str, ty.print(cx))
c30ab7b3 449 }
1a4d82fc 450 }
e74abb32 451 })
1a4d82fc
JJ
452 }
453}
454
e74abb32 455impl clean::GenericArgs {
cdc7bbd5
XL
456 fn print<'a, 'tcx: 'a>(
457 &'a self,
458 cx: &'a Context<'tcx>,
459 ) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32 460 display_fn(move |f| {
5869c6ff
XL
461 match self {
462 clean::GenericArgs::AngleBracketed { args, bindings } => {
e74abb32
XL
463 if !args.is_empty() || !bindings.is_empty() {
464 if f.alternate() {
465 f.write_str("<")?;
466 } else {
467 f.write_str("&lt;")?;
468 }
469 let mut comma = false;
923072b8 470 for arg in args.iter() {
e74abb32
XL
471 if comma {
472 f.write_str(", ")?;
473 }
474 comma = true;
475 if f.alternate() {
cdc7bbd5 476 write!(f, "{:#}", arg.print(cx))?;
e74abb32 477 } else {
cdc7bbd5 478 write!(f, "{}", arg.print(cx))?;
e74abb32
XL
479 }
480 }
923072b8 481 for binding in bindings.iter() {
e74abb32
XL
482 if comma {
483 f.write_str(", ")?;
484 }
485 comma = true;
486 if f.alternate() {
cdc7bbd5 487 write!(f, "{:#}", binding.print(cx))?;
e74abb32 488 } else {
cdc7bbd5 489 write!(f, "{}", binding.print(cx))?;
e74abb32 490 }
1a4d82fc 491 }
c30ab7b3 492 if f.alternate() {
e74abb32 493 f.write_str(">")?;
c30ab7b3 494 } else {
e74abb32 495 f.write_str("&gt;")?;
c30ab7b3 496 }
1a4d82fc 497 }
e74abb32 498 }
5869c6ff 499 clean::GenericArgs::Parenthesized { inputs, output } => {
e74abb32
XL
500 f.write_str("(")?;
501 let mut comma = false;
923072b8 502 for ty in inputs.iter() {
1a4d82fc 503 if comma {
c30ab7b3 504 f.write_str(", ")?;
1a4d82fc
JJ
505 }
506 comma = true;
c30ab7b3 507 if f.alternate() {
cdc7bbd5 508 write!(f, "{:#}", ty.print(cx))?;
c30ab7b3 509 } else {
cdc7bbd5 510 write!(f, "{}", ty.print(cx))?;
c30ab7b3
SL
511 }
512 }
e74abb32
XL
513 f.write_str(")")?;
514 if let Some(ref ty) = *output {
515 if f.alternate() {
cdc7bbd5 516 write!(f, " -> {:#}", ty.print(cx))?;
e74abb32 517 } else {
cdc7bbd5 518 write!(f, " -&gt; {}", ty.print(cx))?;
e74abb32 519 }
c30ab7b3 520 }
1a4d82fc
JJ
521 }
522 }
e74abb32
XL
523 Ok(())
524 })
1a4d82fc
JJ
525 }
526}
527
136023e0 528// Possible errors when computing href link source for a `DefId`
923072b8
FG
529#[derive(PartialEq, Eq)]
530pub(crate) enum HrefError {
136023e0
XL
531 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
532 ///
533 /// This can only happen for non-local items.
04454e1e
FG
534 ///
535 /// # Example
536 ///
537 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
538 /// implements it for a local type.
539 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
540 ///
541 /// ```sh
542 /// rustc a.rs --crate-type=lib
543 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
544 /// ```
545 ///
546 /// Now, the associated items in the trait impl want to link to the corresponding item in the
547 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
548 /// *documentation (was) not built*.
136023e0
XL
549 DocumentationNotBuilt,
550 /// This can only happen for non-local items when `--document-private-items` is not passed.
551 Private,
552 // Not in external cache, href link should be in same page
553 NotInExternalCache,
554}
555
5099ac24 556// Panics if `syms` is empty.
923072b8 557pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
5099ac24 558 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
923072b8 559 s.push_str(syms[0].as_str());
5099ac24
FG
560 for sym in &syms[1..] {
561 s.push_str("::");
923072b8 562 s.push_str(sym.as_str());
5099ac24
FG
563 }
564 s
565}
566
923072b8
FG
567/// This function is to get the external macro path because they are not in the cache used in
568/// `href_with_root_path`.
569fn generate_macro_def_id_path(
570 def_id: DefId,
571 cx: &Context<'_>,
572 root_path: Option<&str>,
573) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
574 let tcx = cx.shared.tcx;
9c376795 575 let crate_name = tcx.crate_name(def_id.krate);
923072b8
FG
576 let cache = cx.cache();
577
578 let fqp: Vec<Symbol> = tcx
579 .def_path(def_id)
580 .data
581 .into_iter()
582 .filter_map(|elem| {
583 // extern blocks (and a few others things) have an empty name.
584 match elem.data.get_opt_name() {
585 Some(s) if !s.is_empty() => Some(s),
586 _ => None,
587 }
588 })
589 .collect();
9c376795 590 let mut relative = fqp.iter().copied();
923072b8
FG
591 let cstore = CStore::from_tcx(tcx);
592 // We need this to prevent a `panic` when this function is used from intra doc links...
593 if !cstore.has_crate_data(def_id.krate) {
594 debug!("No data for crate {}", crate_name);
595 return Err(HrefError::NotInExternalCache);
596 }
597 // Check to see if it is a macro 2.0 or built-in macro.
598 // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
599 let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
600 LoadedMacro::MacroDef(def, _) => {
601 // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
602 matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
603 }
604 _ => false,
605 };
606
607 let mut path = if is_macro_2 {
9c376795 608 once(crate_name).chain(relative).collect()
923072b8 609 } else {
9c376795 610 vec![crate_name, relative.next_back().unwrap()]
923072b8
FG
611 };
612 if path.len() < 2 {
613 // The minimum we can have is the crate name followed by the macro name. If shorter, then
2b03887a 614 // it means that `relative` was empty, which is an error.
923072b8
FG
615 debug!("macro path cannot be empty!");
616 return Err(HrefError::NotInExternalCache);
617 }
618
619 if let Some(last) = path.last_mut() {
9c376795 620 *last = Symbol::intern(&format!("macro.{}.html", last.as_str()));
923072b8
FG
621 }
622
623 let url = match cache.extern_locations[&def_id.krate] {
624 ExternalLocation::Remote(ref s) => {
625 // `ExternalLocation::Remote` always end with a `/`.
9c376795 626 format!("{}{}", s, path.iter().map(|p| p.as_str()).join("/"))
923072b8
FG
627 }
628 ExternalLocation::Local => {
629 // `root_path` always end with a `/`.
9c376795
FG
630 format!(
631 "{}{}/{}",
632 root_path.unwrap_or(""),
633 crate_name,
634 path.iter().map(|p| p.as_str()).join("/")
635 )
923072b8
FG
636 }
637 ExternalLocation::Unknown => {
638 debug!("crate {} not in cache when linkifying macros", crate_name);
639 return Err(HrefError::NotInExternalCache);
640 }
641 };
642 Ok((url, ItemType::Macro, fqp))
643}
644
645pub(crate) fn href_with_root_path(
94222f64
XL
646 did: DefId,
647 cx: &Context<'_>,
648 root_path: Option<&str>,
5099ac24 649) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
3c0e092e
XL
650 let tcx = cx.tcx();
651 let def_kind = tcx.def_kind(did);
652 let did = match def_kind {
653 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
654 // documented on their parent's page
04454e1e 655 tcx.parent(did)
3c0e092e
XL
656 }
657 _ => did,
658 };
659 let cache = cx.cache();
cdc7bbd5 660 let relative_to = &cx.current;
5099ac24 661 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
94222f64 662 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
1a4d82fc 663 }
1a4d82fc 664
c295e0f8 665 if !did.is_local()
487cf647 666 && !cache.effective_visibilities.is_directly_public(tcx, did)
c295e0f8
XL
667 && !cache.document_private
668 && !cache.primitive_locations.values().any(|&id| id == did)
669 {
136023e0 670 return Err(HrefError::Private);
a7813a04
XL
671 }
672
94222f64 673 let mut is_remote = false;
cdc7bbd5
XL
674 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
675 Some(&(ref fqp, shortty)) => (fqp, shortty, {
5099ac24 676 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
c295e0f8 677 debug!(?fqp, ?shortty, ?module_fqp);
5099ac24 678 href_relative_parts(module_fqp, relative_to).collect()
cdc7bbd5 679 }),
ff7c6d11 680 None => {
136023e0
XL
681 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
682 let module_fqp = to_module_fqp(shortty, fqp);
683 (
684 fqp,
685 shortty,
686 match cache.extern_locations[&did.krate] {
687 ExternalLocation::Remote(ref s) => {
94222f64 688 is_remote = true;
136023e0 689 let s = s.trim_end_matches('/');
a2a8927a 690 let mut builder = UrlPartsBuilder::singleton(s);
5099ac24 691 builder.extend(module_fqp.iter().copied());
a2a8927a 692 builder
136023e0 693 }
5099ac24
FG
694 ExternalLocation::Local => {
695 href_relative_parts(module_fqp, relative_to).collect()
696 }
136023e0
XL
697 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
698 },
699 )
923072b8
FG
700 } else if matches!(def_kind, DefKind::Macro(_)) {
701 return generate_macro_def_id_path(did, cx, root_path);
136023e0
XL
702 } else {
703 return Err(HrefError::NotInExternalCache);
704 }
9346a6ac
AL
705 }
706 };
9ffffee4
FG
707 if !is_remote && let Some(root_path) = root_path {
708 let root = root_path.trim_end_matches('/');
709 url_parts.push_front(root);
94222f64 710 }
c295e0f8 711 debug!(?url_parts);
9346a6ac
AL
712 match shortty {
713 ItemType::Module => {
cdc7bbd5 714 url_parts.push("index.html");
9346a6ac
AL
715 }
716 _ => {
5099ac24
FG
717 let prefix = shortty.as_str();
718 let last = fqp.last().unwrap();
719 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
9346a6ac
AL
720 }
721 }
a2a8927a 722 Ok((url_parts.finish(), shortty, fqp.to_vec()))
cdc7bbd5
XL
723}
724
923072b8
FG
725pub(crate) fn href(
726 did: DefId,
727 cx: &Context<'_>,
728) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
94222f64
XL
729 href_with_root_path(did, cx, None)
730}
731
cdc7bbd5
XL
732/// Both paths should only be modules.
733/// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
734/// both need `../iter/trait.Iterator.html` to get at the iterator trait.
923072b8 735pub(crate) fn href_relative_parts<'fqp>(
5099ac24
FG
736 fqp: &'fqp [Symbol],
737 relative_to_fqp: &[Symbol],
738) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
cdc7bbd5
XL
739 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
740 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
741 if f != r {
742 let dissimilar_part_count = relative_to_fqp.len() - i;
5099ac24 743 let fqp_module = &fqp[i..fqp.len()];
064997fb
FG
744 return Box::new(
745 iter::repeat(sym::dotdot)
746 .take(dissimilar_part_count)
747 .chain(fqp_module.iter().copied()),
748 );
cdc7bbd5
XL
749 }
750 }
751 // e.g. linking to std::sync::atomic from std::sync
752 if relative_to_fqp.len() < fqp.len() {
064997fb 753 Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
cdc7bbd5
XL
754 // e.g. linking to std::sync from std::sync::atomic
755 } else if fqp.len() < relative_to_fqp.len() {
756 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
064997fb 757 Box::new(iter::repeat(sym::dotdot).take(dissimilar_part_count))
cdc7bbd5
XL
758 // linking to the same module
759 } else {
064997fb 760 Box::new(iter::empty())
cdc7bbd5 761 }
9346a6ac
AL
762}
763
9ffffee4
FG
764pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Context<'_>) -> String {
765 let cache = cx.cache();
766 let Some((fqp, shortty)) = cache.paths.get(&did)
767 .or_else(|| cache.external_paths.get(&did))
768 else { return String::new() };
769 let mut buf = Buffer::new();
353b0b11
FG
770 let fqp = if *shortty == ItemType::Primitive {
771 // primitives are documented in a crate, but not actually part of it
772 &fqp[fqp.len() - 1..]
773 } else {
774 &fqp
775 };
9ffffee4
FG
776 if let &Some(UrlFragment::Item(id)) = fragment {
777 write!(buf, "{} ", cx.tcx().def_descr(id));
778 for component in fqp {
779 write!(buf, "{component}::");
780 }
781 write!(buf, "{}", cx.tcx().item_name(id));
782 } else if !fqp.is_empty() {
783 let mut fqp_it = fqp.into_iter();
784 write!(buf, "{shortty} {}", fqp_it.next().unwrap());
785 for component in fqp_it {
786 write!(buf, "::{component}");
787 }
788 }
789 buf.into_inner()
790}
791
3c0e092e
XL
792/// Used to render a [`clean::Path`].
793fn resolved_path<'cx>(
dfeec247
XL
794 w: &mut fmt::Formatter<'_>,
795 did: DefId,
796 path: &clean::Path,
797 print_all: bool,
798 use_absolute: bool,
cdc7bbd5 799 cx: &'cx Context<'_>,
dfeec247 800) -> fmt::Result {
041b39d2 801 let last = path.segments.last().unwrap();
1a4d82fc
JJ
802
803 if print_all {
ff7c6d11 804 for seg in &path.segments[..path.segments.len() - 1] {
04454e1e 805 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
1a4d82fc
JJ
806 }
807 }
c30ab7b3 808 if w.alternate() {
cdc7bbd5 809 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
c30ab7b3 810 } else {
7cac9316 811 let path = if use_absolute {
136023e0 812 if let Ok((_, _, fqp)) = href(did, cx) {
5869c6ff
XL
813 format!(
814 "{}::{}",
5099ac24
FG
815 join_with_double_colon(&fqp[..fqp.len() - 1]),
816 anchor(did, *fqp.last().unwrap(), cx)
5869c6ff 817 )
e1599b0c
XL
818 } else {
819 last.name.to_string()
7cac9316 820 }
32a655c1 821 } else {
5099ac24 822 anchor(did, last.name, cx).to_string()
7cac9316 823 };
cdc7bbd5 824 write!(w, "{}{}", path, last.args.print(cx))?;
c30ab7b3 825 }
1a4d82fc
JJ
826 Ok(())
827}
828
dfeec247
XL
829fn primitive_link(
830 f: &mut fmt::Formatter<'_>,
831 prim: clean::PrimitiveType,
832 name: &str,
cdc7bbd5 833 cx: &Context<'_>,
923072b8
FG
834) -> fmt::Result {
835 primitive_link_fragment(f, prim, name, "", cx)
836}
837
838fn primitive_link_fragment(
839 f: &mut fmt::Formatter<'_>,
840 prim: clean::PrimitiveType,
841 name: &str,
842 fragment: &str,
843 cx: &Context<'_>,
dfeec247 844) -> fmt::Result {
cdc7bbd5 845 let m = &cx.cache();
1a4d82fc 846 let mut needs_termination = false;
c30ab7b3
SL
847 if !f.alternate() {
848 match m.primitive_locations.get(&prim) {
476ff2be 849 Some(&def_id) if def_id.is_local() => {
cdc7bbd5 850 let len = cx.current.len();
dfeec247
XL
851 let len = if len == 0 { 0 } else { len - 1 };
852 write!(
853 f,
923072b8 854 "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
dfeec247 855 "../".repeat(len),
17df50a5 856 prim.as_sym()
dfeec247 857 )?;
3157f602 858 needs_termination = true;
1a4d82fc 859 }
476ff2be
SL
860 Some(&def_id) => {
861 let loc = match m.extern_locations[&def_id.krate] {
17df50a5 862 ExternalLocation::Remote(ref s) => {
5099ac24
FG
863 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
864 let builder: UrlPartsBuilder =
865 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
866 .into_iter()
867 .collect();
868 Some(builder)
cdc7bbd5 869 }
17df50a5 870 ExternalLocation::Local => {
5099ac24
FG
871 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
872 Some(if cx.current.first() == Some(&cname_sym) {
873 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
cdc7bbd5 874 } else {
5099ac24
FG
875 iter::repeat(sym::dotdot)
876 .take(cx.current.len())
877 .chain(iter::once(cname_sym))
878 .collect()
cdc7bbd5 879 })
c30ab7b3 880 }
17df50a5 881 ExternalLocation::Unknown => None,
c30ab7b3 882 };
5099ac24
FG
883 if let Some(mut loc) = loc {
884 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
923072b8 885 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
c30ab7b3
SL
886 needs_termination = true;
887 }
888 }
889 None => {}
1a4d82fc 890 }
1a4d82fc 891 }
54a0048b 892 write!(f, "{}", name)?;
1a4d82fc 893 if needs_termination {
54a0048b 894 write!(f, "</a>")?;
1a4d82fc
JJ
895 }
896 Ok(())
897}
898
899/// Helper to render type parameters
cdc7bbd5 900fn tybounds<'a, 'tcx: 'a>(
3c0e092e 901 bounds: &'a [clean::PolyTrait],
136023e0 902 lt: &'a Option<clean::Lifetime>,
cdc7bbd5
XL
903 cx: &'a Context<'tcx>,
904) -> impl fmt::Display + 'a + Captures<'tcx> {
136023e0
XL
905 display_fn(move |f| {
906 for (i, bound) in bounds.iter().enumerate() {
907 if i > 0 {
dfeec247 908 write!(f, " + ")?;
1a4d82fc 909 }
136023e0
XL
910
911 fmt::Display::fmt(&bound.print(cx), f)?;
1a4d82fc 912 }
136023e0
XL
913
914 if let Some(lt) = lt {
915 write!(f, " + ")?;
916 fmt::Display::fmt(&lt.print(), f)?;
917 }
918 Ok(())
e1599b0c 919 })
a7813a04
XL
920}
921
923072b8 922pub(crate) fn anchor<'a, 'cx: 'a>(
cdc7bbd5 923 did: DefId,
5099ac24 924 text: Symbol,
cdc7bbd5
XL
925 cx: &'cx Context<'_>,
926) -> impl fmt::Display + 'a {
94222f64 927 let parts = href(did, cx);
e1599b0c 928 display_fn(move |f| {
136023e0 929 if let Ok((url, short_ty, fqp)) = parts {
dfeec247
XL
930 write!(
931 f,
932 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
933 short_ty,
934 url,
935 short_ty,
5099ac24
FG
936 join_with_double_colon(&fqp),
937 text.as_str()
dfeec247 938 )
e1599b0c
XL
939 } else {
940 write!(f, "{}", text)
a7813a04 941 }
e1599b0c 942 })
a7813a04
XL
943}
944
cdc7bbd5 945fn fmt_type<'cx>(
5869c6ff
XL
946 t: &clean::Type,
947 f: &mut fmt::Formatter<'_>,
948 use_absolute: bool,
cdc7bbd5 949 cx: &'cx Context<'_>,
5869c6ff 950) -> fmt::Result {
c295e0f8 951 trace!("fmt_type(t = {:?})", t);
5869c6ff 952
32a655c1 953 match *t {
fc512014 954 clean::Generic(name) => write!(f, "{}", name),
3c0e092e 955 clean::Type::Path { ref path } => {
dc9dc135 956 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
3c0e092e 957 let did = path.def_id();
c295e0f8 958 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
136023e0
XL
959 }
960 clean::DynTrait(ref bounds, ref lt) => {
961 f.write_str("dyn ")?;
962 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
32a655c1
SL
963 }
964 clean::Infer => write!(f, "_"),
c295e0f8
XL
965 clean::Primitive(clean::PrimitiveType::Never) => {
966 primitive_link(f, PrimitiveType::Never, "!", cx)
967 }
a2a8927a 968 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
32a655c1
SL
969 clean::BareFunction(ref decl) => {
970 if f.alternate() {
dfeec247
XL
971 write!(
972 f,
5869c6ff 973 "{:#}{}{:#}fn{:#}",
cdc7bbd5 974 decl.print_hrtb_with_space(cx),
dfeec247
XL
975 decl.unsafety.print_with_space(),
976 print_abi_with_space(decl.abi),
cdc7bbd5 977 decl.decl.print(cx),
dfeec247 978 )
32a655c1 979 } else {
dfeec247
XL
980 write!(
981 f,
5869c6ff 982 "{}{}{}",
cdc7bbd5 983 decl.print_hrtb_with_space(cx),
dfeec247
XL
984 decl.unsafety.print_with_space(),
985 print_abi_with_space(decl.abi)
986 )?;
cdc7bbd5
XL
987 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
988 write!(f, "{}", decl.decl.print(cx))
32a655c1
SL
989 }
990 }
991 clean::Tuple(ref typs) => {
992 match &typs[..] {
cdc7bbd5 993 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
9c376795 994 [one] => {
923072b8
FG
995 if let clean::Generic(name) = one {
996 primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
997 } else {
998 write!(f, "(")?;
999 // Carry `f.alternate()` into this display w/o branching manually.
1000 fmt::Display::fmt(&one.print(cx), f)?;
1001 write!(f, ",)")
1002 }
c30ab7b3 1003 }
7cac9316 1004 many => {
923072b8
FG
1005 let generic_names: Vec<Symbol> = many
1006 .iter()
1007 .filter_map(|t| match t {
1008 clean::Generic(name) => Some(*name),
1009 _ => None,
1010 })
1011 .collect();
1012 let is_generic = generic_names.len() == many.len();
1013 if is_generic {
1014 primitive_link(
1015 f,
1016 PrimitiveType::Tuple,
1017 &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
1018 cx,
1019 )
1020 } else {
1021 write!(f, "(")?;
1022 for (i, item) in many.iter().enumerate() {
1023 if i != 0 {
1024 write!(f, ", ")?;
1025 }
1026 // Carry `f.alternate()` into this display w/o branching manually.
1027 fmt::Display::fmt(&item.print(cx), f)?;
dfeec247 1028 }
923072b8 1029 write!(f, ")")
e74abb32 1030 }
7453a54e 1031 }
1a4d82fc 1032 }
32a655c1 1033 }
923072b8
FG
1034 clean::Slice(ref t) => match **t {
1035 clean::Generic(name) => {
1036 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1037 }
1038 _ => {
1039 write!(f, "[")?;
1040 fmt::Display::fmt(&t.print(cx), f)?;
1041 write!(f, "]")
1042 }
1043 },
2b03887a
FG
1044 clean::Array(ref t, ref n) => match **t {
1045 clean::Generic(name) if !f.alternate() => primitive_link(
1046 f,
1047 PrimitiveType::Array,
1048 &format!("[{name}; {n}]", n = Escape(n)),
1049 cx,
1050 ),
1051 _ => {
1052 write!(f, "[")?;
1053 fmt::Display::fmt(&t.print(cx), f)?;
1054 if f.alternate() {
1055 write!(f, "; {n}")?;
1056 } else {
1057 write!(f, "; ")?;
1058 primitive_link(f, PrimitiveType::Array, &format!("{n}", n = Escape(n)), cx)?;
1059 }
1060 write!(f, "]")
dfeec247 1061 }
2b03887a 1062 },
32a655c1 1063 clean::RawPointer(m, ref t) => {
e1599b0c 1064 let m = match m {
dfeec247
XL
1065 hir::Mutability::Mut => "mut",
1066 hir::Mutability::Not => "const",
e1599b0c 1067 };
c295e0f8
XL
1068
1069 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1070 let text = if f.alternate() {
1071 format!("*{} {:#}", m, t.print(cx))
1072 } else {
1073 format!("*{} {}", m, t.print(cx))
1074 };
1075 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1076 } else {
1077 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1078 fmt::Display::fmt(&t.print(cx), f)
1a4d82fc 1079 }
32a655c1 1080 }
dfeec247 1081 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
e74abb32
XL
1082 let lt = match l {
1083 Some(l) => format!("{} ", l.print()),
dfeec247 1084 _ => String::new(),
32a655c1 1085 };
e74abb32 1086 let m = mutability.print_with_space();
9c376795 1087 let amp = if f.alternate() { "&" } else { "&amp;" };
32a655c1 1088 match **ty {
136023e0
XL
1089 clean::DynTrait(ref bounds, ref trait_lt)
1090 if bounds.len() > 1 || trait_lt.is_some() =>
1091 {
3b2f2976 1092 write!(f, "{}{}{}(", amp, lt, m)?;
3c0e092e 1093 fmt_type(ty, f, use_absolute, cx)?;
7cac9316
XL
1094 write!(f, ")")
1095 }
9ffffee4
FG
1096 clean::Generic(name) => {
1097 primitive_link(f, PrimitiveType::Reference, &format!("{amp}{lt}{m}{name}"), cx)
3b2f2976 1098 }
32a655c1 1099 _ => {
3b2f2976 1100 write!(f, "{}{}{}", amp, lt, m)?;
3c0e092e 1101 fmt_type(ty, f, use_absolute, cx)
1a4d82fc 1102 }
1a4d82fc 1103 }
32a655c1
SL
1104 }
1105 clean::ImplTrait(ref bounds) => {
9fa01778 1106 if f.alternate() {
cdc7bbd5 1107 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
9fa01778 1108 } else {
cdc7bbd5 1109 write!(f, "impl {}", print_generic_bounds(bounds, cx))
9fa01778 1110 }
32a655c1 1111 }
f2b60f7d
FG
1112 clean::QPath(box clean::QPathData {
1113 ref assoc,
1114 ref self_type,
1115 ref trait_,
1116 should_show_cast,
1117 }) => {
32a655c1 1118 if f.alternate() {
7cac9316 1119 if should_show_cast {
cdc7bbd5 1120 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
8bb4bdeb 1121 } else {
cdc7bbd5 1122 write!(f, "{:#}::", self_type.print(cx))?
8bb4bdeb 1123 }
32a655c1 1124 } else {
7cac9316 1125 if should_show_cast {
cdc7bbd5 1126 write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
8bb4bdeb 1127 } else {
cdc7bbd5 1128 write!(f, "{}::", self_type.print(cx))?
cc61c64b
XL
1129 }
1130 };
c295e0f8
XL
1131 // It's pretty unsightly to look at `<A as B>::C` in output, and
1132 // we've got hyperlinking on our side, so try to avoid longer
1133 // notation as much as possible by making `C` a hyperlink to trait
1134 // `B` to disambiguate.
1135 //
1136 // FIXME: this is still a lossy conversion and there should probably
1137 // be a better way of representing this in general? Most of
1138 // the ugliness comes from inlining across crates where
1139 // everything comes in as a fully resolved QPath (hard to
1140 // look at).
353b0b11
FG
1141 if !f.alternate() && let Ok((url, _, path)) = href(trait_.def_id(), cx) {
1142 write!(
1143 f,
1144 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1145 title=\"type {path}::{name}\">{name}</a>",
1146 shortty = ItemType::AssocType,
1147 name = assoc.name,
1148 path = join_with_double_colon(&path),
1149 )
1150 } else {
1151 write!(f, "{}", assoc.name)
1152 }?;
1153
1154 // Carry `f.alternate()` into this display w/o branching manually.
1155 fmt::Display::fmt(&assoc.args.print(cx), f)
1a4d82fc 1156 }
32a655c1
SL
1157 }
1158}
1159
e74abb32 1160impl clean::Type {
923072b8 1161 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
cdc7bbd5
XL
1162 &'a self,
1163 cx: &'a Context<'tcx>,
1164 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1165 display_fn(move |f| fmt_type(self, f, false, cx))
1a4d82fc
JJ
1166 }
1167}
1168
c295e0f8 1169impl clean::Path {
923072b8 1170 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
c295e0f8
XL
1171 &'a self,
1172 cx: &'a Context<'tcx>,
1173 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1174 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1175 }
1176}
1177
e74abb32 1178impl clean::Impl {
923072b8 1179 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1180 &'a self,
1181 use_absolute: bool,
1182 cx: &'a Context<'tcx>,
1183 ) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32
XL
1184 display_fn(move |f| {
1185 if f.alternate() {
cdc7bbd5 1186 write!(f, "impl{:#} ", self.generics.print(cx))?;
e74abb32 1187 } else {
cdc7bbd5 1188 write!(f, "impl{} ", self.generics.print(cx))?;
e74abb32 1189 }
476ff2be 1190
e74abb32 1191 if let Some(ref ty) = self.trait_ {
3c0e092e
XL
1192 match self.polarity {
1193 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1194 ty::ImplPolarity::Negative => write!(f, "!")?,
a7813a04 1195 }
cdc7bbd5 1196 fmt::Display::fmt(&ty.print(cx), f)?;
e74abb32
XL
1197 write!(f, " for ")?;
1198 }
476ff2be 1199
923072b8
FG
1200 if let clean::Type::Tuple(types) = &self.for_ &&
1201 let [clean::Type::Generic(name)] = &types[..] &&
064997fb
FG
1202 (self.kind.is_fake_variadic() || self.kind.is_auto())
1203 {
923072b8
FG
1204 // Hardcoded anchor library/core/src/primitive_docs.rs
1205 // Link should match `# Trait implementations`
1206 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
064997fb
FG
1207 } else if let clean::BareFunction(bare_fn) = &self.for_ &&
1208 let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
1209 (self.kind.is_fake_variadic() || self.kind.is_auto())
1210 {
1211 // Hardcoded anchor library/core/src/primitive_docs.rs
1212 // Link should match `# Trait implementations`
1213
1214 let hrtb = bare_fn.print_hrtb_with_space(cx);
1215 let unsafety = bare_fn.unsafety.print_with_space();
1216 let abi = print_abi_with_space(bare_fn.abi);
1217 if f.alternate() {
1218 write!(
1219 f,
1220 "{hrtb:#}{unsafety}{abi:#}",
1221 )?;
1222 } else {
1223 write!(
1224 f,
1225 "{hrtb}{unsafety}{abi}",
1226 )?;
1227 }
1228 let ellipsis = if bare_fn.decl.c_variadic {
1229 ", ..."
1230 } else {
1231 ""
1232 };
1233 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
1234 // Write output.
1235 if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
1236 write!(f, " -> ")?;
1237 fmt_type(ty, f, use_absolute, cx)?;
1238 }
923072b8 1239 } else if let Some(ty) = self.kind.as_blanket_ty() {
cdc7bbd5 1240 fmt_type(ty, f, use_absolute, cx)?;
e74abb32 1241 } else {
cdc7bbd5 1242 fmt_type(&self.for_, f, use_absolute, cx)?;
e74abb32 1243 }
a7813a04 1244
064997fb 1245 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
e74abb32
XL
1246 Ok(())
1247 })
c1a9b12d
SL
1248 }
1249}
1250
e74abb32 1251impl clean::Arguments {
923072b8 1252 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1253 &'a self,
1254 cx: &'a Context<'tcx>,
1255 ) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32
XL
1256 display_fn(move |f| {
1257 for (i, input) in self.values.iter().enumerate() {
487cf647
FG
1258 write!(f, "{}: ", input.name)?;
1259
e74abb32 1260 if f.alternate() {
cdc7bbd5 1261 write!(f, "{:#}", input.type_.print(cx))?;
e74abb32 1262 } else {
cdc7bbd5 1263 write!(f, "{}", input.type_.print(cx))?;
e74abb32 1264 }
dfeec247
XL
1265 if i + 1 < self.values.len() {
1266 write!(f, ", ")?;
1267 }
c30ab7b3 1268 }
e74abb32
XL
1269 Ok(())
1270 })
1a4d82fc
JJ
1271 }
1272}
1273
74b04a01 1274impl clean::FnRetTy {
923072b8 1275 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1276 &'a self,
1277 cx: &'a Context<'tcx>,
1278 ) -> impl fmt::Display + 'a + Captures<'tcx> {
dfeec247
XL
1279 display_fn(move |f| match self {
1280 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
cdc7bbd5
XL
1281 clean::Return(ty) if f.alternate() => {
1282 write!(f, " -> {:#}", ty.print(cx))
1283 }
1284 clean::Return(ty) => write!(f, " -&gt; {}", ty.print(cx)),
dfeec247 1285 clean::DefaultReturn => Ok(()),
e74abb32 1286 })
1a4d82fc
JJ
1287 }
1288}
1289
e74abb32 1290impl clean::BareFunctionDecl {
cdc7bbd5
XL
1291 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1292 &'a self,
1293 cx: &'a Context<'tcx>,
1294 ) -> impl fmt::Display + 'a + Captures<'tcx> {
5869c6ff
XL
1295 display_fn(move |f| {
1296 if !self.generic_params.is_empty() {
c295e0f8
XL
1297 write!(
1298 f,
1299 "for&lt;{}&gt; ",
5e7ed085 1300 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
c295e0f8 1301 )
5869c6ff
XL
1302 } else {
1303 Ok(())
1304 }
1305 })
1a4d82fc
JJ
1306 }
1307}
1308
353b0b11
FG
1309// Implements Write but only counts the bytes "written".
1310struct WriteCounter(usize);
1311
1312impl std::fmt::Write for WriteCounter {
1313 fn write_str(&mut self, s: &str) -> fmt::Result {
1314 self.0 += s.len();
1315 Ok(())
1316 }
1317}
1318
1319// Implements Display by emitting the given number of spaces.
1320struct Indent(usize);
1321
1322impl fmt::Display for Indent {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 (0..self.0).for_each(|_| {
1325 f.write_char(' ').unwrap();
1326 });
1327 Ok(())
1328 }
1329}
1330
e74abb32 1331impl clean::FnDecl {
923072b8 1332 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
cdc7bbd5
XL
1333 &'a self,
1334 cx: &'a Context<'tcx>,
1335 ) -> impl fmt::Display + 'b + Captures<'tcx> {
e74abb32 1336 display_fn(move |f| {
dfeec247 1337 let ellipsis = if self.c_variadic { ", ..." } else { "" };
e74abb32 1338 if f.alternate() {
dfeec247
XL
1339 write!(
1340 f,
e74abb32 1341 "({args:#}{ellipsis}){arrow:#}",
cdc7bbd5 1342 args = self.inputs.print(cx),
dfeec247 1343 ellipsis = ellipsis,
cdc7bbd5 1344 arrow = self.output.print(cx)
dfeec247 1345 )
e74abb32 1346 } else {
dfeec247
XL
1347 write!(
1348 f,
e74abb32 1349 "({args}{ellipsis}){arrow}",
cdc7bbd5 1350 args = self.inputs.print(cx),
dfeec247 1351 ellipsis = ellipsis,
cdc7bbd5 1352 arrow = self.output.print(cx)
dfeec247 1353 )
cc61c64b 1354 }
e74abb32
XL
1355 })
1356 }
e74abb32 1357
cdc7bbd5
XL
1358 /// * `header_len`: The length of the function header and name. In other words, the number of
1359 /// characters in the function declaration up to but not including the parentheses.
9ffffee4
FG
1360 /// This is expected to go into a `<pre>`/`code-header` block, so indentation and newlines
1361 /// are preserved.
cdc7bbd5
XL
1362 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1363 /// necessary.
923072b8 1364 pub(crate) fn full_print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1365 &'a self,
1366 header_len: usize,
1367 indent: usize,
cdc7bbd5
XL
1368 cx: &'a Context<'tcx>,
1369 ) -> impl fmt::Display + 'a + Captures<'tcx> {
353b0b11
FG
1370 display_fn(move |f| {
1371 // First, generate the text form of the declaration, with no line wrapping, and count the bytes.
1372 let mut counter = WriteCounter(0);
1373 write!(&mut counter, "{:#}", display_fn(|f| { self.inner_full_print(None, f, cx) }))
1374 .unwrap();
1375 // If the text form was over 80 characters wide, we will line-wrap our output.
1376 let line_wrapping_indent =
1377 if header_len + counter.0 > 80 { Some(indent) } else { None };
1378 // Generate the final output. This happens to accept `{:#}` formatting to get textual
1379 // output but in practice it is only formatted with `{}` to get HTML output.
1380 self.inner_full_print(line_wrapping_indent, f, cx)
1381 })
cdc7bbd5 1382 }
cc61c64b 1383
cdc7bbd5
XL
1384 fn inner_full_print(
1385 &self,
353b0b11
FG
1386 // For None, the declaration will not be line-wrapped. For Some(n),
1387 // the declaration will be line-wrapped, with an indent of n spaces.
1388 line_wrapping_indent: Option<usize>,
cdc7bbd5
XL
1389 f: &mut fmt::Formatter<'_>,
1390 cx: &Context<'_>,
1391 ) -> fmt::Result {
1392 let amp = if f.alternate() { "&" } else { "&amp;" };
353b0b11
FG
1393
1394 write!(f, "(")?;
1395 if let Some(n) = line_wrapping_indent {
1396 write!(f, "\n{}", Indent(n + 4))?;
1397 }
cdc7bbd5 1398 for (i, input) in self.inputs.values.iter().enumerate() {
353b0b11
FG
1399 if i > 0 {
1400 match line_wrapping_indent {
1401 None => write!(f, ", ")?,
1402 Some(n) => write!(f, ",\n{}", Indent(n + 4))?,
1403 };
1404 }
cdc7bbd5
XL
1405 if let Some(selfty) = input.to_self() {
1406 match selfty {
1407 clean::SelfValue => {
353b0b11 1408 write!(f, "self")?;
c30ab7b3 1409 }
cdc7bbd5 1410 clean::SelfBorrowed(Some(ref lt), mtbl) => {
353b0b11 1411 write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?;
a7813a04 1412 }
cdc7bbd5 1413 clean::SelfBorrowed(None, mtbl) => {
353b0b11 1414 write!(f, "{}{}self", amp, mtbl.print_with_space())?;
a7813a04 1415 }
cdc7bbd5 1416 clean::SelfExplicit(ref typ) => {
353b0b11
FG
1417 write!(f, "self: ")?;
1418 fmt::Display::fmt(&typ.print(cx), f)?;
a7813a04
XL
1419 }
1420 }
cdc7bbd5 1421 } else {
a2a8927a 1422 if input.is_const {
353b0b11 1423 write!(f, "const ")?;
cdc7bbd5 1424 }
353b0b11
FG
1425 write!(f, "{}: ", input.name)?;
1426 fmt::Display::fmt(&input.type_.print(cx), f)?;
cdc7bbd5
XL
1427 }
1428 }
c30ab7b3 1429
cdc7bbd5 1430 if self.c_variadic {
353b0b11
FG
1431 match line_wrapping_indent {
1432 None => write!(f, ", ...")?,
1433 Some(n) => write!(f, "\n{}...", Indent(n + 4))?,
1434 };
cdc7bbd5 1435 }
c30ab7b3 1436
353b0b11
FG
1437 match line_wrapping_indent {
1438 None => write!(f, ")")?,
1439 Some(n) => write!(f, "\n{})", Indent(n))?,
cdc7bbd5
XL
1440 };
1441
353b0b11
FG
1442 fmt::Display::fmt(&self.output.print(cx), f)?;
1443 Ok(())
1a4d82fc
JJ
1444 }
1445}
1446
487cf647
FG
1447pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
1448 visibility: Option<ty::Visibility<DefId>>,
1449 item_did: ItemId,
1450 cx: &'a Context<'tcx>,
1451) -> impl fmt::Display + 'a + Captures<'tcx> {
1452 use std::fmt::Write as _;
1453
1454 let to_print: Cow<'static, str> = match visibility {
1455 None => "".into(),
1456 Some(ty::Visibility::Public) => "pub ".into(),
1457 Some(ty::Visibility::Restricted(vis_did)) => {
1458 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1459 // However, rustdoc currently never displays a module's
1460 // visibility, so it shouldn't matter.
1461 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1462
1463 if vis_did.is_crate_root() {
1464 "pub(crate) ".into()
1465 } else if parent_module == Some(vis_did) {
1466 // `pub(in foo)` where `foo` is the parent module
1467 // is the same as no visibility modifier
1468 "".into()
1469 } else if parent_module.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1470 == Some(vis_did)
1471 {
1472 "pub(super) ".into()
1473 } else {
1474 let path = cx.tcx().def_path(vis_did);
1475 debug!("path={:?}", path);
1476 // modified from `resolved_path()` to work with `DefPathData`
1477 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
353b0b11 1478 let anchor = anchor(vis_did, last_name, cx);
487cf647
FG
1479
1480 let mut s = "pub(in ".to_owned();
1481 for seg in &path.data[..path.data.len() - 1] {
1482 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
94b46f34 1483 }
487cf647
FG
1484 let _ = write!(s, "{}) ", anchor);
1485 s.into()
94b46f34 1486 }
487cf647
FG
1487 }
1488 };
1489 display_fn(move |f| write!(f, "{}", to_print))
1490}
cdc7bbd5 1491
487cf647
FG
1492/// This function is the same as print_with_space, except that it renders no links.
1493/// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1494/// any HTML in it.
1495pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
1496 visibility: Option<ty::Visibility<DefId>>,
1497 tcx: TyCtxt<'tcx>,
1498 item_did: DefId,
1499) -> impl fmt::Display + 'a + Captures<'tcx> {
353b0b11
FG
1500 let to_print: Cow<'static, str> = match visibility {
1501 None => "".into(),
1502 Some(ty::Visibility::Public) => "pub ".into(),
487cf647
FG
1503 Some(ty::Visibility::Restricted(vis_did)) => {
1504 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1505 // However, rustdoc currently never displays a module's
1506 // visibility, so it shouldn't matter.
1507 let parent_module = find_nearest_parent_module(tcx, item_did);
1508
1509 if vis_did.is_crate_root() {
353b0b11 1510 "pub(crate) ".into()
487cf647
FG
1511 } else if parent_module == Some(vis_did) {
1512 // `pub(in foo)` where `foo` is the parent module
1513 // is the same as no visibility modifier
353b0b11 1514 "".into()
487cf647
FG
1515 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1516 == Some(vis_did)
1517 {
353b0b11 1518 "pub(super) ".into()
487cf647 1519 } else {
353b0b11 1520 format!("pub(in {}) ", tcx.def_path_str(vis_did)).into()
cdc7bbd5 1521 }
487cf647
FG
1522 }
1523 };
1524 display_fn(move |f| f.write_str(&to_print))
1a4d82fc
JJ
1525}
1526
923072b8 1527pub(crate) trait PrintWithSpace {
e74abb32
XL
1528 fn print_with_space(&self) -> &str;
1529}
1530
1531impl PrintWithSpace for hir::Unsafety {
1532 fn print_with_space(&self) -> &str {
1533 match self {
1534 hir::Unsafety::Unsafe => "unsafe ",
dfeec247 1535 hir::Unsafety::Normal => "",
1a4d82fc
JJ
1536 }
1537 }
1538}
1539
e74abb32
XL
1540impl PrintWithSpace for hir::IsAsync {
1541 fn print_with_space(&self) -> &str {
1542 match self {
1543 hir::IsAsync::Async => "async ",
1544 hir::IsAsync::NotAsync => "",
8faf50e0
XL
1545 }
1546 }
1547}
1548
dfeec247
XL
1549impl PrintWithSpace for hir::Mutability {
1550 fn print_with_space(&self) -> &str {
1551 match self {
1552 hir::Mutability::Not => "",
1553 hir::Mutability::Mut => "mut ",
1554 }
1555 }
1556}
1557
923072b8
FG
1558pub(crate) fn print_constness_with_space(
1559 c: &hir::Constness,
1560 s: Option<ConstStability>,
1561) -> &'static str {
136023e0
XL
1562 match (c, s) {
1563 // const stable or when feature(staged_api) is not set
1564 (
1565 hir::Constness::Const,
1566 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1567 )
1568 | (hir::Constness::Const, None) => "const ",
1569 // const unstable or not const
1570 _ => "",
1571 }
1572}
1573
e74abb32 1574impl clean::Import {
923072b8 1575 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1576 &'a self,
1577 cx: &'a Context<'tcx>,
1578 ) -> impl fmt::Display + 'a + Captures<'tcx> {
29967ef6 1579 display_fn(move |f| match self.kind {
fc512014
XL
1580 clean::ImportKind::Simple(name) => {
1581 if name == self.source.path.last() {
cdc7bbd5 1582 write!(f, "use {};", self.source.print(cx))
dfeec247 1583 } else {
cdc7bbd5 1584 write!(f, "use {} as {};", self.source.print(cx), name)
1a4d82fc 1585 }
dfeec247 1586 }
29967ef6
XL
1587 clean::ImportKind::Glob => {
1588 if self.source.path.segments.is_empty() {
dfeec247
XL
1589 write!(f, "use *;")
1590 } else {
cdc7bbd5 1591 write!(f, "use {}::*;", self.source.print(cx))
041b39d2 1592 }
1a4d82fc 1593 }
e74abb32 1594 })
1a4d82fc
JJ
1595 }
1596}
1597
e74abb32 1598impl clean::ImportSource {
923072b8 1599 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1600 &'a self,
1601 cx: &'a Context<'tcx>,
1602 ) -> impl fmt::Display + 'a + Captures<'tcx> {
dfeec247 1603 display_fn(move |f| match self.did {
cdc7bbd5 1604 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
dfeec247 1605 _ => {
74b04a01
XL
1606 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1607 write!(f, "{}::", seg.name)?;
1608 }
a2a8927a 1609 let name = self.path.last();
74b04a01 1610 if let hir::def::Res::PrimTy(p) = self.path.res {
a2a8927a 1611 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
74b04a01
XL
1612 } else {
1613 write!(f, "{}", name)?;
1a4d82fc 1614 }
dfeec247 1615 Ok(())
1a4d82fc 1616 }
e74abb32 1617 })
1a4d82fc
JJ
1618 }
1619}
1620
e74abb32 1621impl clean::TypeBinding {
923072b8 1622 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1623 &'a self,
1624 cx: &'a Context<'tcx>,
1625 ) -> impl fmt::Display + 'a + Captures<'tcx> {
e74abb32 1626 display_fn(move |f| {
5e7ed085
FG
1627 f.write_str(self.assoc.name.as_str())?;
1628 if f.alternate() {
1629 write!(f, "{:#}", self.assoc.args.print(cx))?;
1630 } else {
1631 write!(f, "{}", self.assoc.args.print(cx))?;
1632 }
e74abb32 1633 match self.kind {
5099ac24 1634 clean::TypeBindingKind::Equality { ref term } => {
dc9dc135 1635 if f.alternate() {
5099ac24 1636 write!(f, " = {:#}", term.print(cx))?;
dc9dc135 1637 } else {
5099ac24 1638 write!(f, " = {}", term.print(cx))?;
e74abb32
XL
1639 }
1640 }
1641 clean::TypeBindingKind::Constraint { ref bounds } => {
1642 if !bounds.is_empty() {
1643 if f.alternate() {
cdc7bbd5 1644 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
e74abb32 1645 } else {
9ffffee4 1646 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
e74abb32 1647 }
dc9dc135
XL
1648 }
1649 }
1650 }
e74abb32
XL
1651 Ok(())
1652 })
1a4d82fc
JJ
1653 }
1654}
1655
923072b8 1656pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
e74abb32 1657 display_fn(move |f| {
c30ab7b3 1658 let quot = if f.alternate() { "\"" } else { "&quot;" };
e74abb32 1659 match abi {
9346a6ac 1660 Abi::Rust => Ok(()),
c30ab7b3 1661 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
9346a6ac 1662 }
e74abb32
XL
1663 })
1664}
1665
923072b8 1666pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
dfeec247 1667 if v { "default " } else { "" }
9346a6ac 1668}
532ac7d7 1669
e74abb32 1670impl clean::GenericArg {
923072b8 1671 pub(crate) fn print<'a, 'tcx: 'a>(
cdc7bbd5
XL
1672 &'a self,
1673 cx: &'a Context<'tcx>,
1674 ) -> impl fmt::Display + 'a + Captures<'tcx> {
dfeec247
XL
1675 display_fn(move |f| match self {
1676 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
cdc7bbd5
XL
1677 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1678 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
94222f64 1679 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
e74abb32 1680 })
532ac7d7
XL
1681 }
1682}
e1599b0c 1683
5099ac24 1684impl clean::types::Term {
923072b8 1685 pub(crate) fn print<'a, 'tcx: 'a>(
5099ac24
FG
1686 &'a self,
1687 cx: &'a Context<'tcx>,
1688 ) -> impl fmt::Display + 'a + Captures<'tcx> {
9c376795
FG
1689 display_fn(move |f| match self {
1690 clean::types::Term::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1691 clean::types::Term::Constant(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1692 })
5099ac24
FG
1693 }
1694}
1695
923072b8
FG
1696pub(crate) fn display_fn(
1697 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1698) -> impl fmt::Display {
5869c6ff
XL
1699 struct WithFormatter<F>(Cell<Option<F>>);
1700
1701 impl<F> fmt::Display for WithFormatter<F>
1702 where
1703 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1704 {
1705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1706 (self.0.take()).unwrap()(f)
1707 }
e1599b0c 1708 }
5869c6ff
XL
1709
1710 WithFormatter(Cell::new(Some(f)))
e1599b0c 1711}